diff --git a/examples/bridge-app/asr/subdevice/SubDeviceManager.cpp b/examples/bridge-app/asr/subdevice/SubDeviceManager.cpp index 3508068c4832c6..776c4e43490e04 100644 --- a/examples/bridge-app/asr/subdevice/SubDeviceManager.cpp +++ b/examples/bridge-app/asr/subdevice/SubDeviceManager.cpp @@ -156,8 +156,8 @@ Protocols::InteractionModel::Status HandleWriteOnOffAttribute(SubDevice * dev, c { ChipLogProgress(DeviceLayer, "HandleWriteOnOffAttribute: attrId=%" PRIu32, attributeId); - ReturnErrorCodeIf((attributeId != OnOff::Attributes::OnOff::Id) || (!dev->IsReachable()), - Protocols::InteractionModel::Status::Failure); + VerifyOrReturnError((attributeId == OnOff::Attributes::OnOff::Id) && dev->IsReachable(), + Protocols::InteractionModel::Status::Failure); dev->SetOnOff(*buffer == 1); return Protocols::InteractionModel::Status::Success; } diff --git a/examples/bridge-app/esp32/main/main.cpp b/examples/bridge-app/esp32/main/main.cpp index 016b75803cd69b..d1075385cec8c9 100644 --- a/examples/bridge-app/esp32/main/main.cpp +++ b/examples/bridge-app/esp32/main/main.cpp @@ -268,8 +268,8 @@ Protocols::InteractionModel::Status HandleWriteOnOffAttribute(Device * dev, chip { ChipLogProgress(DeviceLayer, "HandleWriteOnOffAttribute: attrId=%" PRIu32, attributeId); - ReturnErrorCodeIf((attributeId != OnOff::Attributes::OnOff::Id) || (!dev->IsReachable()), - Protocols::InteractionModel::Status::Failure); + VerifyOrReturnError((attributeId == OnOff::Attributes::OnOff::Id) && dev->IsReachable(), + Protocols::InteractionModel::Status::Failure); dev->SetOnOff(*buffer == 1); return Protocols::InteractionModel::Status::Success; } diff --git a/examples/bridge-app/telink/src/AppTask.cpp b/examples/bridge-app/telink/src/AppTask.cpp index e080e40eb5dda9..79644c2860ae21 100644 --- a/examples/bridge-app/telink/src/AppTask.cpp +++ b/examples/bridge-app/telink/src/AppTask.cpp @@ -298,8 +298,8 @@ Protocols::InteractionModel::Status HandleWriteOnOffAttribute(Device * dev, chip { ChipLogProgress(DeviceLayer, "HandleWriteOnOffAttribute: attrId=%" PRIu32, attributeId); - ReturnErrorCodeIf((attributeId != Clusters::OnOff::Attributes::OnOff::Id) || (!dev->IsReachable()), - Protocols::InteractionModel::Status::Failure); + VerifyOrReturnError((attributeId == Clusters::OnOff::Attributes::OnOff::Id) && dev->IsReachable(), + Protocols::InteractionModel::Status::Failure); dev->SetOnOff(*buffer == 1); return Protocols::InteractionModel::Status::Success; } diff --git a/examples/chip-tool/commands/delay/WaitForCommissioneeCommand.cpp b/examples/chip-tool/commands/delay/WaitForCommissioneeCommand.cpp index 486e9f1204f2b5..2634c78e99a503 100644 --- a/examples/chip-tool/commands/delay/WaitForCommissioneeCommand.cpp +++ b/examples/chip-tool/commands/delay/WaitForCommissioneeCommand.cpp @@ -23,7 +23,7 @@ using namespace chip; CHIP_ERROR WaitForCommissioneeCommand::RunCommand() { chip::FabricIndex fabricIndex = CurrentCommissioner().GetFabricIndex(); - ReturnErrorCodeIf(fabricIndex == chip::kUndefinedFabricIndex, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(fabricIndex != chip::kUndefinedFabricIndex, CHIP_ERROR_INCORRECT_STATE); if (mExpireExistingSession.ValueOr(true)) { diff --git a/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseTargetsStore.cpp b/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseTargetsStore.cpp index f15e0b7a109817..2144219409bc5f 100644 --- a/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseTargetsStore.cpp +++ b/examples/energy-management-app/energy-management-common/energy-evse/src/EnergyEvseTargetsStore.cpp @@ -75,7 +75,7 @@ CHIP_ERROR EvseTargetsDelegate::LoadTargets() Platform::ScopedMemoryBuffer backingBuffer; uint16_t length = GetTlvSizeUpperBound(); - ReturnErrorCodeIf(!backingBuffer.Calloc(length), CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(backingBuffer.Calloc(length), CHIP_ERROR_NO_MEMORY); CHIP_ERROR err = mpTargetStore->SyncGetKeyValue(spEvseTargetsKeyName, backingBuffer.Get(), length); if (err == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND) @@ -390,7 +390,7 @@ EvseTargetsDelegate::SaveTargets(DataModel::List backingBuffer; - ReturnErrorCodeIf(!backingBuffer.Calloc(total), CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(backingBuffer.Calloc(total), CHIP_ERROR_NO_MEMORY); TLV::ScopedBufferTLVWriter writer(std::move(backingBuffer), total); TLV::TLVType arrayType; diff --git a/examples/persistent-storage/KeyValueStorageTest.cpp b/examples/persistent-storage/KeyValueStorageTest.cpp index 5aab299dc014ac..0f688c4f07f6ac 100644 --- a/examples/persistent-storage/KeyValueStorageTest.cpp +++ b/examples/persistent-storage/KeyValueStorageTest.cpp @@ -55,8 +55,8 @@ CHIP_ERROR TestEmptyString() size_t read_size; ReturnErrorOnFailure(KeyValueStoreMgr().Put(kTestKey, kTestValue)); ReturnErrorOnFailure(KeyValueStoreMgr().Get(kTestKey, read_value, sizeof(read_value), &read_size)); - ReturnErrorCodeIf(strcmp(kTestValue, read_value) != 0, CHIP_ERROR_INTERNAL); - ReturnErrorCodeIf(read_size != sizeof(kTestValue), CHIP_ERROR_INTERNAL); + VerifyOrReturnError(strcmp(kTestValue, read_value) == 0, CHIP_ERROR_INTERNAL); + VerifyOrReturnError(read_size == sizeof(kTestValue), CHIP_ERROR_INTERNAL); ReturnErrorOnFailure(KeyValueStoreMgr().Delete(kTestKey)); return CHIP_NO_ERROR; } @@ -69,8 +69,8 @@ CHIP_ERROR TestString() size_t read_size; ReturnErrorOnFailure(KeyValueStoreMgr().Put(kTestKey, kTestValue)); ReturnErrorOnFailure(KeyValueStoreMgr().Get(kTestKey, read_value, sizeof(read_value), &read_size)); - ReturnErrorCodeIf(strcmp(kTestValue, read_value) != 0, CHIP_ERROR_INTERNAL); - ReturnErrorCodeIf(read_size != sizeof(kTestValue), CHIP_ERROR_INTERNAL); + VerifyOrReturnError(strcmp(kTestValue, read_value) == 0, CHIP_ERROR_INTERNAL); + VerifyOrReturnError(read_size == sizeof(kTestValue), CHIP_ERROR_INTERNAL); ReturnErrorOnFailure(KeyValueStoreMgr().Delete(kTestKey)); return CHIP_NO_ERROR; } @@ -82,7 +82,7 @@ CHIP_ERROR TestUint32() uint32_t read_value; ReturnErrorOnFailure(KeyValueStoreMgr().Put(kTestKey, kTestValue)); ReturnErrorOnFailure(KeyValueStoreMgr().Get(kTestKey, &read_value)); - ReturnErrorCodeIf(kTestValue != read_value, CHIP_ERROR_INTERNAL); + VerifyOrReturnError(kTestValue == read_value, CHIP_ERROR_INTERNAL); ReturnErrorOnFailure(KeyValueStoreMgr().Delete(kTestKey)); return CHIP_NO_ERROR; } @@ -94,7 +94,7 @@ CHIP_ERROR TestArray() uint32_t read_value[5]; ReturnErrorOnFailure(KeyValueStoreMgr().Put(kTestKey, kTestValue)); ReturnErrorOnFailure(KeyValueStoreMgr().Get(kTestKey, &read_value)); - ReturnErrorCodeIf(memcmp(kTestValue, read_value, sizeof(kTestValue)) != 0, CHIP_ERROR_INTERNAL); + VerifyOrReturnError(memcmp(kTestValue, read_value, sizeof(kTestValue)) == 0, CHIP_ERROR_INTERNAL); ReturnErrorOnFailure(KeyValueStoreMgr().Delete(kTestKey)); return CHIP_NO_ERROR; } @@ -111,8 +111,8 @@ CHIP_ERROR TestStruct() SomeStruct read_value; ReturnErrorOnFailure(KeyValueStoreMgr().Put(kTestKey, kTestValue)); ReturnErrorOnFailure(KeyValueStoreMgr().Get(kTestKey, &read_value)); - ReturnErrorCodeIf(kTestValue.value1 != read_value.value1, CHIP_ERROR_INTERNAL); - ReturnErrorCodeIf(kTestValue.value2 != read_value.value2, CHIP_ERROR_INTERNAL); + VerifyOrReturnError(kTestValue.value1 == read_value.value1, CHIP_ERROR_INTERNAL); + VerifyOrReturnError(kTestValue.value2 == read_value.value2, CHIP_ERROR_INTERNAL); ReturnErrorOnFailure(KeyValueStoreMgr().Delete(kTestKey)); return CHIP_NO_ERROR; } @@ -125,7 +125,7 @@ CHIP_ERROR TestUpdateValue() { ReturnErrorOnFailure(KeyValueStoreMgr().Put(kTestKey, i)); ReturnErrorOnFailure(KeyValueStoreMgr().Get(kTestKey, &read_value)); - ReturnErrorCodeIf(i != read_value, CHIP_ERROR_INTERNAL); + VerifyOrReturnError(i == read_value, CHIP_ERROR_INTERNAL); } ReturnErrorOnFailure(KeyValueStoreMgr().Delete(kTestKey)); return CHIP_NO_ERROR; @@ -142,9 +142,9 @@ CHIP_ERROR TestMultiRead() size_t read_size; // Returns buffer too small for all but the last read. CHIP_ERROR error = KeyValueStoreMgr().Get(kTestKey, &read_value, sizeof(read_value), &read_size, i * sizeof(uint32_t)); - ReturnErrorCodeIf(error != (i < 4 ? CHIP_ERROR_BUFFER_TOO_SMALL : CHIP_NO_ERROR), error); - ReturnErrorCodeIf(read_size != sizeof(read_value), CHIP_ERROR_INTERNAL); - ReturnErrorCodeIf(kTestValue[i] != read_value, CHIP_ERROR_INTERNAL); + VerifyOrReturnError(error == (i < 4 ? CHIP_ERROR_BUFFER_TOO_SMALL : CHIP_NO_ERROR), error); + VerifyOrReturnError(read_size == sizeof(read_value), CHIP_ERROR_INTERNAL); + VerifyOrReturnError(kTestValue[i] == read_value, CHIP_ERROR_INTERNAL); } ReturnErrorOnFailure(KeyValueStoreMgr().Delete(kTestKey)); return CHIP_NO_ERROR; diff --git a/examples/platform/cc13x4_26x4/CC13X4_26X4DeviceAttestationCreds.cpp b/examples/platform/cc13x4_26x4/CC13X4_26X4DeviceAttestationCreds.cpp index 2cd36b6a14e93f..18b5890e9d156e 100644 --- a/examples/platform/cc13x4_26x4/CC13X4_26X4DeviceAttestationCreds.cpp +++ b/examples/platform/cc13x4_26x4/CC13X4_26X4DeviceAttestationCreds.cpp @@ -218,8 +218,8 @@ CHIP_ERROR DeviceAttestationCredsCC13X4_26X4::GetFirmwareInformation(MutableByte CHIP_ERROR DeviceAttestationCredsCC13X4_26X4::GetDeviceAttestationCert(MutableByteSpan & out_buffer) { - ReturnErrorCodeIf(out_buffer.size() < mFactoryData->dac_cert.len, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!mFactoryData->dac_cert.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(out_buffer.size() >= mFactoryData->dac_cert.len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData->dac_cert.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); return CopySpanToMutableSpan(ByteSpan{ mFactoryData->dac_cert.data, mFactoryData->dac_cert.len }, out_buffer); return CHIP_NO_ERROR; @@ -227,8 +227,8 @@ CHIP_ERROR DeviceAttestationCredsCC13X4_26X4::GetDeviceAttestationCert(MutableBy CHIP_ERROR DeviceAttestationCredsCC13X4_26X4::GetProductAttestationIntermediateCert(MutableByteSpan & out_buffer) { - ReturnErrorCodeIf(out_buffer.size() < mFactoryData->pai_cert.len, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!mFactoryData->pai_cert.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(out_buffer.size() >= mFactoryData->pai_cert.len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData->pai_cert.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); return CopySpanToMutableSpan(ByteSpan{ mFactoryData->pai_cert.data, mFactoryData->pai_cert.len }, out_buffer); } diff --git a/examples/platform/cc32xx/CC32XXDeviceAttestationCreds.cpp b/examples/platform/cc32xx/CC32XXDeviceAttestationCreds.cpp index 0323e3b7ed39b1..2e85c0b69a3b25 100644 --- a/examples/platform/cc32xx/CC32XXDeviceAttestationCreds.cpp +++ b/examples/platform/cc32xx/CC32XXDeviceAttestationCreds.cpp @@ -349,8 +349,8 @@ CHIP_ERROR DeviceAttestationCredsCC32XX::GetFirmwareInformation(MutableByteSpan CHIP_ERROR DeviceAttestationCredsCC32XX::GetDeviceAttestationCert(MutableByteSpan & out_buffer) { - ReturnErrorCodeIf(out_buffer.size() < mFactoryData->dac_cert.len, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!mFactoryData->dac_cert.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(out_buffer.size() >= mFactoryData->dac_cert.len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData->dac_cert.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); return CopySpanToMutableSpan(ByteSpan{ mFactoryData->dac_cert.data, mFactoryData->dac_cert.len }, out_buffer); return CHIP_NO_ERROR; @@ -358,8 +358,8 @@ CHIP_ERROR DeviceAttestationCredsCC32XX::GetDeviceAttestationCert(MutableByteSpa CHIP_ERROR DeviceAttestationCredsCC32XX::GetProductAttestationIntermediateCert(MutableByteSpan & out_buffer) { - ReturnErrorCodeIf(out_buffer.size() < mFactoryData->pai_cert.len, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!mFactoryData->pai_cert.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(out_buffer.size() >= mFactoryData->pai_cert.len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData->pai_cert.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); return CopySpanToMutableSpan(ByteSpan{ mFactoryData->pai_cert.data, mFactoryData->pai_cert.len }, out_buffer); } diff --git a/examples/platform/silabs/SiWx917/SiWx917/sl_wifi_if.cpp b/examples/platform/silabs/SiWx917/SiWx917/sl_wifi_if.cpp index 9dd91a44061799..d3572289eb7f30 100644 --- a/examples/platform/silabs/SiWx917/SiWx917/sl_wifi_if.cpp +++ b/examples/platform/silabs/SiWx917/SiWx917/sl_wifi_if.cpp @@ -619,7 +619,7 @@ static void wfx_rsi_save_ap_info(void) // translation **********************************************************************************************/ static sl_status_t wfx_rsi_do_join(void) { - ReturnErrorCodeIf((wfx_rsi.dev_state & (WFX_RSI_ST_STA_CONNECTING | WFX_RSI_ST_STA_CONNECTED)), SL_STATUS_IN_PROGRESS); + VerifyOrReturnError(!(wfx_rsi.dev_state & (WFX_RSI_ST_STA_CONNECTING | WFX_RSI_ST_STA_CONNECTED)), SL_STATUS_IN_PROGRESS); sl_status_t status = SL_STATUS_OK; sl_wifi_client_configuration_t ap; memset(&ap, 0, sizeof(ap)); @@ -680,7 +680,7 @@ static sl_status_t wfx_rsi_do_join(void) status = sl_wifi_connect(SL_WIFI_CLIENT_INTERFACE, &ap, timeout_ms); // sl_wifi_connect returns SL_STATUS_IN_PROGRESS if join is in progress // after the initial scan is done, the scan does not check for SSID - ReturnErrorCodeIf((status == SL_STATUS_OK || status == SL_STATUS_IN_PROGRESS), status); + VerifyOrReturnError(status != SL_STATUS_OK && status != SL_STATUS_IN_PROGRESS, status); // failure only happens when the firmware returns an error ChipLogError(DeviceLayer, "wfx_rsi_do_join: sl_wifi_connect failed: 0x%lx", static_cast(status)); diff --git a/examples/platform/silabs/provision/ProvisionStorageFlash.cpp b/examples/platform/silabs/provision/ProvisionStorageFlash.cpp index af59d6560cd0fc..abca012e361b13 100644 --- a/examples/platform/silabs/provision/ProvisionStorageFlash.cpp +++ b/examples/platform/silabs/provision/ProvisionStorageFlash.cpp @@ -78,7 +78,7 @@ CHIP_ERROR DecodeTotal(Encoding::Buffer & reader, uint16_t & total) ReturnErrorOnFailure(reader.Get(sz)); total = (0xffff == sz) ? sizeof(uint16_t) : sz; reader.in = reader.begin + total; - ReturnErrorCodeIf(reader.in > reader.end, CHIP_ERROR_INTERNAL); + VerifyOrReturnError(reader.in <= reader.end, CHIP_ERROR_INTERNAL); return CHIP_NO_ERROR; } @@ -118,7 +118,7 @@ CHIP_ERROR Set(uint16_t id, Encoding::Buffer & in) { // New entry size_t temp_total = found.offset; - ReturnErrorCodeIf(temp_total + in.Size() > kPageSize, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(temp_total + in.Size() <= kPageSize, CHIP_ERROR_INVALID_ARGUMENT); // Copy entry ReturnErrorOnFailure(in.Get(page + temp_total, in.Size())); // Update total @@ -138,7 +138,7 @@ CHIP_ERROR Set(uint16_t id, Encoding::Buffer & in) { // Size change, move to the end uint16_t temp_total = total - found.encoded_size; - ReturnErrorCodeIf(temp_total + in.Size() > kPageSize, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(temp_total + in.Size() <= kPageSize, CHIP_ERROR_INVALID_ARGUMENT); // Remove the entry memmove(page + found.offset, page + found.offset + found.encoded_size, temp_total); // Add the entry diff --git a/examples/tv-casting-app/tv-casting-common/include/MediaCommandBase.h b/examples/tv-casting-app/tv-casting-common/include/MediaCommandBase.h index 87ddf70ef2effd..d3d03b1a2402fb 100644 --- a/examples/tv-casting-app/tv-casting-common/include/MediaCommandBase.h +++ b/examples/tv-casting-app/tv-casting-common/include/MediaCommandBase.h @@ -32,7 +32,7 @@ class MediaCommandBase : public MediaBase VerifyOrDieWithMsg(mTargetVideoPlayerInfo != nullptr, AppServer, "Target unknown"); auto deviceProxy = mTargetVideoPlayerInfo->GetOperationalDeviceProxy(); - ReturnErrorCodeIf(deviceProxy == nullptr || !deviceProxy->ConnectionReady(), CHIP_ERROR_PEER_NODE_NOT_FOUND); + VerifyOrReturnError(deviceProxy != nullptr && deviceProxy->ConnectionReady(), CHIP_ERROR_PEER_NODE_NOT_FOUND); sResponseCallback = responseCallback; diff --git a/examples/tv-casting-app/tv-casting-common/include/MediaReadBase.h b/examples/tv-casting-app/tv-casting-common/include/MediaReadBase.h index e7e99e3d7ec662..ba896739d6d5b0 100644 --- a/examples/tv-casting-app/tv-casting-common/include/MediaReadBase.h +++ b/examples/tv-casting-app/tv-casting-common/include/MediaReadBase.h @@ -32,7 +32,7 @@ class MediaReadBase : public MediaBase VerifyOrDieWithMsg(mTargetVideoPlayerInfo != nullptr, AppServer, "Target unknown"); auto deviceProxy = mTargetVideoPlayerInfo->GetOperationalDeviceProxy(); - ReturnErrorCodeIf(deviceProxy == nullptr || !deviceProxy->ConnectionReady(), CHIP_ERROR_PEER_NODE_NOT_FOUND); + VerifyOrReturnError(deviceProxy != nullptr && deviceProxy->ConnectionReady(), CHIP_ERROR_PEER_NODE_NOT_FOUND); MediaClusterBase cluster(*deviceProxy->GetExchangeManager(), deviceProxy->GetSecureSession().Value(), mTvEndpoint); diff --git a/examples/tv-casting-app/tv-casting-common/include/MediaSubscriptionBase.h b/examples/tv-casting-app/tv-casting-common/include/MediaSubscriptionBase.h index 65b91b175f7b9d..caf6e5da71b39f 100644 --- a/examples/tv-casting-app/tv-casting-common/include/MediaSubscriptionBase.h +++ b/examples/tv-casting-app/tv-casting-common/include/MediaSubscriptionBase.h @@ -33,7 +33,7 @@ class MediaSubscriptionBase : public MediaBase VerifyOrDieWithMsg(mTargetVideoPlayerInfo != nullptr, AppServer, "Target unknown"); auto deviceProxy = mTargetVideoPlayerInfo->GetOperationalDeviceProxy(); - ReturnErrorCodeIf(deviceProxy == nullptr || !deviceProxy->ConnectionReady(), CHIP_ERROR_PEER_NODE_NOT_FOUND); + VerifyOrReturnError(deviceProxy != nullptr && deviceProxy->ConnectionReady(), CHIP_ERROR_PEER_NODE_NOT_FOUND); MediaClusterBase cluster(*deviceProxy->GetExchangeManager(), deviceProxy->GetSecureSession().Value(), mTvEndpoint); diff --git a/src/access/AccessControl.cpp b/src/access/AccessControl.cpp index c9da05e51038cc..ba149a6a225b54 100644 --- a/src/access/AccessControl.cpp +++ b/src/access/AccessControl.cpp @@ -232,7 +232,7 @@ CHIP_ERROR AccessControl::CreateEntry(const SubjectDescriptor * subjectDescripto VerifyOrReturnError((count + 1) <= maxCount, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!IsValid(entry), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(IsValid(entry), CHIP_ERROR_INVALID_ARGUMENT); size_t i = 0; ReturnErrorOnFailure(mDelegate->CreateEntry(&i, entry, &fabric)); @@ -250,7 +250,7 @@ CHIP_ERROR AccessControl::UpdateEntry(const SubjectDescriptor * subjectDescripto const Entry & entry) { VerifyOrReturnError(IsInitialized(), CHIP_ERROR_INCORRECT_STATE); - ReturnErrorCodeIf(!IsValid(entry), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(IsValid(entry), CHIP_ERROR_INVALID_ARGUMENT); ReturnErrorOnFailure(mDelegate->UpdateEntry(index, entry, &fabric)); NotifyEntryChanged(subjectDescriptor, fabric, index, &entry, EntryListener::ChangeType::kUpdated); return CHIP_NO_ERROR; diff --git a/src/access/AccessControl.h b/src/access/AccessControl.h index df986864b8ff4c..638c8d71f8f50a 100644 --- a/src/access/AccessControl.h +++ b/src/access/AccessControl.h @@ -501,7 +501,7 @@ class AccessControl */ CHIP_ERROR CreateEntry(size_t * index, const Entry & entry, FabricIndex * fabricIndex = nullptr) { - ReturnErrorCodeIf(!IsValid(entry), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(IsValid(entry), CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(IsInitialized(), CHIP_ERROR_INCORRECT_STATE); return mDelegate->CreateEntry(index, entry, fabricIndex); } @@ -551,7 +551,7 @@ class AccessControl */ CHIP_ERROR UpdateEntry(size_t index, const Entry & entry, const FabricIndex * fabricIndex = nullptr) { - ReturnErrorCodeIf(!IsValid(entry), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(IsValid(entry), CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(IsInitialized(), CHIP_ERROR_INCORRECT_STATE); return mDelegate->UpdateEntry(index, entry, fabricIndex); } diff --git a/src/access/examples/ExampleAccessControlDelegate.cpp b/src/access/examples/ExampleAccessControlDelegate.cpp index fc1c1b710deba4..9297740bf889ee 100644 --- a/src/access/examples/ExampleAccessControlDelegate.cpp +++ b/src/access/examples/ExampleAccessControlDelegate.cpp @@ -909,7 +909,7 @@ CHIP_ERROR CopyViaInterface(const Entry & entry, EntryStorage & storage) size_t subjectCount = 0; ReturnErrorOnFailure(entry.GetSubjectCount(subjectCount)); - ReturnErrorCodeIf(subjectCount > EntryStorage::kMaxSubjects, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(subjectCount <= EntryStorage::kMaxSubjects, CHIP_ERROR_BUFFER_TOO_SMALL); for (size_t i = 0; i < subjectCount; ++i) { NodeId subject = kUndefinedNodeId; @@ -919,7 +919,7 @@ CHIP_ERROR CopyViaInterface(const Entry & entry, EntryStorage & storage) size_t targetCount = 0; ReturnErrorOnFailure(entry.GetTargetCount(targetCount)); - ReturnErrorCodeIf(targetCount > EntryStorage::kMaxTargets, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(targetCount <= EntryStorage::kMaxTargets, CHIP_ERROR_BUFFER_TOO_SMALL); for (size_t i = 0; i < targetCount; ++i) { Target target; diff --git a/src/access/tests/TestAccessControl.cpp b/src/access/tests/TestAccessControl.cpp index 00b95baf39164b..b528d4a3bc3b79 100644 --- a/src/access/tests/TestAccessControl.cpp +++ b/src/access/tests/TestAccessControl.cpp @@ -662,30 +662,30 @@ CHIP_ERROR CompareEntry(const Entry & entry, const EntryData & entryData) { AuthMode authMode = AuthMode::kNone; ReturnErrorOnFailure(entry.GetAuthMode(authMode)); - ReturnErrorCodeIf(authMode != entryData.authMode, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(authMode == entryData.authMode, CHIP_ERROR_INCORRECT_STATE); FabricIndex fabricIndex = kUndefinedFabricIndex; ReturnErrorOnFailure(entry.GetFabricIndex(fabricIndex)); - ReturnErrorCodeIf(fabricIndex != entryData.fabricIndex, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(fabricIndex == entryData.fabricIndex, CHIP_ERROR_INCORRECT_STATE); Privilege privilege = Privilege::kView; ReturnErrorOnFailure(entry.GetPrivilege(privilege)); - ReturnErrorCodeIf(privilege != entryData.privilege, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(privilege == entryData.privilege, CHIP_ERROR_INCORRECT_STATE); size_t subjectCount = 0; ReturnErrorOnFailure(entry.GetSubjectCount(subjectCount)); - ReturnErrorCodeIf(subjectCount != entryData.GetSubjectCount(), CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(subjectCount == entryData.GetSubjectCount(), CHIP_ERROR_INCORRECT_STATE); for (size_t i = 0; i < subjectCount; ++i) { NodeId subject = kUndefinedNodeId; ReturnErrorOnFailure(entry.GetSubject(i, subject)); - ReturnErrorCodeIf(subject != entryData.subjects[i], CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(subject == entryData.subjects[i], CHIP_ERROR_INCORRECT_STATE); } size_t targetCount = 0; ReturnErrorOnFailure(entry.GetTargetCount(targetCount)); - ReturnErrorCodeIf(targetCount != entryData.GetTargetCount(), CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(targetCount == entryData.GetTargetCount(), CHIP_ERROR_INCORRECT_STATE); for (size_t i = 0; i < targetCount; ++i) { Target target; ReturnErrorOnFailure(entry.GetTarget(i, target)); - ReturnErrorCodeIf(target != entryData.targets[i], CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(target == entryData.targets[i], CHIP_ERROR_INCORRECT_STATE); } return CHIP_NO_ERROR; } @@ -724,7 +724,7 @@ CHIP_ERROR CompareAccessControl(AccessControl & ac, const EntryData * entryData, ReturnErrorOnFailure(ac.ReadEntry(i, entry)); ReturnErrorOnFailure(CompareEntry(entry, *entryData)); } - ReturnErrorCodeIf(ac.ReadEntry(count, entry) == CHIP_NO_ERROR, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(ac.ReadEntry(count, entry) != CHIP_NO_ERROR, CHIP_ERROR_INCORRECT_STATE); return CHIP_NO_ERROR; } diff --git a/src/app/CASEClient.h b/src/app/CASEClient.h index 7ef968d544165f..2cb43498f6de22 100644 --- a/src/app/CASEClient.h +++ b/src/app/CASEClient.h @@ -44,10 +44,10 @@ struct CASEClientInitParams { // sessionResumptionStorage can be nullptr when resumption is disabled. // certificateValidityPolicy is optional, too. - ReturnErrorCodeIf(sessionManager == nullptr, CHIP_ERROR_INCORRECT_STATE); - ReturnErrorCodeIf(exchangeMgr == nullptr, CHIP_ERROR_INCORRECT_STATE); - ReturnErrorCodeIf(fabricTable == nullptr, CHIP_ERROR_INCORRECT_STATE); - ReturnErrorCodeIf(groupDataProvider == nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(sessionManager != nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(exchangeMgr != nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(fabricTable != nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(groupDataProvider != nullptr, CHIP_ERROR_INCORRECT_STATE); return CHIP_NO_ERROR; } diff --git a/src/app/CASESessionManager.cpp b/src/app/CASESessionManager.cpp index fa22748a50feff..766e60115df829 100644 --- a/src/app/CASESessionManager.cpp +++ b/src/app/CASESessionManager.cpp @@ -146,7 +146,7 @@ CHIP_ERROR CASESessionManager::GetPeerAddress(const ScopedNodeId & peerId, Trans { ReturnErrorOnFailure(mConfig.sessionInitParams.Validate()); auto optionalSessionHandle = FindExistingSession(peerId, transportPayloadCapability); - ReturnErrorCodeIf(!optionalSessionHandle.HasValue(), CHIP_ERROR_NOT_CONNECTED); + VerifyOrReturnError(optionalSessionHandle.HasValue(), CHIP_ERROR_NOT_CONNECTED); addr = optionalSessionHandle.Value()->AsSecureSession()->GetPeerAddress(); return CHIP_NO_ERROR; } diff --git a/src/app/DeferredAttributePersistenceProvider.cpp b/src/app/DeferredAttributePersistenceProvider.cpp index 9480fba14e9c8e..26adcb18c8dcf7 100644 --- a/src/app/DeferredAttributePersistenceProvider.cpp +++ b/src/app/DeferredAttributePersistenceProvider.cpp @@ -28,7 +28,7 @@ CHIP_ERROR DeferredAttribute::PrepareWrite(System::Clock::Timestamp flushTime, c if (mValue.AllocatedSize() != value.size()) { mValue.Alloc(value.size()); - ReturnErrorCodeIf(!mValue, CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(mValue, CHIP_ERROR_NO_MEMORY); } memcpy(mValue.Get(), value.data(), value.size()); diff --git a/src/app/EventManagement.cpp b/src/app/EventManagement.cpp index 271f72ec107f3b..4c01bedf4b9a5b 100644 --- a/src/app/EventManagement.cpp +++ b/src/app/EventManagement.cpp @@ -563,9 +563,9 @@ CHIP_ERROR EventManagement::CheckEventContext(EventLoadOutContext * eventLoadOut Access::GetAccessControl().Check(eventLoadOutContext->mSubjectDescriptor, requestPath, requestPrivilege); if (accessControlError != CHIP_NO_ERROR) { - ReturnErrorCodeIf((accessControlError != CHIP_ERROR_ACCESS_DENIED) && - (accessControlError != CHIP_ERROR_ACCESS_RESTRICTED_BY_ARL), - accessControlError); + VerifyOrReturnError((accessControlError == CHIP_ERROR_ACCESS_DENIED) || + (accessControlError == CHIP_ERROR_ACCESS_RESTRICTED_BY_ARL), + accessControlError); ret = CHIP_ERROR_UNEXPECTED_EVENT; } diff --git a/src/app/InteractionModelEngine.cpp b/src/app/InteractionModelEngine.cpp index 6f326b5fdb4842..269cc7f9158ee3 100644 --- a/src/app/InteractionModelEngine.cpp +++ b/src/app/InteractionModelEngine.cpp @@ -756,8 +756,8 @@ Protocols::InteractionModel::Status InteractionModelEngine::OnReadInitialRequest { TLV::TLVReader pathReader; attributePathListParser.GetReader(&pathReader); - ReturnErrorCodeIf(TLV::Utilities::Count(pathReader, requestedAttributePathCount, false) != CHIP_NO_ERROR, - Status::InvalidAction); + VerifyOrReturnError(TLV::Utilities::Count(pathReader, requestedAttributePathCount, false) == CHIP_NO_ERROR, + Status::InvalidAction); } else if (err != CHIP_ERROR_END_OF_TLV) { @@ -769,8 +769,8 @@ Protocols::InteractionModel::Status InteractionModelEngine::OnReadInitialRequest { TLV::TLVReader pathReader; eventpathListParser.GetReader(&pathReader); - ReturnErrorCodeIf(TLV::Utilities::Count(pathReader, requestedEventPathCount, false) != CHIP_NO_ERROR, - Status::InvalidAction); + VerifyOrReturnError(TLV::Utilities::Count(pathReader, requestedEventPathCount, false) == CHIP_NO_ERROR, + Status::InvalidAction); } else if (err != CHIP_ERROR_END_OF_TLV) { @@ -1988,9 +1988,9 @@ void InteractionModelEngine::OnFabricRemoved(const FabricTable & fabricTable, Fa CHIP_ERROR InteractionModelEngine::ResumeSubscriptions() { #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS - ReturnErrorCodeIf(!mpSubscriptionResumptionStorage, CHIP_NO_ERROR); + VerifyOrReturnError(mpSubscriptionResumptionStorage, CHIP_NO_ERROR); #if CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION - ReturnErrorCodeIf(mSubscriptionResumptionScheduled, CHIP_NO_ERROR); + VerifyOrReturnError(!mSubscriptionResumptionScheduled, CHIP_NO_ERROR); #endif // To avoid the case of a reboot loop causing rapid traffic generation / power consumption, subscription resumption should make diff --git a/src/app/OperationalSessionSetup.cpp b/src/app/OperationalSessionSetup.cpp index a0af8fa3d00ecf..6b9b894314bd81 100644 --- a/src/app/OperationalSessionSetup.cpp +++ b/src/app/OperationalSessionSetup.cpp @@ -318,7 +318,7 @@ CHIP_ERROR OperationalSessionSetup::EstablishConnection(const ResolveResult & re #endif mCASEClient = mClientPool->Allocate(); - ReturnErrorCodeIf(mCASEClient == nullptr, CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(mCASEClient != nullptr, CHIP_ERROR_NO_MEMORY); MATTER_LOG_METRIC_BEGIN(kMetricDeviceCASESession); CHIP_ERROR err = mCASEClient->EstablishSession(mInitParams, mPeerId, mDeviceAddress, config, this); diff --git a/src/app/SimpleSubscriptionResumptionStorage.cpp b/src/app/SimpleSubscriptionResumptionStorage.cpp index e233c18af9218a..0818a758236b3d 100644 --- a/src/app/SimpleSubscriptionResumptionStorage.cpp +++ b/src/app/SimpleSubscriptionResumptionStorage.cpp @@ -143,7 +143,7 @@ CHIP_ERROR SimpleSubscriptionResumptionStorage::Load(uint16_t subscriptionIndex, { Platform::ScopedMemoryBuffer backingBuffer; backingBuffer.Calloc(MaxSubscriptionSize()); - ReturnErrorCodeIf(backingBuffer.Get() == nullptr, CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(backingBuffer.Get() != nullptr, CHIP_ERROR_NO_MEMORY); uint16_t len = static_cast(MaxSubscriptionSize()); ReturnErrorOnFailure(mStorage->SyncGetKeyValue(DefaultStorageKeyAllocator::SubscriptionResumption(subscriptionIndex).KeyName(), @@ -193,7 +193,7 @@ CHIP_ERROR SimpleSubscriptionResumptionStorage::Load(uint16_t subscriptionIndex, if (pathCount) { subscriptionInfo.mAttributePaths.Calloc(pathCount); - ReturnErrorCodeIf(subscriptionInfo.mAttributePaths.Get() == nullptr, CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(subscriptionInfo.mAttributePaths.Get() != nullptr, CHIP_ERROR_NO_MEMORY); for (size_t pathIndex = 0; pathIndex < pathCount; pathIndex++) { ReturnErrorOnFailure(reader.Next(TLV::kTLVType_Structure, kAttributePathTag)); @@ -226,7 +226,7 @@ CHIP_ERROR SimpleSubscriptionResumptionStorage::Load(uint16_t subscriptionIndex, if (pathCount) { subscriptionInfo.mEventPaths.Calloc(pathCount); - ReturnErrorCodeIf(subscriptionInfo.mEventPaths.Get() == nullptr, CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(subscriptionInfo.mEventPaths.Get() != nullptr, CHIP_ERROR_NO_MEMORY); for (size_t pathIndex = 0; pathIndex < pathCount; pathIndex++) { ReturnErrorOnFailure(reader.Next(TLV::kTLVType_Structure, kEventPathTag)); @@ -371,7 +371,7 @@ CHIP_ERROR SimpleSubscriptionResumptionStorage::Save(SubscriptionInfo & subscrip // Now construct subscription state and save Platform::ScopedMemoryBuffer backingBuffer; backingBuffer.Calloc(MaxSubscriptionSize()); - ReturnErrorCodeIf(backingBuffer.Get() == nullptr, CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(backingBuffer.Get() != nullptr, CHIP_ERROR_NO_MEMORY); TLV::ScopedBufferTLVWriter writer(std::move(backingBuffer), MaxSubscriptionSize()); diff --git a/src/app/SubscriptionResumptionStorage.h b/src/app/SubscriptionResumptionStorage.h index 74158ecfd395f8..23a06c91e3bced 100644 --- a/src/app/SubscriptionResumptionStorage.h +++ b/src/app/SubscriptionResumptionStorage.h @@ -95,9 +95,9 @@ class SubscriptionResumptionStorage attributePathCount++; attributePath = attributePath->mpNext; } - ReturnErrorCodeIf((attributePathCount * sizeof(AttributePathParamsValues)) > UINT16_MAX, CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError((attributePathCount * sizeof(AttributePathParamsValues)) <= UINT16_MAX, CHIP_ERROR_NO_MEMORY); mAttributePaths.Calloc(attributePathCount); - ReturnErrorCodeIf(mAttributePaths.Get() == nullptr, CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(mAttributePaths.Get() != nullptr, CHIP_ERROR_NO_MEMORY); attributePath = pAttributePathList; for (size_t i = 0; i < attributePathCount; i++) { @@ -120,9 +120,9 @@ class SubscriptionResumptionStorage eventPathCount++; eventPath = eventPath->mpNext; } - ReturnErrorCodeIf((eventPathCount * sizeof(EventPathParamsValues)) > UINT16_MAX, CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError((eventPathCount * sizeof(EventPathParamsValues)) <= UINT16_MAX, CHIP_ERROR_NO_MEMORY); mEventPaths.Calloc(eventPathCount); - ReturnErrorCodeIf(mEventPaths.Get() == nullptr, CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(mEventPaths.Get() != nullptr, CHIP_ERROR_NO_MEMORY); eventPath = pEventPathList; for (size_t i = 0; i < eventPathCount; i++) { diff --git a/src/app/WriteClient.cpp b/src/app/WriteClient.cpp index da24d058f1c40a..0f1aef9f748885 100644 --- a/src/app/WriteClient.cpp +++ b/src/app/WriteClient.cpp @@ -142,7 +142,7 @@ CHIP_ERROR WriteClient::FinalizeMessage(bool aHasMoreChunks) VerifyOrReturnError(mState == State::AddAttribute, CHIP_ERROR_INCORRECT_STATE); TLV::TLVWriter * writer = mWriteRequestBuilder.GetWriter(); - ReturnErrorCodeIf(writer == nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(writer != nullptr, CHIP_ERROR_INCORRECT_STATE); ReturnErrorOnFailure(writer->UnreserveBuffer(kReservedSizeForTLVEncodingOverhead)); ReturnErrorOnFailure(mWriteRequestBuilder.GetWriteRequests().EndOfAttributeDataIBs()); diff --git a/src/app/WriteHandler.cpp b/src/app/WriteHandler.cpp index 011fd2e46b48ab..67a5c7a3ac99d9 100644 --- a/src/app/WriteHandler.cpp +++ b/src/app/WriteHandler.cpp @@ -344,7 +344,7 @@ CHIP_ERROR WriteHandler::ProcessAttributeDataIBs(TLV::TLVReader & aAttributeData { CHIP_ERROR err = CHIP_NO_ERROR; - ReturnErrorCodeIf(!mExchangeCtx, CHIP_ERROR_INTERNAL); + VerifyOrReturnError(mExchangeCtx, CHIP_ERROR_INTERNAL); const Access::SubjectDescriptor subjectDescriptor = mExchangeCtx->GetSessionHandle()->GetSubjectDescriptor(); while (CHIP_NO_ERROR == (err = aAttributeDataIBsReader.Next())) @@ -446,7 +446,7 @@ CHIP_ERROR WriteHandler::ProcessGroupAttributeDataIBs(TLV::TLVReader & aAttribut { CHIP_ERROR err = CHIP_NO_ERROR; - ReturnErrorCodeIf(!mExchangeCtx, CHIP_ERROR_INTERNAL); + VerifyOrReturnError(mExchangeCtx, CHIP_ERROR_INTERNAL); const Access::SubjectDescriptor subjectDescriptor = mExchangeCtx->GetSessionHandle()->AsIncomingGroupSession()->GetSubjectDescriptor(); diff --git a/src/app/clusters/access-control-server/access-control-server.cpp b/src/app/clusters/access-control-server/access-control-server.cpp index f6a47fb96dca12..e4c5688e6a9805 100644 --- a/src/app/clusters/access-control-server/access-control-server.cpp +++ b/src/app/clusters/access-control-server/access-control-server.cpp @@ -215,7 +215,7 @@ CHIP_ERROR AccessControlAttribute::ReadAcl(AttributeValueEncoder & aEncoder) { ReturnErrorOnFailure(encoder.Encode(encodableEntry)); } - ReturnErrorCodeIf(err != CHIP_NO_ERROR && err != CHIP_ERROR_SENTINEL, err); + VerifyOrReturnError(err == CHIP_NO_ERROR || err == CHIP_ERROR_SENTINEL, err); } return CHIP_NO_ERROR; }); @@ -233,7 +233,7 @@ CHIP_ERROR AccessControlAttribute::ReadExtension(AttributeValueEncoder & aEncode uint16_t size = static_cast(sizeof(buffer)); CHIP_ERROR errStorage = storage.SyncGetKeyValue( DefaultStorageKeyAllocator::AccessControlExtensionEntry(fabric.GetFabricIndex()).KeyName(), buffer, size); - ReturnErrorCodeIf(errStorage == CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(errStorage != CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_ERROR_INCORRECT_STATE); if (errStorage == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND) { continue; @@ -333,8 +333,8 @@ CHIP_ERROR AccessControlAttribute::WriteExtension(const ConcreteDataAttributePat uint16_t size = static_cast(sizeof(buffer)); CHIP_ERROR errStorage = storage.SyncGetKeyValue( DefaultStorageKeyAllocator::AccessControlExtensionEntry(accessingFabricIndex).KeyName(), buffer, size); - ReturnErrorCodeIf(errStorage == CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_ERROR_INCORRECT_STATE); - ReturnErrorCodeIf(errStorage != CHIP_NO_ERROR && errStorage != CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND, errStorage); + VerifyOrReturnError(errStorage != CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(errStorage == CHIP_NO_ERROR || errStorage == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND, errStorage); if (!aPath.IsListItemOperation()) { @@ -346,7 +346,7 @@ CHIP_ERROR AccessControlAttribute::WriteExtension(const ConcreteDataAttributePat if (count == 0) { - ReturnErrorCodeIf(errStorage == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND, CHIP_NO_ERROR); + VerifyOrReturnError(errStorage != CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND, CHIP_NO_ERROR); ReturnErrorOnFailure(storage.SyncDeleteKeyValue( DefaultStorageKeyAllocator::AccessControlExtensionEntry(accessingFabricIndex).KeyName())); AccessControlCluster::Structs::AccessControlExtensionStruct::Type item = { @@ -367,7 +367,7 @@ CHIP_ERROR AccessControlAttribute::WriteExtension(const ConcreteDataAttributePat } auto & item = iterator.GetValue(); // TODO(#13590): generated code doesn't automatically handle max length so do it manually - ReturnErrorCodeIf(item.data.size() > kExtensionDataMaxLength, CHIP_IM_GLOBAL_STATUS(ConstraintError)); + VerifyOrReturnError(item.data.size() <= kExtensionDataMaxLength, CHIP_IM_GLOBAL_STATUS(ConstraintError)); ReturnErrorOnFailure(CheckExtensionEntryDataFormat(item.data)); @@ -386,11 +386,11 @@ CHIP_ERROR AccessControlAttribute::WriteExtension(const ConcreteDataAttributePat } else if (aPath.mListOp == ConcreteDataAttributePath::ListOperation::AppendItem) { - ReturnErrorCodeIf(errStorage != CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND, CHIP_IM_GLOBAL_STATUS(ConstraintError)); + VerifyOrReturnError(errStorage == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND, CHIP_IM_GLOBAL_STATUS(ConstraintError)); AccessControlCluster::Structs::AccessControlExtensionStruct::DecodableType item; ReturnErrorOnFailure(aDecoder.Decode(item)); // TODO(#13590): generated code doesn't automatically handle max length so do it manually - ReturnErrorCodeIf(item.data.size() > kExtensionDataMaxLength, CHIP_IM_GLOBAL_STATUS(ConstraintError)); + VerifyOrReturnError(item.data.size() <= kExtensionDataMaxLength, CHIP_IM_GLOBAL_STATUS(ConstraintError)); ReturnErrorOnFailure(CheckExtensionEntryDataFormat(item.data)); diff --git a/src/app/clusters/bindings/bindings.cpp b/src/app/clusters/bindings/bindings.cpp index 409e667278b081..47e4d4571562f3 100644 --- a/src/app/clusters/bindings/bindings.cpp +++ b/src/app/clusters/bindings/bindings.cpp @@ -114,8 +114,8 @@ CHIP_ERROR CheckValidBindingList(const EndpointId localEndpoint, const Decodable oldListSize++; } } - ReturnErrorCodeIf(BindingTable::GetInstance().Size() - oldListSize + listSize > MATTER_BINDING_TABLE_SIZE, - CHIP_IM_GLOBAL_STATUS(ResourceExhausted)); + VerifyOrReturnError(BindingTable::GetInstance().Size() - oldListSize + listSize <= MATTER_BINDING_TABLE_SIZE, + CHIP_IM_GLOBAL_STATUS(ResourceExhausted)); return CHIP_NO_ERROR; } diff --git a/src/app/clusters/ota-requestor/DefaultOTARequestor.cpp b/src/app/clusters/ota-requestor/DefaultOTARequestor.cpp index edd0b5729c2708..e8352d890d7f21 100644 --- a/src/app/clusters/ota-requestor/DefaultOTARequestor.cpp +++ b/src/app/clusters/ota-requestor/DefaultOTARequestor.cpp @@ -593,7 +593,7 @@ CHIP_ERROR DefaultOTARequestor::ClearDefaultOtaProviderList(FabricIndex fabricIn CHIP_ERROR error = mDefaultOtaProviderList.Delete(fabricIndex); // Ignore the error if no entry for the associated fabric index has been found. - ReturnErrorCodeIf(error == CHIP_ERROR_NOT_FOUND, CHIP_NO_ERROR); + VerifyOrReturnError(error != CHIP_ERROR_NOT_FOUND, CHIP_NO_ERROR); ReturnErrorOnFailure(error); return mStorage->StoreDefaultProviders(mDefaultOtaProviderList); diff --git a/src/app/clusters/thread-border-router-management-server/thread-border-router-management-server.cpp b/src/app/clusters/thread-border-router-management-server/thread-border-router-management-server.cpp index 6988b83b46ba72..81dc2125e146a5 100644 --- a/src/app/clusters/thread-border-router-management-server/thread-border-router-management-server.cpp +++ b/src/app/clusters/thread-border-router-management-server/thread-border-router-management-server.cpp @@ -126,7 +126,7 @@ Status ServerInstance::HandleSetPendingDatasetRequest(CommandHandlerInterface::H Thread::OperationalDataset pendingDataset; // If any of the parameters in the PendingDataset is invalid, the command SHALL fail with a status code // of INVALID_COMMAND. - ReturnErrorCodeIf(pendingDataset.Init(req.pendingDataset) != CHIP_NO_ERROR, Status::InvalidCommand); + VerifyOrReturnError(pendingDataset.Init(req.pendingDataset) == CHIP_NO_ERROR, Status::InvalidCommand); CHIP_ERROR err = mDelegate->SetPendingDataset(pendingDataset); return StatusIB(err).mStatus; } @@ -363,7 +363,7 @@ void ServerInstance::OnPlatformEventHandler(const DeviceLayer::ChipDeviceEvent * CHIP_ERROR ServerInstance::Init() { - ReturnErrorCodeIf(!mDelegate, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(mDelegate, CHIP_ERROR_INVALID_ARGUMENT); ReturnErrorOnFailure(CommandHandlerInterfaceRegistry::Instance().RegisterCommandHandler(this)); VerifyOrReturnError(chip::app::AttributeAccessInterfaceRegistry::Instance().Register(this), CHIP_ERROR_INCORRECT_STATE); ReturnErrorOnFailure(DeviceLayer::PlatformMgrImpl().AddEventHandler(OnPlatformEventHandler, reinterpret_cast(this))); diff --git a/src/app/clusters/user-label-server/user-label-server.cpp b/src/app/clusters/user-label-server/user-label-server.cpp index 5daae5ab179ac3..e1ea85cf01a78a 100644 --- a/src/app/clusters/user-label-server/user-label-server.cpp +++ b/src/app/clusters/user-label-server/user-label-server.cpp @@ -131,7 +131,7 @@ CHIP_ERROR UserLabelAttrAccess::WriteLabelList(const ConcreteDataAttributePath & LabelList::TypeInfo::DecodableType decodablelist; ReturnErrorOnFailure(aDecoder.Decode(decodablelist)); - ReturnErrorCodeIf(!IsValidLabelEntryList(decodablelist), CHIP_IM_GLOBAL_STATUS(ConstraintError)); + VerifyOrReturnError(IsValidLabelEntryList(decodablelist), CHIP_IM_GLOBAL_STATUS(ConstraintError)); auto iter = decodablelist.begin(); while (iter.Next()) @@ -148,7 +148,7 @@ CHIP_ERROR UserLabelAttrAccess::WriteLabelList(const ConcreteDataAttributePath & Structs::LabelStruct::DecodableType entry; ReturnErrorOnFailure(aDecoder.Decode(entry)); - ReturnErrorCodeIf(!IsValidLabelEntry(entry), CHIP_IM_GLOBAL_STATUS(ConstraintError)); + VerifyOrReturnError(IsValidLabelEntry(entry), CHIP_IM_GLOBAL_STATUS(ConstraintError)); return provider->AppendUserLabel(endpoint, entry); } diff --git a/src/app/codegen-data-model-provider/CodegenDataModelProvider_Read.cpp b/src/app/codegen-data-model-provider/CodegenDataModelProvider_Read.cpp index 82baba4835c8b5..6ce5d282f89d30 100644 --- a/src/app/codegen-data-model-provider/CodegenDataModelProvider_Read.cpp +++ b/src/app/codegen-data-model-provider/CodegenDataModelProvider_Read.cpp @@ -271,7 +271,7 @@ DataModel::ActionReturnStatus CodegenDataModelProvider::ReadAttribute(const Data // ACL check for non-internal requests if (!request.operationFlags.Has(DataModel::OperationFlags::kInternal)) { - ReturnErrorCodeIf(!request.subjectDescriptor.has_value(), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(request.subjectDescriptor.has_value(), CHIP_ERROR_INVALID_ARGUMENT); Access::RequestPath requestPath{ .cluster = request.path.mClusterId, .endpoint = request.path.mEndpointId, @@ -281,7 +281,7 @@ DataModel::ActionReturnStatus CodegenDataModelProvider::ReadAttribute(const Data RequiredPrivilege::ForReadAttribute(request.path)); if (err != CHIP_NO_ERROR) { - ReturnErrorCodeIf((err != CHIP_ERROR_ACCESS_DENIED) && (err != CHIP_ERROR_ACCESS_RESTRICTED_BY_ARL), err); + VerifyOrReturnError((err == CHIP_ERROR_ACCESS_DENIED) || (err == CHIP_ERROR_ACCESS_RESTRICTED_BY_ARL), err); // Implementation of 8.4.3.2 of the spec for path expansion if (request.path.mExpanded) @@ -319,7 +319,7 @@ DataModel::ActionReturnStatus CodegenDataModelProvider::ReadAttribute(const Data request.path, AttributeAccessInterfaceRegistry::Instance().Get(request.path.mEndpointId, request.path.mClusterId), encoder); } - ReturnErrorCodeIf(aai_result.has_value(), *aai_result); + VerifyOrReturnError(!aai_result.has_value(), *aai_result); if (!std::holds_alternative(metadata)) { diff --git a/src/app/codegen-data-model-provider/CodegenDataModelProvider_Write.cpp b/src/app/codegen-data-model-provider/CodegenDataModelProvider_Write.cpp index 76c283ae04108a..4c46a2a364d16b 100644 --- a/src/app/codegen-data-model-provider/CodegenDataModelProvider_Write.cpp +++ b/src/app/codegen-data-model-provider/CodegenDataModelProvider_Write.cpp @@ -350,7 +350,7 @@ DataModel::ActionReturnStatus CodegenDataModelProvider::WriteAttribute(const Dat if (checkAcl) { - ReturnErrorCodeIf(!request.subjectDescriptor.has_value(), Status::UnsupportedAccess); + VerifyOrReturnError(request.subjectDescriptor.has_value(), Status::UnsupportedAccess); Access::RequestPath requestPath{ .cluster = request.path.mClusterId, .endpoint = request.path.mEndpointId, diff --git a/src/app/icd/client/DefaultICDClientStorage.cpp b/src/app/icd/client/DefaultICDClientStorage.cpp index c50bb621a2dc3a..2a1bc6a5d4fb86 100644 --- a/src/app/icd/client/DefaultICDClientStorage.cpp +++ b/src/app/icd/client/DefaultICDClientStorage.cpp @@ -59,7 +59,7 @@ CHIP_ERROR DefaultICDClientStorage::StoreFabricList() Platform::ScopedMemoryBuffer backingBuffer; size_t counter = mFabricList.size(); size_t total = kFabricIndexTlvSize * counter + kArrayOverHead; - ReturnErrorCodeIf(!backingBuffer.Calloc(total), CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(backingBuffer.Calloc(total), CHIP_ERROR_NO_MEMORY); TLV::ScopedBufferTLVWriter writer(std::move(backingBuffer), total); TLV::TLVType arrayType; @@ -81,7 +81,7 @@ CHIP_ERROR DefaultICDClientStorage::StoreFabricList() CHIP_ERROR DefaultICDClientStorage::LoadFabricList() { Platform::ScopedMemoryBuffer backingBuffer; - ReturnErrorCodeIf(!backingBuffer.Calloc(kMaxFabricListTlvLength), CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(backingBuffer.Calloc(kMaxFabricListTlvLength), CHIP_ERROR_NO_MEMORY); uint16_t length = kMaxFabricListTlvLength; ReturnErrorOnFailure( mpClientInfoStore->SyncGetKeyValue(DefaultStorageKeyAllocator::ICDFabricList().KeyName(), backingBuffer.Get(), length)); @@ -182,7 +182,7 @@ CHIP_ERROR DefaultICDClientStorage::LoadCounter(FabricIndex fabricIndex, size_t Platform::ScopedMemoryBuffer backingBuffer; size_t len = MaxICDCounterSize(); VerifyOrReturnError(CanCastTo(len), CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!backingBuffer.Calloc(len), CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(backingBuffer.Calloc(len), CHIP_ERROR_NO_MEMORY); uint16_t length = static_cast(len); CHIP_ERROR err = mpClientInfoStore->SyncGetKeyValue( @@ -220,7 +220,7 @@ CHIP_ERROR DefaultICDClientStorage::Load(FabricIndex fabricIndex, std::vector backingBuffer; VerifyOrReturnError(CanCastTo(len), CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!backingBuffer.Calloc(len), CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(backingBuffer.Calloc(len), CHIP_ERROR_NO_MEMORY); uint16_t length = static_cast(len); CHIP_ERROR err = mpClientInfoStore->SyncGetKeyValue(DefaultStorageKeyAllocator::ICDClientInfoKey(fabricIndex).KeyName(), backingBuffer.Get(), length); @@ -381,7 +381,7 @@ CHIP_ERROR DefaultICDClientStorage::StoreEntry(const ICDClientInfo & clientInfo) clientInfoVector.push_back(clientInfo); size_t total = clientInfoSize * clientInfoVector.size() + kArrayOverHead; Platform::ScopedMemoryBuffer backingBuffer; - ReturnErrorCodeIf(!backingBuffer.Calloc(total), CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(backingBuffer.Calloc(total), CHIP_ERROR_NO_MEMORY); TLV::ScopedBufferTLVWriter writer(std::move(backingBuffer), total); ReturnErrorOnFailure(SerializeToTlv(writer, clientInfoVector)); @@ -428,7 +428,7 @@ CHIP_ERROR DefaultICDClientStorage::UpdateEntryCountForFabric(FabricIndex fabric size_t total = MaxICDCounterSize(); Platform::ScopedMemoryBuffer backingBuffer; - ReturnErrorCodeIf(!backingBuffer.Calloc(total), CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(backingBuffer.Calloc(total), CHIP_ERROR_NO_MEMORY); TLV::ScopedBufferTLVWriter writer(std::move(backingBuffer), total); TLV::TLVType structType; @@ -467,7 +467,7 @@ CHIP_ERROR DefaultICDClientStorage::DeleteEntry(const ScopedNodeId & peerNode) mpClientInfoStore->SyncDeleteKeyValue(DefaultStorageKeyAllocator::ICDClientInfoKey(peerNode.GetFabricIndex()).KeyName())); size_t total = clientInfoSize * clientInfoVector.size() + kArrayOverHead; Platform::ScopedMemoryBuffer backingBuffer; - ReturnErrorCodeIf(!backingBuffer.Calloc(total), CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(backingBuffer.Calloc(total), CHIP_ERROR_NO_MEMORY); TLV::ScopedBufferTLVWriter writer(std::move(backingBuffer), total); ReturnErrorOnFailure(SerializeToTlv(writer, clientInfoVector)); diff --git a/src/app/reporting/Engine.cpp b/src/app/reporting/Engine.cpp index 2dd08739ad8959..45ebdeb7f64c02 100644 --- a/src/app/reporting/Engine.cpp +++ b/src/app/reporting/Engine.cpp @@ -852,7 +852,7 @@ bool Engine::MergeDirtyPathsUnderSameEndpoint() CHIP_ERROR Engine::InsertPathIntoDirtySet(const AttributePathParams & aAttributePath) { - ReturnErrorCodeIf(MergeOverlappedAttributePath(aAttributePath), CHIP_NO_ERROR); + VerifyOrReturnError(!MergeOverlappedAttributePath(aAttributePath), CHIP_NO_ERROR); if (mGlobalDirtySet.Exhausted() && !MergeDirtyPathsUnderSameCluster() && !MergeDirtyPathsUnderSameEndpoint()) { @@ -862,7 +862,7 @@ CHIP_ERROR Engine::InsertPathIntoDirtySet(const AttributePathParams & aAttribute object->mGeneration = GetDirtySetGeneration(); } - ReturnErrorCodeIf(MergeOverlappedAttributePath(aAttributePath), CHIP_NO_ERROR); + VerifyOrReturnError(!MergeOverlappedAttributePath(aAttributePath), CHIP_NO_ERROR); ChipLogDetail(DataManagement, "Cannot merge the new path into any existing path, create one."); auto object = mGlobalDirtySet.CreateObject(); diff --git a/src/app/server/AclStorage.cpp b/src/app/server/AclStorage.cpp index 03ebc7a1341906..913589ef828fb7 100644 --- a/src/app/server/AclStorage.cpp +++ b/src/app/server/AclStorage.cpp @@ -152,14 +152,14 @@ CHIP_ERROR Convert(StagingSubject from, NodeId & to) switch (from.authMode) { case StagingAuthMode::kPase: - ReturnErrorCodeIf((from.nodeId & ~kMaskPAKEKeyId) != 0, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError((from.nodeId & ~kMaskPAKEKeyId) == 0, CHIP_ERROR_INVALID_ARGUMENT); to = NodeIdFromPAKEKeyId(static_cast(from.nodeId)); break; case StagingAuthMode::kCase: to = from.nodeId; break; case StagingAuthMode::kGroup: - ReturnErrorCodeIf((from.nodeId & ~kMaskGroupId) != 0, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError((from.nodeId & ~kMaskGroupId) == 0, CHIP_ERROR_INVALID_ARGUMENT); to = NodeIdFromGroupId(static_cast(from.nodeId)); break; default: diff --git a/src/app/util/binding-table.cpp b/src/app/util/binding-table.cpp index ce3c45f196b3c9..7ca3c4ba18aace 100644 --- a/src/app/util/binding-table.cpp +++ b/src/app/util/binding-table.cpp @@ -219,7 +219,7 @@ CHIP_ERROR BindingTable::LoadEntryFromStorage(uint8_t index, uint8_t & nextIndex else { entry.type = MATTER_MULTICAST_BINDING; - ReturnErrorCodeIf(reader.GetTag() != TLV::ContextTag(kTagGroupId), CHIP_ERROR_INVALID_TLV_TAG); + VerifyOrReturnError(reader.GetTag() == TLV::ContextTag(kTagGroupId), CHIP_ERROR_INVALID_TLV_TAG); ReturnErrorOnFailure(reader.Get(entry.groupId)); } ReturnErrorOnFailure(reader.Next(TLV::ContextTag(kTagNextEntry))); diff --git a/src/app/util/ember-compatibility-functions.cpp b/src/app/util/ember-compatibility-functions.cpp index 0ea63cba30d1db..e50b55975f9de8 100644 --- a/src/app/util/ember-compatibility-functions.cpp +++ b/src/app/util/ember-compatibility-functions.cpp @@ -302,7 +302,7 @@ CHIP_ERROR ReadSingleClusterData(const SubjectDescriptor & aSubjectDescriptor, b CHIP_ERROR err = Access::GetAccessControl().Check(aSubjectDescriptor, requestPath, requestPrivilege); if (err != CHIP_NO_ERROR) { - ReturnErrorCodeIf((err != CHIP_ERROR_ACCESS_DENIED) && (err != CHIP_ERROR_ACCESS_RESTRICTED_BY_ARL), err); + VerifyOrReturnError((err == CHIP_ERROR_ACCESS_DENIED) || (err == CHIP_ERROR_ACCESS_RESTRICTED_BY_ARL), err); if (aPath.mExpanded) { return CHIP_NO_ERROR; @@ -324,7 +324,7 @@ CHIP_ERROR ReadSingleClusterData(const SubjectDescriptor & aSubjectDescriptor, b bool triedEncode = false; ReturnErrorOnFailure(ReadViaAccessInterface(aSubjectDescriptor, aIsFabricFiltered, aPath, aAttributeReports, apEncoderState, attributeOverride, &triedEncode)); - ReturnErrorCodeIf(triedEncode, CHIP_NO_ERROR); + VerifyOrReturnError(!triedEncode, CHIP_NO_ERROR); } } @@ -704,7 +704,7 @@ CHIP_ERROR WriteSingleClusterData(const SubjectDescriptor & aSubjectDescriptor, } if (err != CHIP_NO_ERROR) { - ReturnErrorCodeIf((err != CHIP_ERROR_ACCESS_DENIED) && (err != CHIP_ERROR_ACCESS_RESTRICTED_BY_ARL), err); + VerifyOrReturnError((err == CHIP_ERROR_ACCESS_DENIED) || (err == CHIP_ERROR_ACCESS_RESTRICTED_BY_ARL), err); // TODO: when wildcard/group writes are supported, handle them to discard rather than fail with status return apWriteHandler->AddStatus(aPath, err == CHIP_ERROR_ACCESS_DENIED diff --git a/src/controller/CHIPDeviceController.cpp b/src/controller/CHIPDeviceController.cpp index 346867226e4261..0c4f7ac9969b03 100644 --- a/src/controller/CHIPDeviceController.cpp +++ b/src/controller/CHIPDeviceController.cpp @@ -182,9 +182,9 @@ CHIP_ERROR DeviceController::InitControllerNOCChain(const ControllerInitParams & externalOperationalKeypair = params.operationalKeypair; } - ReturnErrorCodeIf(!rcacBuf.Alloc(chipCertAllocatedLen), CHIP_ERROR_NO_MEMORY); - ReturnErrorCodeIf(!icacBuf.Alloc(chipCertAllocatedLen), CHIP_ERROR_NO_MEMORY); - ReturnErrorCodeIf(!nocBuf.Alloc(chipCertAllocatedLen), CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(rcacBuf.Alloc(chipCertAllocatedLen), CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(icacBuf.Alloc(chipCertAllocatedLen), CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(nocBuf.Alloc(chipCertAllocatedLen), CHIP_ERROR_NO_MEMORY); MutableByteSpan rcacSpan(rcacBuf.Get(), chipCertAllocatedLen); @@ -2745,7 +2745,7 @@ void DeviceCommissioner::OnScanNetworksResponse(void * context, CHIP_ERROR DeviceCommissioner::NetworkCredentialsReady() { - ReturnErrorCodeIf(mCommissioningStage != CommissioningStage::kNeedsNetworkCreds, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mCommissioningStage == CommissioningStage::kNeedsNetworkCreds, CHIP_ERROR_INCORRECT_STATE); // need to advance to next step CommissioningStageComplete(CHIP_NO_ERROR); @@ -2755,7 +2755,7 @@ CHIP_ERROR DeviceCommissioner::NetworkCredentialsReady() CHIP_ERROR DeviceCommissioner::ICDRegistrationInfoReady() { - ReturnErrorCodeIf(mCommissioningStage != CommissioningStage::kICDGetRegistrationInfo, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mCommissioningStage == CommissioningStage::kICDGetRegistrationInfo, CHIP_ERROR_INCORRECT_STATE); // need to advance to next step CommissioningStageComplete(CHIP_NO_ERROR); diff --git a/src/controller/CHIPDeviceControllerFactory.cpp b/src/controller/CHIPDeviceControllerFactory.cpp index dbc55dd7b7327e..e7e718964d3745 100644 --- a/src/controller/CHIPDeviceControllerFactory.cpp +++ b/src/controller/CHIPDeviceControllerFactory.cpp @@ -132,8 +132,8 @@ CHIP_ERROR DeviceControllerFactory::InitSystemState(FactoryInitParams params) // OperationalCertificateStore needs to be provided to init the fabric table if fabric table is // not provided wholesale. - ReturnErrorCodeIf((params.fabricTable == nullptr) && (params.opCertStore == nullptr), CHIP_ERROR_INVALID_ARGUMENT); - ReturnErrorCodeIf(params.sessionKeystore == nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError((params.fabricTable != nullptr) || (params.opCertStore != nullptr), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(params.sessionKeystore != nullptr, CHIP_ERROR_INVALID_ARGUMENT); #if CONFIG_NETWORK_LAYER_BLE #if CONFIG_DEVICE_LAYER @@ -197,7 +197,7 @@ CHIP_ERROR DeviceControllerFactory::InitSystemState(FactoryInitParams params) { // TODO(#16231): Previously (and still) the objects new-ed in this entire method seem expected to last forever... auto newFabricTable = Platform::MakeUnique(); - ReturnErrorCodeIf(!newFabricTable, CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(newFabricTable, CHIP_ERROR_NO_MEMORY); FabricTable::InitParams fabricTableInitParams; fabricTableInitParams.storage = params.fabricIndependentStorage; diff --git a/src/controller/ExampleOperationalCredentialsIssuer.cpp b/src/controller/ExampleOperationalCredentialsIssuer.cpp index 516b3ece2b4357..346b9012c1b8e5 100644 --- a/src/controller/ExampleOperationalCredentialsIssuer.cpp +++ b/src/controller/ExampleOperationalCredentialsIssuer.cpp @@ -59,7 +59,7 @@ CHIP_ERROR IssueX509Cert(uint32_t now, uint32_t validity, ChipDN issuerDn, ChipD constexpr uint8_t sOID_Extension_SubjectAltName[] = { 0x55, 0x1d, 0x11 }; Platform::ScopedMemoryBuffer derBuf; - ReturnErrorCodeIf(!derBuf.Alloc(kMaxDERCertLength), CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(derBuf.Alloc(kMaxDERCertLength), CHIP_ERROR_NO_MEMORY); MutableByteSpan derSpan{ derBuf.Get(), kMaxDERCertLength }; int64_t serialNumber = 1; @@ -88,16 +88,16 @@ CHIP_ERROR IssueX509Cert(uint32_t now, uint32_t validity, ChipDN issuerDn, ChipD if (maximizeSize) { Platform::ScopedMemoryBuffer paddedTlvBuf; - ReturnErrorCodeIf(!paddedTlvBuf.Alloc(kMaxCHIPCertLength + kMaxCertPaddingLength), CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(paddedTlvBuf.Alloc(kMaxCHIPCertLength + kMaxCertPaddingLength), CHIP_ERROR_NO_MEMORY); MutableByteSpan paddedTlvSpan{ paddedTlvBuf.Get(), kMaxCHIPCertLength + kMaxCertPaddingLength }; ReturnErrorOnFailure(ConvertX509CertToChipCert(derSpan, paddedTlvSpan)); Platform::ScopedMemoryBuffer paddedDerBuf; - ReturnErrorCodeIf(!paddedDerBuf.Alloc(kMaxDERCertLength + kMaxCertPaddingLength), CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(paddedDerBuf.Alloc(kMaxDERCertLength + kMaxCertPaddingLength), CHIP_ERROR_NO_MEMORY); MutableByteSpan paddedDerSpan{ paddedDerBuf.Get(), kMaxDERCertLength + kMaxCertPaddingLength }; Platform::ScopedMemoryBuffer fillerBuf; - ReturnErrorCodeIf(!fillerBuf.Alloc(kMaxCertPaddingLength), CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(fillerBuf.Alloc(kMaxCertPaddingLength), CHIP_ERROR_NO_MEMORY); memset(fillerBuf.Get(), 'A', kMaxCertPaddingLength); int derPaddingLen = static_cast(kMaxDERCertLength - kDERCertFutureExtEncodingOverhead - derSpan.size()); @@ -361,15 +361,15 @@ CHIP_ERROR ExampleOperationalCredentialsIssuer::GenerateNOCChain(const ByteSpan ReturnErrorOnFailure(VerifyCertificateSigningRequest(csr.data(), csr.size(), pubkey)); chip::Platform::ScopedMemoryBuffer noc; - ReturnErrorCodeIf(!noc.Alloc(kMaxDERCertLength), CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(noc.Alloc(kMaxDERCertLength), CHIP_ERROR_NO_MEMORY); MutableByteSpan nocSpan(noc.Get(), kMaxDERCertLength); chip::Platform::ScopedMemoryBuffer icac; - ReturnErrorCodeIf(!icac.Alloc(kMaxDERCertLength), CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(icac.Alloc(kMaxDERCertLength), CHIP_ERROR_NO_MEMORY); MutableByteSpan icacSpan(icac.Get(), kMaxDERCertLength); chip::Platform::ScopedMemoryBuffer rcac; - ReturnErrorCodeIf(!rcac.Alloc(kMaxDERCertLength), CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(rcac.Alloc(kMaxDERCertLength), CHIP_ERROR_NO_MEMORY); MutableByteSpan rcacSpan(rcac.Get(), kMaxDERCertLength); ReturnErrorOnFailure( @@ -387,7 +387,7 @@ CHIP_ERROR ExampleOperationalCredentialsIssuer::GenerateNOCChain(const ByteSpan uint8_t ipkValue[CHIP_CRYPTO_SYMMETRIC_KEY_LENGTH_BYTES]; Crypto::IdentityProtectionKeySpan ipkSpan(ipkValue); - ReturnErrorCodeIf(defaultIpkSpan.size() != sizeof(ipkValue), CHIP_ERROR_INTERNAL); + VerifyOrReturnError(defaultIpkSpan.size() == sizeof(ipkValue), CHIP_ERROR_INTERNAL); memcpy(&ipkValue[0], defaultIpkSpan.data(), defaultIpkSpan.size()); // Callback onto commissioner. diff --git a/src/controller/ExamplePersistentStorage.cpp b/src/controller/ExamplePersistentStorage.cpp index 27ea886a77dd7f..599f0980db99b3 100644 --- a/src/controller/ExamplePersistentStorage.cpp +++ b/src/controller/ExamplePersistentStorage.cpp @@ -102,20 +102,20 @@ CHIP_ERROR PersistentStorage::SyncGetKeyValue(const char * key, void * value, ui { std::string iniValue; - ReturnErrorCodeIf(((value == nullptr) && (size != 0)), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError((value != nullptr) || (size == 0), CHIP_ERROR_INVALID_ARGUMENT); auto section = mConfig.sections[kDefaultSectionName]; - ReturnErrorCodeIf(!SyncDoesKeyExist(key), CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(SyncDoesKeyExist(key), CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); std::string escapedKey = EscapeKey(key); - ReturnErrorCodeIf(!inipp::extract(section[escapedKey], iniValue), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(inipp::extract(section[escapedKey], iniValue), CHIP_ERROR_INVALID_ARGUMENT); iniValue = Base64ToString(iniValue); uint16_t dataSize = static_cast(iniValue.size()); - ReturnErrorCodeIf(size == 0 && dataSize == 0, CHIP_NO_ERROR); - ReturnErrorCodeIf(value == nullptr, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(size != 0 || dataSize != 0, CHIP_NO_ERROR); + VerifyOrReturnError(value != nullptr, CHIP_ERROR_BUFFER_TOO_SMALL); uint16_t sizeToCopy = std::min(size, dataSize); @@ -126,7 +126,7 @@ CHIP_ERROR PersistentStorage::SyncGetKeyValue(const char * key, void * value, ui CHIP_ERROR PersistentStorage::SyncSetKeyValue(const char * key, const void * value, uint16_t size) { - ReturnErrorCodeIf((value == nullptr) && (size != 0), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError((value != nullptr) || (size == 0), CHIP_ERROR_INVALID_ARGUMENT); auto section = mConfig.sections[kDefaultSectionName]; @@ -148,7 +148,7 @@ CHIP_ERROR PersistentStorage::SyncDeleteKeyValue(const char * key) { auto section = mConfig.sections[kDefaultSectionName]; - ReturnErrorCodeIf(!SyncDoesKeyExist(key), CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(SyncDoesKeyExist(key), CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); std::string escapedKey = EscapeKey(key); section.erase(escapedKey); diff --git a/src/controller/java/AndroidOperationalCredentialsIssuer.cpp b/src/controller/java/AndroidOperationalCredentialsIssuer.cpp index d87e4f94825c9f..4873f21c1a26b8 100644 --- a/src/controller/java/AndroidOperationalCredentialsIssuer.cpp +++ b/src/controller/java/AndroidOperationalCredentialsIssuer.cpp @@ -295,7 +295,7 @@ CHIP_ERROR AndroidOperationalCredentialsIssuer::NOCChainGenerated(CHIP_ERROR sta Optional ipk, Optional adminSubject) { - ReturnErrorCodeIf(mOnNOCCompletionCallback == nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mOnNOCCompletionCallback != nullptr, CHIP_ERROR_INCORRECT_STATE); Callback::Callback * onCompletion = mOnNOCCompletionCallback; mOnNOCCompletionCallback = nullptr; @@ -357,11 +357,11 @@ CHIP_ERROR AndroidOperationalCredentialsIssuer::LocalGenerateNOCChain(const Byte ChipLogProgress(chipTool, "VerifyCertificateSigningRequest"); Platform::ScopedMemoryBuffer noc; - ReturnErrorCodeIf(!noc.Alloc(kMaxCHIPDERCertLength), CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(noc.Alloc(kMaxCHIPDERCertLength), CHIP_ERROR_NO_MEMORY); MutableByteSpan nocSpan(noc.Get(), kMaxCHIPDERCertLength); Platform::ScopedMemoryBuffer rcac; - ReturnErrorCodeIf(!rcac.Alloc(kMaxCHIPDERCertLength), CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(rcac.Alloc(kMaxCHIPDERCertLength), CHIP_ERROR_NO_MEMORY); MutableByteSpan rcacSpan(rcac.Get(), kMaxCHIPDERCertLength); MutableByteSpan icacSpan; @@ -380,7 +380,7 @@ CHIP_ERROR AndroidOperationalCredentialsIssuer::LocalGenerateNOCChain(const Byte uint8_t ipkValue[CHIP_CRYPTO_SYMMETRIC_KEY_LENGTH_BYTES]; Crypto::IdentityProtectionKeySpan ipkSpan(ipkValue); - ReturnErrorCodeIf(defaultIpkSpan.size() != sizeof(ipkValue), CHIP_ERROR_INTERNAL); + VerifyOrReturnError(defaultIpkSpan.size() == sizeof(ipkValue), CHIP_ERROR_INTERNAL); memcpy(&ipkValue[0], defaultIpkSpan.data(), defaultIpkSpan.size()); diff --git a/src/controller/python/ChipDeviceController-ScriptBinding.cpp b/src/controller/python/ChipDeviceController-ScriptBinding.cpp index b31cb5b7b8a4e6..11fdf763da558d 100644 --- a/src/controller/python/ChipDeviceController-ScriptBinding.cpp +++ b/src/controller/python/ChipDeviceController-ScriptBinding.cpp @@ -512,7 +512,7 @@ PyChipError pychip_DeviceController_OnNetworkCommission(chip::Controller::Device PyChipError pychip_DeviceController_SetThreadOperationalDataset(const char * threadOperationalDataset, uint32_t size) { - ReturnErrorCodeIf(!sThreadBuf.Alloc(size), ToPyChipError(CHIP_ERROR_NO_MEMORY)); + VerifyOrReturnError(sThreadBuf.Alloc(size), ToPyChipError(CHIP_ERROR_NO_MEMORY)); memcpy(sThreadBuf.Get(), threadOperationalDataset, size); sCommissioningParameters.SetThreadOperationalDataset(ByteSpan(sThreadBuf.Get(), size)); return ToPyChipError(CHIP_NO_ERROR); @@ -520,11 +520,11 @@ PyChipError pychip_DeviceController_SetThreadOperationalDataset(const char * thr PyChipError pychip_DeviceController_SetWiFiCredentials(const char * ssid, const char * credentials) { size_t ssidSize = strlen(ssid); - ReturnErrorCodeIf(!sSsidBuf.Alloc(ssidSize), ToPyChipError(CHIP_ERROR_NO_MEMORY)); + VerifyOrReturnError(sSsidBuf.Alloc(ssidSize), ToPyChipError(CHIP_ERROR_NO_MEMORY)); memcpy(sSsidBuf.Get(), ssid, ssidSize); size_t credsSize = strlen(credentials); - ReturnErrorCodeIf(!sCredsBuf.Alloc(credsSize), ToPyChipError(CHIP_ERROR_NO_MEMORY)); + VerifyOrReturnError(sCredsBuf.Alloc(credsSize), ToPyChipError(CHIP_ERROR_NO_MEMORY)); memcpy(sCredsBuf.Get(), credentials, credsSize); sCommissioningParameters.SetWiFiCredentials( @@ -544,7 +544,7 @@ PyChipError pychip_DeviceController_SetTimeZone(int32_t offset, uint64_t validAt else { size_t len = strlen(name); - ReturnErrorCodeIf(!sTimeZoneNameBuf.Alloc(len), ToPyChipError(CHIP_ERROR_NO_MEMORY)); + VerifyOrReturnError(sTimeZoneNameBuf.Alloc(len), ToPyChipError(CHIP_ERROR_NO_MEMORY)); memcpy(sTimeZoneNameBuf.Get(), name, len); sTimeZoneBuf.name.SetValue(CharSpan(sTimeZoneNameBuf.Get(), len)); } @@ -564,7 +564,7 @@ PyChipError pychip_DeviceController_SetDSTOffset(int32_t offset, uint64_t validS PyChipError pychip_DeviceController_SetDefaultNtp(const char * defaultNTP) { size_t len = strlen(defaultNTP); - ReturnErrorCodeIf(!sDefaultNTPBuf.Alloc(len), ToPyChipError(CHIP_ERROR_NO_MEMORY)); + VerifyOrReturnError(sDefaultNTPBuf.Alloc(len), ToPyChipError(CHIP_ERROR_NO_MEMORY)); memcpy(sDefaultNTPBuf.Get(), defaultNTP, len); sCommissioningParameters.SetDefaultNTP(chip::app::DataModel::MakeNullable(CharSpan(sDefaultNTPBuf.Get(), len))); return ToPyChipError(CHIP_NO_ERROR); diff --git a/src/controller/python/ChipDeviceController-StorageDelegate.cpp b/src/controller/python/ChipDeviceController-StorageDelegate.cpp index 9fb19efccdd2db..68e1531b7d8907 100644 --- a/src/controller/python/ChipDeviceController-StorageDelegate.cpp +++ b/src/controller/python/ChipDeviceController-StorageDelegate.cpp @@ -32,7 +32,7 @@ namespace Controller { CHIP_ERROR PythonPersistentStorageDelegate::SyncGetKeyValue(const char * key, void * value, uint16_t & size) { - ReturnErrorCodeIf(((value == nullptr) && (size != 0)), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError((value != nullptr) || (size == 0), CHIP_ERROR_INVALID_ARGUMENT); auto val = mStorage.find(key); if (val == mStorage.end()) @@ -47,8 +47,8 @@ CHIP_ERROR PythonPersistentStorageDelegate::SyncGetKeyValue(const char * key, vo } uint16_t neededSize = static_cast(val->second.size()); - ReturnErrorCodeIf(size == 0 && neededSize == 0, CHIP_NO_ERROR); - ReturnErrorCodeIf(value == nullptr, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(size != 0 || neededSize != 0, CHIP_NO_ERROR); + VerifyOrReturnError(value != nullptr, CHIP_ERROR_BUFFER_TOO_SMALL); if (size < neededSize) { @@ -114,7 +114,7 @@ CHIP_ERROR StorageAdapter::SyncGetKeyValue(const char * key, void * value, uint1 CHIP_ERROR StorageAdapter::SyncSetKeyValue(const char * key, const void * value, uint16_t size) { - ReturnErrorCodeIf(((value == nullptr) && (size != 0)), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError((value != nullptr) || (size == 0), CHIP_ERROR_INVALID_ARGUMENT); ChipLogDetail(Controller, "StorageAdapter::SetKeyValue: Key = %s, Value = %p (%u)", StringOrNullMarker(key), value, size); mSetKeyCb(mContext, key, value, size); return CHIP_NO_ERROR; diff --git a/src/controller/python/OpCredsBinding.cpp b/src/controller/python/OpCredsBinding.cpp index f5815922cc14eb..37b1e9a9d1a267 100644 --- a/src/controller/python/OpCredsBinding.cpp +++ b/src/controller/python/OpCredsBinding.cpp @@ -413,9 +413,9 @@ PyChipError pychip_OpCreds_AllocateControllerForPythonCommissioningFLow( uint8_t * rcac, uint32_t rcacLen, const uint8_t * ipk, uint32_t ipkLen, chip::VendorId adminVendorId, bool enableServerInteractions) { - ReturnErrorCodeIf(nocLen > Controller::kMaxCHIPDERCertLength, ToPyChipError(CHIP_ERROR_NO_MEMORY)); - ReturnErrorCodeIf(icacLen > Controller::kMaxCHIPDERCertLength, ToPyChipError(CHIP_ERROR_NO_MEMORY)); - ReturnErrorCodeIf(rcacLen > Controller::kMaxCHIPDERCertLength, ToPyChipError(CHIP_ERROR_NO_MEMORY)); + VerifyOrReturnError(nocLen <= Controller::kMaxCHIPDERCertLength, ToPyChipError(CHIP_ERROR_NO_MEMORY)); + VerifyOrReturnError(icacLen <= Controller::kMaxCHIPDERCertLength, ToPyChipError(CHIP_ERROR_NO_MEMORY)); + VerifyOrReturnError(rcacLen <= Controller::kMaxCHIPDERCertLength, ToPyChipError(CHIP_ERROR_NO_MEMORY)); ChipLogDetail(Controller, "Creating New Device Controller"); @@ -507,15 +507,15 @@ PyChipError pychip_OpCreds_AllocateController(OpCredsContext * context, chip::Co } chip::Platform::ScopedMemoryBuffer noc; - ReturnErrorCodeIf(!noc.Alloc(Controller::kMaxCHIPDERCertLength), ToPyChipError(CHIP_ERROR_NO_MEMORY)); + VerifyOrReturnError(noc.Alloc(Controller::kMaxCHIPDERCertLength), ToPyChipError(CHIP_ERROR_NO_MEMORY)); MutableByteSpan nocSpan(noc.Get(), Controller::kMaxCHIPDERCertLength); chip::Platform::ScopedMemoryBuffer icac; - ReturnErrorCodeIf(!icac.Alloc(Controller::kMaxCHIPDERCertLength), ToPyChipError(CHIP_ERROR_NO_MEMORY)); + VerifyOrReturnError(icac.Alloc(Controller::kMaxCHIPDERCertLength), ToPyChipError(CHIP_ERROR_NO_MEMORY)); MutableByteSpan icacSpan(icac.Get(), Controller::kMaxCHIPDERCertLength); chip::Platform::ScopedMemoryBuffer rcac; - ReturnErrorCodeIf(!rcac.Alloc(Controller::kMaxCHIPDERCertLength), ToPyChipError(CHIP_ERROR_NO_MEMORY)); + VerifyOrReturnError(rcac.Alloc(Controller::kMaxCHIPDERCertLength), ToPyChipError(CHIP_ERROR_NO_MEMORY)); MutableByteSpan rcacSpan(rcac.Get(), Controller::kMaxCHIPDERCertLength); CATValues catValues; diff --git a/src/credentials/CHIPCert.cpp b/src/credentials/CHIPCert.cpp index 5bad0ab75076a9..034b2873971405 100644 --- a/src/credentials/CHIPCert.cpp +++ b/src/credentials/CHIPCert.cpp @@ -989,7 +989,7 @@ CHIP_ERROR ChipDN::DecodeFromASN1(ASN1Reader & reader) // Only one AttributeTypeAndValue allowed per RDN. err = reader.Next(); - ReturnErrorCodeIf(err == CHIP_NO_ERROR, ASN1_ERROR_UNSUPPORTED_ENCODING); + VerifyOrReturnError(err != CHIP_NO_ERROR, ASN1_ERROR_UNSUPPORTED_ENCODING); VerifyOrReturnError(err == ASN1_END, err); } ASN1_EXIT_SET; @@ -1245,7 +1245,7 @@ CHIP_ERROR ExtractNodeIdFabricIdFromOpCert(const ChipCertificateData & opcert, N { // Since we assume the cert is pre-validated, we are going to assume that // its subject in fact has both a node id and a fabric id. - ReturnErrorCodeIf(outNodeId == nullptr || outFabricId == nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(outNodeId != nullptr && outFabricId != nullptr, CHIP_ERROR_INVALID_ARGUMENT); NodeId nodeId = 0; FabricId fabricId = kUndefinedFabricId; bool foundNodeId = false; @@ -1341,7 +1341,7 @@ CHIP_ERROR ExtractCATsFromOpCert(const ChipCertificateData & opcert, CATValues & // This error should never happen in practice because valid NOC cannot have more // than kMaxSubjectCATAttributeCount CATs in its subject. The check that it is // valid NOC was done above. - ReturnErrorCodeIf(catCount == cats.size(), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(catCount != cats.size(), CHIP_ERROR_BUFFER_TOO_SMALL); VerifyOrReturnError(CanCastTo(rdn.mChipVal), CHIP_ERROR_INVALID_ARGUMENT); cats.values[catCount++] = static_cast(rdn.mChipVal); } diff --git a/src/credentials/CHIPCertToX509.cpp b/src/credentials/CHIPCertToX509.cpp index 9e0549d13f4921..b5447780ce76f1 100644 --- a/src/credentials/CHIPCertToX509.cpp +++ b/src/credentials/CHIPCertToX509.cpp @@ -453,7 +453,7 @@ static CHIP_ERROR DecodeConvertECDSASignature(TLVReader & reader, ASN1Writer & w ReturnErrorOnFailure(DecodeECDSASignature(reader, certData)); // Converting the signature is a bit of work, so explicitly check if we have a null writer - ReturnErrorCodeIf(writer.IsNullWriter(), CHIP_NO_ERROR); + VerifyOrReturnError(!writer.IsNullWriter(), CHIP_NO_ERROR); // signatureValue BIT STRING // Per RFC3279, the ECDSA signature value is encoded in DER encapsulated in the signatureValue BIT STRING. diff --git a/src/credentials/FabricTable.cpp b/src/credentials/FabricTable.cpp index 8ed838243df4ab..1c4001cefecebd 100644 --- a/src/credentials/FabricTable.cpp +++ b/src/credentials/FabricTable.cpp @@ -436,7 +436,7 @@ CHIP_ERROR FabricTable::VerifyCredentials(const ByteSpan & noc, const ByteSpan & err = ExtractFabricIdFromCert(certificates.GetCertSet()[1], &icacFabricId); if (err == CHIP_NO_ERROR) { - ReturnErrorCodeIf(icacFabricId != outFabricId, CHIP_ERROR_FABRIC_MISMATCH_ON_ICA); + VerifyOrReturnError(icacFabricId == outFabricId, CHIP_ERROR_FABRIC_MISMATCH_ON_ICA); } // FabricId is optional field in ICAC and "not found" code is not treated as error. else if (err != CHIP_ERROR_NOT_FOUND) @@ -449,7 +449,7 @@ CHIP_ERROR FabricTable::VerifyCredentials(const ByteSpan & noc, const ByteSpan & err = ExtractFabricIdFromCert(certificates.GetCertSet()[0], &rcacFabricId); if (err == CHIP_NO_ERROR) { - ReturnErrorCodeIf(rcacFabricId != outFabricId, CHIP_ERROR_WRONG_CERT_DN); + VerifyOrReturnError(rcacFabricId == outFabricId, CHIP_ERROR_WRONG_CERT_DN); } // FabricId is optional field in RCAC and "not found" code is not treated as error. else if (err != CHIP_ERROR_NOT_FOUND) @@ -660,7 +660,7 @@ CHIP_ERROR FabricTable::FetchRootPubkey(FabricIndex fabricIndex, Crypto::P256Pub { MATTER_TRACE_SCOPE("FetchRootPubkey", "Fabric"); const FabricInfo * fabricInfo = FindFabricWithIndex(fabricIndex); - ReturnErrorCodeIf(fabricInfo == nullptr, CHIP_ERROR_INVALID_FABRIC_INDEX); + VerifyOrReturnError(fabricInfo != nullptr, CHIP_ERROR_INVALID_FABRIC_INDEX); return fabricInfo->FetchRootPubkey(outPublicKey); } @@ -861,9 +861,9 @@ FabricTable::AddOrUpdateInner(FabricIndex fabricIndex, bool isAddition, Crypto:: Platform::ScopedMemoryBuffer icacBuf; Platform::ScopedMemoryBuffer rcacBuf; - ReturnErrorCodeIf(!nocBuf.Alloc(kMaxCHIPCertLength), CHIP_ERROR_NO_MEMORY); - ReturnErrorCodeIf(!icacBuf.Alloc(kMaxCHIPCertLength), CHIP_ERROR_NO_MEMORY); - ReturnErrorCodeIf(!rcacBuf.Alloc(kMaxCHIPCertLength), CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(nocBuf.Alloc(kMaxCHIPCertLength), CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(icacBuf.Alloc(kMaxCHIPCertLength), CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(rcacBuf.Alloc(kMaxCHIPCertLength), CHIP_ERROR_NO_MEMORY); MutableByteSpan nocSpan{ nocBuf.Get(), kMaxCHIPCertLength }; MutableByteSpan icacSpan{ icacBuf.Get(), kMaxCHIPCertLength }; @@ -1590,7 +1590,7 @@ CHIP_ERROR FabricTable::AllocatePendingOperationalKey(Optional fabr if (fabricIndex.HasValue()) { // Check we not are trying to do an update but also change the root: forbidden - ReturnErrorCodeIf(mStateFlags.Has(StateFlags::kIsTrustedRootPending), CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(!mStateFlags.Has(StateFlags::kIsTrustedRootPending), CHIP_ERROR_INCORRECT_STATE); // Fabric update case (e.g. UpdateNOC): we already know the fabric index fabricIndexToUse = fabricIndex.Value(); @@ -1621,8 +1621,8 @@ CHIP_ERROR FabricTable::AddNewPendingTrustedRootCert(const ByteSpan & rcac) VerifyOrReturnError(mOpCertStore != nullptr, CHIP_ERROR_INCORRECT_STATE); // We should not already have pending NOC chain elements when we get here - ReturnErrorCodeIf( - mStateFlags.HasAny(StateFlags::kIsTrustedRootPending, StateFlags::kIsUpdatePending, StateFlags::kIsAddPending), + VerifyOrReturnError( + !mStateFlags.HasAny(StateFlags::kIsTrustedRootPending, StateFlags::kIsUpdatePending, StateFlags::kIsAddPending), CHIP_ERROR_INCORRECT_STATE); EnsureNextAvailableFabricIndexUpdated(); @@ -1738,7 +1738,7 @@ CHIP_ERROR FabricTable::AddNewPendingFabricCommon(const ByteSpan & noc, const By { FabricIndex collidingFabricIndex = kUndefinedFabricIndex; ReturnErrorOnFailure(FindExistingFabricByNocChaining(fabricIndexToUse, noc, collidingFabricIndex)); - ReturnErrorCodeIf(collidingFabricIndex != kUndefinedFabricIndex, CHIP_ERROR_FABRIC_EXISTS); + VerifyOrReturnError(collidingFabricIndex == kUndefinedFabricIndex, CHIP_ERROR_FABRIC_EXISTS); } // We don't have a collision, handle the temp insert of NOC/ICAC @@ -1790,7 +1790,7 @@ CHIP_ERROR FabricTable::UpdatePendingFabricCommon(FabricIndex fabricIndex, const // Make sure we are updating at least an existing FabricIndex const auto * fabricInfo = FindFabricWithIndex(fabricIndex); - ReturnErrorCodeIf(fabricInfo == nullptr, CHIP_ERROR_INVALID_FABRIC_INDEX); + VerifyOrReturnError(fabricInfo != nullptr, CHIP_ERROR_INVALID_FABRIC_INDEX); // Check for an existing fabric matching RCAC and FabricID. We must find a correct // existing fabric that chains to same root. We assume the stored root is correct. @@ -1798,7 +1798,7 @@ CHIP_ERROR FabricTable::UpdatePendingFabricCommon(FabricIndex fabricIndex, const { FabricIndex collidingFabricIndex = kUndefinedFabricIndex; ReturnErrorOnFailure(FindExistingFabricByNocChaining(fabricIndex, noc, collidingFabricIndex)); - ReturnErrorCodeIf(collidingFabricIndex != fabricIndex, CHIP_ERROR_INVALID_FABRIC_INDEX); + VerifyOrReturnError(collidingFabricIndex == fabricIndex, CHIP_ERROR_INVALID_FABRIC_INDEX); } // Handle the temp insert of NOC/ICAC @@ -2110,7 +2110,7 @@ CHIP_ERROR FabricTable::SetFabricLabel(FabricIndex fabricIndex, const CharSpan & VerifyOrReturnError(mStorage != nullptr, CHIP_ERROR_INCORRECT_STATE); VerifyOrReturnError(IsValidFabricIndex(fabricIndex), CHIP_ERROR_INVALID_FABRIC_INDEX); - ReturnErrorCodeIf(fabricLabel.size() > kFabricLabelMaxLengthInBytes, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(fabricLabel.size() <= kFabricLabelMaxLengthInBytes, CHIP_ERROR_INVALID_ARGUMENT); FabricInfo * fabricInfo = GetMutableFabricByIndex(fabricIndex); bool fabricIsInitialized = (fabricInfo != nullptr) && fabricInfo->IsInitialized(); diff --git a/src/credentials/FabricTable.h b/src/credentials/FabricTable.h index 9515ffb8889c06..2bf8af51af4a48 100644 --- a/src/credentials/FabricTable.h +++ b/src/credentials/FabricTable.h @@ -96,7 +96,7 @@ class DLL_EXPORT FabricInfo CompressedFabricId GetCompressedFabricId() const { return mCompressedFabricId; } CHIP_ERROR GetCompressedFabricIdBytes(MutableByteSpan & compressedFabricId) const { - ReturnErrorCodeIf(compressedFabricId.size() != sizeof(uint64_t), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(compressedFabricId.size() == sizeof(uint64_t), CHIP_ERROR_INVALID_ARGUMENT); Encoding::BigEndian::Put64(compressedFabricId.data(), GetCompressedFabricId()); return CHIP_NO_ERROR; } diff --git a/src/credentials/PersistentStorageOpCertStore.cpp b/src/credentials/PersistentStorageOpCertStore.cpp index a2c0eb8bfb09d3..bda1e06d9a0baa 100644 --- a/src/credentials/PersistentStorageOpCertStore.cpp +++ b/src/credentials/PersistentStorageOpCertStore.cpp @@ -210,17 +210,17 @@ bool PersistentStorageOpCertStore::HasCertificateForFabric(FabricIndex fabricInd CHIP_ERROR PersistentStorageOpCertStore::AddNewTrustedRootCertForFabric(FabricIndex fabricIndex, const ByteSpan & rcac) { - ReturnErrorCodeIf(mStorage == nullptr, CHIP_ERROR_INCORRECT_STATE); - ReturnErrorCodeIf(!IsValidFabricIndex(fabricIndex), CHIP_ERROR_INVALID_FABRIC_INDEX); - ReturnErrorCodeIf(rcac.empty() || (rcac.size() > Credentials::kMaxCHIPCertLength), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(mStorage != nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(IsValidFabricIndex(fabricIndex), CHIP_ERROR_INVALID_FABRIC_INDEX); + VerifyOrReturnError(!rcac.empty() && (rcac.size() <= Credentials::kMaxCHIPCertLength), CHIP_ERROR_INVALID_ARGUMENT); - ReturnErrorCodeIf(mStateFlags.HasAny(StateFlags::kUpdateOpCertsCalled, StateFlags::kAddNewTrustedRootCalled, - StateFlags::kAddNewOpCertsCalled), - CHIP_ERROR_INCORRECT_STATE); - ReturnErrorCodeIf(StorageHasCertificate(mStorage, fabricIndex, CertChainElement::kRcac), CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(!mStateFlags.HasAny(StateFlags::kUpdateOpCertsCalled, StateFlags::kAddNewTrustedRootCalled, + StateFlags::kAddNewOpCertsCalled), + CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(!StorageHasCertificate(mStorage, fabricIndex, CertChainElement::kRcac), CHIP_ERROR_INCORRECT_STATE); Platform::ScopedMemoryBufferWithSize rcacBuf; - ReturnErrorCodeIf(!rcacBuf.Alloc(rcac.size()), CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(rcacBuf.Alloc(rcac.size()), CHIP_ERROR_NO_MEMORY); memcpy(rcacBuf.Get(), rcac.data(), rcac.size()); mPendingRcac = std::move(rcacBuf); @@ -234,33 +234,33 @@ CHIP_ERROR PersistentStorageOpCertStore::AddNewTrustedRootCertForFabric(FabricIn CHIP_ERROR PersistentStorageOpCertStore::AddNewOpCertsForFabric(FabricIndex fabricIndex, const ByteSpan & noc, const ByteSpan & icac) { - ReturnErrorCodeIf(mStorage == nullptr, CHIP_ERROR_INCORRECT_STATE); - ReturnErrorCodeIf(!IsValidFabricIndex(fabricIndex), CHIP_ERROR_INVALID_FABRIC_INDEX); - ReturnErrorCodeIf(noc.empty() || (noc.size() > Credentials::kMaxCHIPCertLength), CHIP_ERROR_INVALID_ARGUMENT); - ReturnErrorCodeIf(icac.size() > Credentials::kMaxCHIPCertLength, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(mStorage != nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(IsValidFabricIndex(fabricIndex), CHIP_ERROR_INVALID_FABRIC_INDEX); + VerifyOrReturnError(!noc.empty() && (noc.size() <= Credentials::kMaxCHIPCertLength), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(icac.size() <= Credentials::kMaxCHIPCertLength, CHIP_ERROR_INVALID_ARGUMENT); // Can't have called UpdateOpCertsForFabric first, or called with pending certs - ReturnErrorCodeIf(mStateFlags.HasAny(StateFlags::kUpdateOpCertsCalled, StateFlags::kAddNewOpCertsCalled), - CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(!mStateFlags.HasAny(StateFlags::kUpdateOpCertsCalled, StateFlags::kAddNewOpCertsCalled), + CHIP_ERROR_INCORRECT_STATE); // Need to have trusted roots installed to make the chain valid - ReturnErrorCodeIf(!mStateFlags.Has(StateFlags::kAddNewTrustedRootCalled), CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mStateFlags.Has(StateFlags::kAddNewTrustedRootCalled), CHIP_ERROR_INCORRECT_STATE); // fabricIndex must match the current pending fabric - ReturnErrorCodeIf(fabricIndex != mPendingFabricIndex, CHIP_ERROR_INVALID_FABRIC_INDEX); + VerifyOrReturnError(fabricIndex == mPendingFabricIndex, CHIP_ERROR_INVALID_FABRIC_INDEX); // Can't have persisted NOC/ICAC for same fabric if adding - ReturnErrorCodeIf(StorageHasCertificate(mStorage, fabricIndex, CertChainElement::kNoc), CHIP_ERROR_INCORRECT_STATE); - ReturnErrorCodeIf(StorageHasCertificate(mStorage, fabricIndex, CertChainElement::kIcac), CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(!StorageHasCertificate(mStorage, fabricIndex, CertChainElement::kNoc), CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(!StorageHasCertificate(mStorage, fabricIndex, CertChainElement::kIcac), CHIP_ERROR_INCORRECT_STATE); Platform::ScopedMemoryBufferWithSize nocBuf; - ReturnErrorCodeIf(!nocBuf.Alloc(noc.size()), CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(nocBuf.Alloc(noc.size()), CHIP_ERROR_NO_MEMORY); memcpy(nocBuf.Get(), noc.data(), noc.size()); Platform::ScopedMemoryBufferWithSize icacBuf; if (icac.size() > 0) { - ReturnErrorCodeIf(!icacBuf.Alloc(icac.size()), CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(icacBuf.Alloc(icac.size()), CHIP_ERROR_NO_MEMORY); memcpy(icacBuf.Get(), icac.data(), icac.size()); } @@ -275,35 +275,35 @@ CHIP_ERROR PersistentStorageOpCertStore::AddNewOpCertsForFabric(FabricIndex fabr CHIP_ERROR PersistentStorageOpCertStore::UpdateOpCertsForFabric(FabricIndex fabricIndex, const ByteSpan & noc, const ByteSpan & icac) { - ReturnErrorCodeIf(mStorage == nullptr, CHIP_ERROR_INCORRECT_STATE); - ReturnErrorCodeIf(!IsValidFabricIndex(fabricIndex), CHIP_ERROR_INVALID_FABRIC_INDEX); - ReturnErrorCodeIf(noc.empty() || (noc.size() > Credentials::kMaxCHIPCertLength), CHIP_ERROR_INVALID_ARGUMENT); - ReturnErrorCodeIf(icac.size() > Credentials::kMaxCHIPCertLength, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(mStorage != nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(IsValidFabricIndex(fabricIndex), CHIP_ERROR_INVALID_FABRIC_INDEX); + VerifyOrReturnError(!noc.empty() && (noc.size() <= Credentials::kMaxCHIPCertLength), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(icac.size() <= Credentials::kMaxCHIPCertLength, CHIP_ERROR_INVALID_ARGUMENT); // Can't have called AddNewOpCertsForFabric first, and should never get here after AddNewTrustedRootCertForFabric. - ReturnErrorCodeIf(mStateFlags.HasAny(StateFlags::kAddNewOpCertsCalled, StateFlags::kAddNewTrustedRootCalled), - CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(!mStateFlags.HasAny(StateFlags::kAddNewOpCertsCalled, StateFlags::kAddNewTrustedRootCalled), + CHIP_ERROR_INCORRECT_STATE); // Can't have already pending NOC from UpdateOpCerts not yet committed - ReturnErrorCodeIf(mStateFlags.Has(StateFlags::kUpdateOpCertsCalled), CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(!mStateFlags.Has(StateFlags::kUpdateOpCertsCalled), CHIP_ERROR_INCORRECT_STATE); // Need to have trusted roots installed to make the chain valid - ReturnErrorCodeIf(!StorageHasCertificate(mStorage, fabricIndex, CertChainElement::kRcac), CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(StorageHasCertificate(mStorage, fabricIndex, CertChainElement::kRcac), CHIP_ERROR_INCORRECT_STATE); // Must have persisted NOC for same fabric if updating - ReturnErrorCodeIf(!StorageHasCertificate(mStorage, fabricIndex, CertChainElement::kNoc), CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(StorageHasCertificate(mStorage, fabricIndex, CertChainElement::kNoc), CHIP_ERROR_INCORRECT_STATE); // Don't check for ICAC, we may not have had one before, but assume that if NOC is there, a // previous chain was at least partially there Platform::ScopedMemoryBufferWithSize nocBuf; - ReturnErrorCodeIf(!nocBuf.Alloc(noc.size()), CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(nocBuf.Alloc(noc.size()), CHIP_ERROR_NO_MEMORY); memcpy(nocBuf.Get(), noc.data(), noc.size()); Platform::ScopedMemoryBufferWithSize icacBuf; if (icac.size() > 0) { - ReturnErrorCodeIf(!icacBuf.Alloc(icac.size()), CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(icacBuf.Alloc(icac.size()), CHIP_ERROR_NO_MEMORY); memcpy(icacBuf.Get(), icac.data(), icac.size()); } @@ -329,8 +329,8 @@ CHIP_ERROR PersistentStorageOpCertStore::CommitOpCertsForFabric(FabricIndex fabr { // Neither of these conditions should have occurred based on other interlocks, but since // committing certificates is a dangerous operation, we absolutely validate our assumptions. - ReturnErrorCodeIf(mStateFlags.Has(StateFlags::kUpdateOpCertsCalled), CHIP_ERROR_INCORRECT_STATE); - ReturnErrorCodeIf(!mStateFlags.Has(StateFlags::kAddNewTrustedRootCalled), CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(!mStateFlags.Has(StateFlags::kUpdateOpCertsCalled), CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mStateFlags.Has(StateFlags::kAddNewTrustedRootCalled), CHIP_ERROR_INCORRECT_STATE); } // TODO: Handle transaction marking to revert partial certs at next boot if we get interrupted by reboot. @@ -405,7 +405,7 @@ CHIP_ERROR PersistentStorageOpCertStore::RemoveOpCertsForFabric(FabricIndex fabr VerifyOrReturnError(IsValidFabricIndex(fabricIndex), CHIP_ERROR_INVALID_FABRIC_INDEX); // If there was *no* state, pending or persisted, we have an error - ReturnErrorCodeIf(!HasAnyCertificateForFabric(fabricIndex), CHIP_ERROR_INVALID_FABRIC_INDEX); + VerifyOrReturnError(HasAnyCertificateForFabric(fabricIndex), CHIP_ERROR_INVALID_FABRIC_INDEX); // Clear any pending state RevertPendingOpCerts(); diff --git a/src/credentials/TestOnlyLocalCertificateAuthority.h b/src/credentials/TestOnlyLocalCertificateAuthority.h index fb731f9fc98b2e..719b6495a0db24 100644 --- a/src/credentials/TestOnlyLocalCertificateAuthority.h +++ b/src/credentials/TestOnlyLocalCertificateAuthority.h @@ -161,9 +161,9 @@ class TestOnlyLocalCertificateAuthority if (mIncludeIcac) { Platform::ScopedMemoryBufferWithSize icacDerBuf; - ReturnErrorCodeIf(!icacDerBuf.Alloc(Credentials::kMaxDERCertLength), CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(icacDerBuf.Alloc(Credentials::kMaxDERCertLength), CHIP_ERROR_NO_MEMORY); Platform::ScopedMemoryBufferWithSize icacChipBuf; - ReturnErrorCodeIf(!icacChipBuf.Alloc(Credentials::kMaxCHIPCertLength), CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(icacChipBuf.Alloc(Credentials::kMaxCHIPCertLength), CHIP_ERROR_NO_MEMORY); ReturnErrorOnFailure(icac_dn.AddAttribute_MatterFabricId(fabricId)); ReturnErrorOnFailure(icac_dn.AddAttribute_MatterICACId(1234)); @@ -176,7 +176,7 @@ class TestOnlyLocalCertificateAuthority MutableByteSpan icacChipSpan{ icacChipBuf.Get(), icacChipBuf.AllocatedSize() }; ReturnErrorOnFailure(Credentials::ConvertX509CertToChipCert(icacDerSpan, icacChipSpan)); - ReturnErrorCodeIf(!mLastIcac.Alloc(icacChipSpan.size()), CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(mLastIcac.Alloc(icacChipSpan.size()), CHIP_ERROR_NO_MEMORY); memcpy(mLastIcac.Get(), icacChipSpan.data(), icacChipSpan.size()); @@ -187,9 +187,9 @@ class TestOnlyLocalCertificateAuthority // Generate NOC always, either issued from ICAC if present or from RCAC { Platform::ScopedMemoryBufferWithSize nocDerBuf; - ReturnErrorCodeIf(!nocDerBuf.Alloc(Credentials::kMaxDERCertLength), CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(nocDerBuf.Alloc(Credentials::kMaxDERCertLength), CHIP_ERROR_NO_MEMORY); Platform::ScopedMemoryBufferWithSize nocChipBuf; - ReturnErrorCodeIf(!nocChipBuf.Alloc(Credentials::kMaxCHIPCertLength), CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(nocChipBuf.Alloc(Credentials::kMaxCHIPCertLength), CHIP_ERROR_NO_MEMORY); ReturnErrorOnFailure(noc_dn.AddAttribute_MatterFabricId(fabricId)); ReturnErrorOnFailure(noc_dn.AddAttribute_MatterNodeId(nodeId)); @@ -202,7 +202,7 @@ class TestOnlyLocalCertificateAuthority MutableByteSpan nocChipSpan{ nocChipBuf.Get(), nocChipBuf.AllocatedSize() }; ReturnErrorOnFailure(Credentials::ConvertX509CertToChipCert(nocDerSpan, nocChipSpan)); - ReturnErrorCodeIf(!mLastNoc.Alloc(nocChipSpan.size()), CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(mLastNoc.Alloc(nocChipSpan.size()), CHIP_ERROR_NO_MEMORY); memcpy(mLastNoc.Get(), nocChipSpan.data(), nocChipSpan.size()); } diff --git a/src/credentials/attestation_verifier/DefaultDeviceAttestationVerifier.cpp b/src/credentials/attestation_verifier/DefaultDeviceAttestationVerifier.cpp index 14759d850ffc40..f9cf68e6cf24bd 100644 --- a/src/credentials/attestation_verifier/DefaultDeviceAttestationVerifier.cpp +++ b/src/credentials/attestation_verifier/DefaultDeviceAttestationVerifier.cpp @@ -627,9 +627,9 @@ bool CsaCdKeysTrustStore::IsCdTestKey(const ByteSpan & kid) const CHIP_ERROR CsaCdKeysTrustStore::AddTrustedKey(const ByteSpan & kid, const Crypto::P256PublicKey & pubKey) { - ReturnErrorCodeIf(kid.size() > SingleKeyEntry::kMaxKidSize, CHIP_ERROR_INVALID_ARGUMENT); - ReturnErrorCodeIf(kid.empty(), CHIP_ERROR_INVALID_ARGUMENT); - ReturnErrorCodeIf(mNumTrustedKeys == kMaxNumTrustedKeys, CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(kid.size() <= SingleKeyEntry::kMaxKidSize, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(!kid.empty(), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(mNumTrustedKeys != kMaxNumTrustedKeys, CHIP_ERROR_NO_MEMORY); auto & entry = mTrustedKeys[mNumTrustedKeys]; diff --git a/src/crypto/CHIPCryptoPAL.cpp b/src/crypto/CHIPCryptoPAL.cpp index fa84d786b8eabb..2caecbcb156779 100644 --- a/src/crypto/CHIPCryptoPAL.cpp +++ b/src/crypto/CHIPCryptoPAL.cpp @@ -75,7 +75,7 @@ CHIP_ERROR ReadDerUnsignedIntegerIntoRaw(Reader & reader, MutableByteSpan raw_in // Check for pseudo-zero to mark unsigned value // This means we have too large an integer (should be at most 1 byte too large), it's invalid - ReturnErrorCodeIf(integer_len > (raw_integer_out.size() + 1), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(integer_len <= (raw_integer_out.size() + 1), CHIP_ERROR_INVALID_ARGUMENT); if (integer_len == (raw_integer_out.size() + 1u)) { @@ -603,10 +603,10 @@ CHIP_ERROR Spake2pVerifier::ComputeWS(uint32_t pbkdf2IterCount, const ByteSpan & uint8_t littleEndianSetupPINCode[sizeof(uint32_t)]; Encoding::LittleEndian::Put32(littleEndianSetupPINCode, setupPin); - ReturnErrorCodeIf(salt.size() < kSpake2p_Min_PBKDF_Salt_Length || salt.size() > kSpake2p_Max_PBKDF_Salt_Length, - CHIP_ERROR_INVALID_ARGUMENT); - ReturnErrorCodeIf(pbkdf2IterCount < kSpake2p_Min_PBKDF_Iterations || pbkdf2IterCount > kSpake2p_Max_PBKDF_Iterations, - CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(salt.size() >= kSpake2p_Min_PBKDF_Salt_Length && salt.size() <= kSpake2p_Max_PBKDF_Salt_Length, + CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(pbkdf2IterCount >= kSpake2p_Min_PBKDF_Iterations && pbkdf2IterCount <= kSpake2p_Max_PBKDF_Iterations, + CHIP_ERROR_INVALID_ARGUMENT); return pbkdf2.pbkdf2_sha256(littleEndianSetupPINCode, sizeof(littleEndianSetupPINCode), salt.data(), salt.size(), pbkdf2IterCount, ws_len, ws); @@ -925,8 +925,8 @@ CHIP_ERROR DeriveGroupOperationalCredentials(const ByteSpan & epoch_key, const B CHIP_ERROR ExtractVIDPIDFromAttributeString(DNAttrType attrType, const ByteSpan & attr, AttestationCertVidPid & vidpidFromMatterAttr, AttestationCertVidPid & vidpidFromCNAttr) { - ReturnErrorCodeIf(attrType == DNAttrType::kUnspecified, CHIP_NO_ERROR); - ReturnErrorCodeIf(attr.empty(), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(attrType != DNAttrType::kUnspecified, CHIP_NO_ERROR); + VerifyOrReturnError(!attr.empty(), CHIP_ERROR_INVALID_ARGUMENT); if (attrType == DNAttrType::kMatterVID || attrType == DNAttrType::kMatterPID) { @@ -939,13 +939,13 @@ CHIP_ERROR ExtractVIDPIDFromAttributeString(DNAttrType attrType, const ByteSpan if (attrType == DNAttrType::kMatterVID) { // Not more than one VID attribute can be present. - ReturnErrorCodeIf(vidpidFromMatterAttr.mVendorId.HasValue(), CHIP_ERROR_WRONG_CERT_DN); + VerifyOrReturnError(!vidpidFromMatterAttr.mVendorId.HasValue(), CHIP_ERROR_WRONG_CERT_DN); vidpidFromMatterAttr.mVendorId.SetValue(static_cast(matterAttr)); } else { // Not more than one PID attribute can be present. - ReturnErrorCodeIf(vidpidFromMatterAttr.mProductId.HasValue(), CHIP_ERROR_WRONG_CERT_DN); + VerifyOrReturnError(!vidpidFromMatterAttr.mProductId.HasValue(), CHIP_ERROR_WRONG_CERT_DN); vidpidFromMatterAttr.mProductId.SetValue(matterAttr); } } diff --git a/src/crypto/CHIPCryptoPALOpenSSL.cpp b/src/crypto/CHIPCryptoPALOpenSSL.cpp index 6b4b17daf005d0..c1182ac8ebe03c 100644 --- a/src/crypto/CHIPCryptoPALOpenSSL.cpp +++ b/src/crypto/CHIPCryptoPALOpenSSL.cpp @@ -2297,11 +2297,11 @@ CHIP_ERROR ReplaceCertIfResignedCertFound(const ByteSpan & referenceCertificate, MutableByteSpan referenceSKID(referenceSKIDBuf); MutableByteSpan candidateSKID(candidateSKIDBuf); - ReturnErrorCodeIf(referenceCertificate.empty(), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(!referenceCertificate.empty(), CHIP_ERROR_INVALID_ARGUMENT); outCertificate = referenceCertificate; - ReturnErrorCodeIf(candidateCertificates == nullptr || candidateCertificatesCount == 0, CHIP_NO_ERROR); + VerifyOrReturnError(candidateCertificates != nullptr && candidateCertificatesCount != 0, CHIP_NO_ERROR); ReturnErrorOnFailure(ExtractSKIDFromX509Cert(referenceCertificate, referenceSKID)); diff --git a/src/crypto/CHIPCryptoPALmbedTLSCert.cpp b/src/crypto/CHIPCryptoPALmbedTLSCert.cpp index 11eab025193135..00053ee5b7ea9c 100644 --- a/src/crypto/CHIPCryptoPALmbedTLSCert.cpp +++ b/src/crypto/CHIPCryptoPALmbedTLSCert.cpp @@ -982,7 +982,7 @@ CHIP_ERROR ExtractRawDNFromX509Cert(bool extractSubject, const ByteSpan & certif size_t len = 0; mbedtls_x509_crt mbedCertificate; - ReturnErrorCodeIf(certificate.empty(), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(!certificate.empty(), CHIP_ERROR_INVALID_ARGUMENT); mbedtls_x509_crt_init(&mbedCertificate); result = mbedtls_x509_crt_parse(&mbedCertificate, Uint8::to_const_uchar(certificate.data()), certificate.size()); @@ -1038,7 +1038,7 @@ CHIP_ERROR ReplaceCertIfResignedCertFound(const ByteSpan & referenceCertificate, outCertificate = referenceCertificate; - ReturnErrorCodeIf(candidateCertificates == nullptr || candidateCertificatesCount == 0, CHIP_NO_ERROR); + VerifyOrReturnError(candidateCertificates != nullptr && candidateCertificatesCount != 0, CHIP_NO_ERROR); ReturnErrorOnFailure(ExtractSubjectFromX509Cert(referenceCertificate, referenceSubject)); ReturnErrorOnFailure(ExtractSKIDFromX509Cert(referenceCertificate, referenceSKID)); diff --git a/src/crypto/PSAOperationalKeystore.cpp b/src/crypto/PSAOperationalKeystore.cpp index 09e00bc9b581f9..b0d0e133e41c21 100644 --- a/src/crypto/PSAOperationalKeystore.cpp +++ b/src/crypto/PSAOperationalKeystore.cpp @@ -88,7 +88,7 @@ CHIP_ERROR PSAOperationalKeystore::PersistentP256Keypair::Destroy() { psa_status_t status = psa_destroy_key(GetKeyId()); - ReturnErrorCodeIf(status == PSA_ERROR_INVALID_HANDLE, CHIP_ERROR_INVALID_FABRIC_INDEX); + VerifyOrReturnError(status != PSA_ERROR_INVALID_HANDLE, CHIP_ERROR_INVALID_FABRIC_INDEX); VerifyOrReturnError(status == PSA_SUCCESS, CHIP_ERROR_INTERNAL); return CHIP_NO_ERROR; diff --git a/src/include/platform/internal/GenericConfigurationManagerImpl.ipp b/src/include/platform/internal/GenericConfigurationManagerImpl.ipp index 9b36f341042aa9..d9769576c90f7b 100644 --- a/src/include/platform/internal/GenericConfigurationManagerImpl.ipp +++ b/src/include/platform/internal/GenericConfigurationManagerImpl.ipp @@ -177,7 +177,7 @@ CHIP_ERROR LegacyTemporaryCommissionableDataProvider::GetSpake2pSal if (err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND) { saltB64Len = strlen(CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_SALT); - ReturnErrorCodeIf(saltB64Len > sizeof(saltB64), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(saltB64Len <= sizeof(saltB64), CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(saltB64, CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_SALT, saltB64Len); err = CHIP_NO_ERROR; } @@ -189,7 +189,7 @@ CHIP_ERROR LegacyTemporaryCommissionableDataProvider::GetSpake2pSal size_t saltLen = chip::Base64Decode32(saltB64, static_cast(saltB64Len), reinterpret_cast(saltB64)); - ReturnErrorCodeIf(saltLen > saltBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(saltLen <= saltBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(saltBuf.data(), saltB64, saltLen); saltBuf.reduce_size(saltLen); @@ -214,7 +214,7 @@ CHIP_ERROR LegacyTemporaryCommissionableDataProvider::GetSpake2pVer if (err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND) { verifierB64Len = strlen(CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_VERIFIER); - ReturnErrorCodeIf(verifierB64Len > sizeof(verifierB64), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(verifierB64Len <= sizeof(verifierB64), CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(verifierB64, CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_VERIFIER, verifierB64Len); err = CHIP_NO_ERROR; } @@ -226,7 +226,7 @@ CHIP_ERROR LegacyTemporaryCommissionableDataProvider::GetSpake2pVer verifierLen = chip::Base64Decode32(verifierB64, static_cast(verifierB64Len), reinterpret_cast(verifierB64)); - ReturnErrorCodeIf(verifierLen > verifierBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(verifierLen <= verifierBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(verifierBuf.data(), verifierB64, verifierLen); verifierBuf.reduce_size(verifierLen); @@ -351,7 +351,7 @@ CHIP_ERROR GenericConfigurationManagerImpl::GetSecondaryPairingHint template CHIP_ERROR GenericConfigurationManagerImpl::GetSoftwareVersionString(char * buf, size_t bufSize) { - ReturnErrorCodeIf(bufSize < sizeof(CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(bufSize >= sizeof(CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING), CHIP_ERROR_BUFFER_TOO_SMALL); strcpy(buf, CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING); return CHIP_NO_ERROR; } @@ -516,8 +516,8 @@ CHIP_ERROR GenericConfigurationManagerImpl::GetUniqueId(char * buf, ReturnErrorOnFailure(err); - ReturnErrorCodeIf(uniqueIdLen >= bufSize, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(buf[uniqueIdLen] != 0, CHIP_ERROR_INVALID_STRING_LENGTH); + VerifyOrReturnError(uniqueIdLen < bufSize, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(buf[uniqueIdLen] == 0, CHIP_ERROR_INVALID_STRING_LENGTH); return err; } @@ -552,8 +552,8 @@ CHIP_ERROR GenericConfigurationManagerImpl::IncrementLifetimeCounte template CHIP_ERROR GenericConfigurationManagerImpl::SetRotatingDeviceIdUniqueId(const ByteSpan & uniqueIdSpan) { - ReturnErrorCodeIf(uniqueIdSpan.size() < kMinRotatingDeviceIDUniqueIDLength, CHIP_ERROR_INVALID_ARGUMENT); - ReturnErrorCodeIf(uniqueIdSpan.size() > CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID_LENGTH, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(uniqueIdSpan.size() >= kMinRotatingDeviceIDUniqueIDLength, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(uniqueIdSpan.size() <= CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID_LENGTH, CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(mRotatingDeviceIdUniqueId, uniqueIdSpan.data(), uniqueIdSpan.size()); mRotatingDeviceIdUniqueIdLength = uniqueIdSpan.size(); return CHIP_NO_ERROR; @@ -562,7 +562,7 @@ CHIP_ERROR GenericConfigurationManagerImpl::SetRotatingDeviceIdUniq template CHIP_ERROR GenericConfigurationManagerImpl::GetRotatingDeviceIdUniqueId(MutableByteSpan & uniqueIdSpan) { - ReturnErrorCodeIf(mRotatingDeviceIdUniqueIdLength > uniqueIdSpan.size(), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mRotatingDeviceIdUniqueIdLength <= uniqueIdSpan.size(), CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(uniqueIdSpan.data(), mRotatingDeviceIdUniqueId, mRotatingDeviceIdUniqueIdLength); uniqueIdSpan.reduce_size(mRotatingDeviceIdUniqueIdLength); return CHIP_NO_ERROR; @@ -646,7 +646,7 @@ bool GenericConfigurationManagerImpl::IsCommissionableDeviceNameEna template CHIP_ERROR GenericConfigurationManagerImpl::GetCommissionableDeviceName(char * buf, size_t bufSize) { - ReturnErrorCodeIf(bufSize < sizeof(CHIP_DEVICE_CONFIG_DEVICE_NAME), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(bufSize >= sizeof(CHIP_DEVICE_CONFIG_DEVICE_NAME), CHIP_ERROR_BUFFER_TOO_SMALL); strcpy(buf, CHIP_DEVICE_CONFIG_DEVICE_NAME); return CHIP_NO_ERROR; } @@ -654,7 +654,7 @@ CHIP_ERROR GenericConfigurationManagerImpl::GetCommissionableDevice template CHIP_ERROR GenericConfigurationManagerImpl::GetInitialPairingInstruction(char * buf, size_t bufSize) { - ReturnErrorCodeIf(bufSize < sizeof(CHIP_DEVICE_CONFIG_PAIRING_INITIAL_INSTRUCTION), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(bufSize >= sizeof(CHIP_DEVICE_CONFIG_PAIRING_INITIAL_INSTRUCTION), CHIP_ERROR_BUFFER_TOO_SMALL); strcpy(buf, CHIP_DEVICE_CONFIG_PAIRING_INITIAL_INSTRUCTION); return CHIP_NO_ERROR; } @@ -662,7 +662,7 @@ CHIP_ERROR GenericConfigurationManagerImpl::GetInitialPairingInstru template CHIP_ERROR GenericConfigurationManagerImpl::GetSecondaryPairingInstruction(char * buf, size_t bufSize) { - ReturnErrorCodeIf(bufSize < sizeof(CHIP_DEVICE_CONFIG_PAIRING_SECONDARY_INSTRUCTION), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(bufSize >= sizeof(CHIP_DEVICE_CONFIG_PAIRING_SECONDARY_INSTRUCTION), CHIP_ERROR_BUFFER_TOO_SMALL); strcpy(buf, CHIP_DEVICE_CONFIG_PAIRING_SECONDARY_INSTRUCTION); return CHIP_NO_ERROR; } diff --git a/src/include/platform/internal/GenericDeviceInstanceInfoProvider.ipp b/src/include/platform/internal/GenericDeviceInstanceInfoProvider.ipp index 549c3eb360aa95..4febf883850277 100644 --- a/src/include/platform/internal/GenericDeviceInstanceInfoProvider.ipp +++ b/src/include/platform/internal/GenericDeviceInstanceInfoProvider.ipp @@ -38,7 +38,7 @@ CHIP_ERROR GenericDeviceInstanceInfoProvider::GetProductId(uint16_t template CHIP_ERROR GenericDeviceInstanceInfoProvider::GetVendorName(char * buf, size_t bufSize) { - ReturnErrorCodeIf(bufSize < sizeof(CHIP_DEVICE_CONFIG_DEVICE_VENDOR_NAME), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(bufSize >= sizeof(CHIP_DEVICE_CONFIG_DEVICE_VENDOR_NAME), CHIP_ERROR_BUFFER_TOO_SMALL); strcpy(buf, CHIP_DEVICE_CONFIG_DEVICE_VENDOR_NAME); return CHIP_NO_ERROR; } @@ -46,7 +46,7 @@ CHIP_ERROR GenericDeviceInstanceInfoProvider::GetVendorName(char * template CHIP_ERROR GenericDeviceInstanceInfoProvider::GetProductName(char * buf, size_t bufSize) { - ReturnErrorCodeIf(bufSize < sizeof(CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_NAME), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(bufSize >= sizeof(CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_NAME), CHIP_ERROR_BUFFER_TOO_SMALL); strcpy(buf, CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_NAME); return CHIP_NO_ERROR; @@ -99,7 +99,7 @@ CHIP_ERROR GenericDeviceInstanceInfoProvider::GetSerialNumber(char #ifdef CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER if (CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER[0] != 0 && err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND) { - ReturnErrorCodeIf(sizeof(CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER) > bufSize, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(sizeof(CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER) <= bufSize, CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(buf, CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER, sizeof(CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER)); serialNumLen = sizeof(CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER) - 1; err = CHIP_NO_ERROR; @@ -107,8 +107,8 @@ CHIP_ERROR GenericDeviceInstanceInfoProvider::GetSerialNumber(char #endif // CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER ReturnErrorOnFailure(err); - ReturnErrorCodeIf(serialNumLen >= bufSize, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(buf[serialNumLen] != 0, CHIP_ERROR_INVALID_STRING_LENGTH); + VerifyOrReturnError(serialNumLen < bufSize, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(buf[serialNumLen] == 0, CHIP_ERROR_INVALID_STRING_LENGTH); return err; } @@ -176,7 +176,7 @@ CHIP_ERROR GenericDeviceInstanceInfoProvider::GetHardwareVersion(ui template CHIP_ERROR GenericDeviceInstanceInfoProvider::GetHardwareVersionString(char * buf, size_t bufSize) { - ReturnErrorCodeIf(bufSize < sizeof(CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION_STRING), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(bufSize >= sizeof(CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION_STRING), CHIP_ERROR_BUFFER_TOO_SMALL); strcpy(buf, CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION_STRING); return CHIP_NO_ERROR; } @@ -194,8 +194,8 @@ CHIP_ERROR GenericDeviceInstanceInfoProvider::GetRotatingDeviceIdUn constexpr uint8_t uniqueId[] = CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID; - ReturnErrorCodeIf(sizeof(uniqueId) > uniqueIdSpan.size(), CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(sizeof(uniqueId) != ConfigurationManager::kRotatingDeviceIDUniqueIDLength, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(sizeof(uniqueId) <= uniqueIdSpan.size(), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(sizeof(uniqueId) == ConfigurationManager::kRotatingDeviceIDUniqueIDLength, CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(uniqueIdSpan.data(), uniqueId, sizeof(uniqueId)); uniqueIdSpan.reduce_size(sizeof(uniqueId)); } diff --git a/src/lib/asn1/ASN1OID.cpp b/src/lib/asn1/ASN1OID.cpp index 4734a4aa7ad527..70ac838ccf5e8e 100644 --- a/src/lib/asn1/ASN1OID.cpp +++ b/src/lib/asn1/ASN1OID.cpp @@ -107,9 +107,9 @@ const char * GetOIDName(OID oid) CHIP_ERROR ASN1Reader::GetObjectId(OID & oid) { - ReturnErrorCodeIf(Value == nullptr, ASN1_ERROR_INVALID_STATE); - ReturnErrorCodeIf(ValueLen < 1, ASN1_ERROR_INVALID_ENCODING); - ReturnErrorCodeIf(mElemStart + mHeadLen + ValueLen > mContainerEnd, ASN1_ERROR_UNDERRUN); + VerifyOrReturnError(Value != nullptr, ASN1_ERROR_INVALID_STATE); + VerifyOrReturnError(ValueLen >= 1, ASN1_ERROR_INVALID_ENCODING); + VerifyOrReturnError(mElemStart + mHeadLen + ValueLen <= mContainerEnd, ASN1_ERROR_UNDERRUN); VerifyOrReturnError(CanCastTo(ValueLen), ASN1_ERROR_INVALID_ENCODING); oid = ParseObjectID(Value, static_cast(ValueLen)); return CHIP_NO_ERROR; diff --git a/src/lib/asn1/ASN1Reader.cpp b/src/lib/asn1/ASN1Reader.cpp index 6039e1ae084561..1a053f307f101d 100644 --- a/src/lib/asn1/ASN1Reader.cpp +++ b/src/lib/asn1/ASN1Reader.cpp @@ -50,8 +50,8 @@ void ASN1Reader::Init(const uint8_t * buf, size_t len) CHIP_ERROR ASN1Reader::Next() { - ReturnErrorCodeIf(EndOfContents, ASN1_END); - ReturnErrorCodeIf(IndefiniteLen, ASN1_ERROR_UNSUPPORTED_ENCODING); + VerifyOrReturnError(!EndOfContents, ASN1_END); + VerifyOrReturnError(!IndefiniteLen, ASN1_ERROR_UNSUPPORTED_ENCODING); // Note: avoid using addition assignment operator (+=), which may result in integer overflow // in the right hand side of an assignment (mHeadLen + ValueLen). @@ -59,14 +59,14 @@ CHIP_ERROR ASN1Reader::Next() ResetElementState(); - ReturnErrorCodeIf(mElemStart == mContainerEnd, ASN1_END); + VerifyOrReturnError(mElemStart != mContainerEnd, ASN1_END); return DecodeHead(); } CHIP_ERROR ASN1Reader::EnterConstructedType() { - ReturnErrorCodeIf(!Constructed, ASN1_ERROR_INVALID_STATE); + VerifyOrReturnError(Constructed, ASN1_ERROR_INVALID_STATE); return EnterContainer(0); } @@ -78,7 +78,7 @@ CHIP_ERROR ASN1Reader::ExitConstructedType() CHIP_ERROR ASN1Reader::GetConstructedType(const uint8_t *& val, uint32_t & valLen) { - ReturnErrorCodeIf(!Constructed, ASN1_ERROR_INVALID_STATE); + VerifyOrReturnError(Constructed, ASN1_ERROR_INVALID_STATE); val = mElemStart; valLen = mHeadLen + ValueLen; @@ -91,7 +91,7 @@ CHIP_ERROR ASN1Reader::EnterEncapsulatedType() (Tag == kASN1UniversalTag_OctetString || Tag == kASN1UniversalTag_BitString), ASN1_ERROR_INVALID_STATE); - ReturnErrorCodeIf(Constructed, ASN1_ERROR_UNSUPPORTED_ENCODING); + VerifyOrReturnError(!Constructed, ASN1_ERROR_UNSUPPORTED_ENCODING); return EnterContainer((Tag == kASN1UniversalTag_BitString) ? 1 : 0); } @@ -103,7 +103,7 @@ CHIP_ERROR ASN1Reader::ExitEncapsulatedType() CHIP_ERROR ASN1Reader::EnterContainer(uint32_t offset) { - ReturnErrorCodeIf(mNumSavedContexts == kMaxContextDepth, ASN1_ERROR_MAX_DEPTH_EXCEEDED); + VerifyOrReturnError(mNumSavedContexts != kMaxContextDepth, ASN1_ERROR_MAX_DEPTH_EXCEEDED); mSavedContexts[mNumSavedContexts].ElemStart = mElemStart; mSavedContexts[mNumSavedContexts].HeadLen = mHeadLen; @@ -127,11 +127,11 @@ CHIP_ERROR ASN1Reader::EnterContainer(uint32_t offset) CHIP_ERROR ASN1Reader::ExitContainer() { - ReturnErrorCodeIf(mNumSavedContexts == 0, ASN1_ERROR_INVALID_STATE); + VerifyOrReturnError(mNumSavedContexts != 0, ASN1_ERROR_INVALID_STATE); ASN1ParseContext & prevContext = mSavedContexts[--mNumSavedContexts]; - ReturnErrorCodeIf(prevContext.IndefiniteLen, ASN1_ERROR_UNSUPPORTED_ENCODING); + VerifyOrReturnError(!prevContext.IndefiniteLen, ASN1_ERROR_UNSUPPORTED_ENCODING); mElemStart = prevContext.ElemStart + prevContext.HeadLen + prevContext.ValueLen; @@ -152,10 +152,10 @@ CHIP_ERROR ASN1Reader::GetInteger(int64_t & val) uint8_t encodedVal[sizeof(int64_t)] = { 0 }; size_t valPaddingLen = sizeof(int64_t) - ValueLen; - ReturnErrorCodeIf(Value == nullptr, ASN1_ERROR_INVALID_STATE); - ReturnErrorCodeIf(ValueLen < 1, ASN1_ERROR_INVALID_ENCODING); - ReturnErrorCodeIf(ValueLen > sizeof(int64_t), ASN1_ERROR_VALUE_OVERFLOW); - ReturnErrorCodeIf(mElemStart + mHeadLen + ValueLen > mContainerEnd, ASN1_ERROR_UNDERRUN); + VerifyOrReturnError(Value != nullptr, ASN1_ERROR_INVALID_STATE); + VerifyOrReturnError(ValueLen >= 1, ASN1_ERROR_INVALID_ENCODING); + VerifyOrReturnError(ValueLen <= sizeof(int64_t), ASN1_ERROR_VALUE_OVERFLOW); + VerifyOrReturnError(mElemStart + mHeadLen + ValueLen <= mContainerEnd, ASN1_ERROR_UNDERRUN); if ((*Value & 0x80) == 0x80) { @@ -173,9 +173,9 @@ CHIP_ERROR ASN1Reader::GetInteger(int64_t & val) CHIP_ERROR ASN1Reader::GetBoolean(bool & val) { - ReturnErrorCodeIf(Value == nullptr, ASN1_ERROR_INVALID_STATE); - ReturnErrorCodeIf(ValueLen != 1, ASN1_ERROR_INVALID_ENCODING); - ReturnErrorCodeIf(mElemStart + mHeadLen + ValueLen > mContainerEnd, ASN1_ERROR_UNDERRUN); + VerifyOrReturnError(Value != nullptr, ASN1_ERROR_INVALID_STATE); + VerifyOrReturnError(ValueLen == 1, ASN1_ERROR_INVALID_ENCODING); + VerifyOrReturnError(mElemStart + mHeadLen + ValueLen <= mContainerEnd, ASN1_ERROR_UNDERRUN); VerifyOrReturnError(Value[0] == 0 || Value[0] == 0xFF, ASN1_ERROR_INVALID_ENCODING); val = (Value[0] != 0); @@ -186,9 +186,9 @@ CHIP_ERROR ASN1Reader::GetBoolean(bool & val) CHIP_ERROR ASN1Reader::GetUTCTime(ASN1UniversalTime & outTime) { // Supported Encoding: YYMMDDHHMMSSZ - ReturnErrorCodeIf(Value == nullptr, ASN1_ERROR_INVALID_STATE); - ReturnErrorCodeIf(ValueLen < 1, ASN1_ERROR_INVALID_ENCODING); - ReturnErrorCodeIf(mElemStart + mHeadLen + ValueLen > mContainerEnd, ASN1_ERROR_UNDERRUN); + VerifyOrReturnError(Value != nullptr, ASN1_ERROR_INVALID_STATE); + VerifyOrReturnError(ValueLen >= 1, ASN1_ERROR_INVALID_ENCODING); + VerifyOrReturnError(mElemStart + mHeadLen + ValueLen <= mContainerEnd, ASN1_ERROR_UNDERRUN); VerifyOrReturnError(ValueLen == 13 && Value[12] == 'Z', ASN1_ERROR_UNSUPPORTED_ENCODING); return outTime.ImportFrom_ASN1_TIME_string(CharSpan(reinterpret_cast(Value), ValueLen)); @@ -197,9 +197,9 @@ CHIP_ERROR ASN1Reader::GetUTCTime(ASN1UniversalTime & outTime) CHIP_ERROR ASN1Reader::GetGeneralizedTime(ASN1UniversalTime & outTime) { // Supported Encoding: YYYYMMDDHHMMSSZ - ReturnErrorCodeIf(Value == nullptr, ASN1_ERROR_INVALID_STATE); - ReturnErrorCodeIf(ValueLen < 1, ASN1_ERROR_INVALID_ENCODING); - ReturnErrorCodeIf(mElemStart + mHeadLen + ValueLen > mContainerEnd, ASN1_ERROR_UNDERRUN); + VerifyOrReturnError(Value != nullptr, ASN1_ERROR_INVALID_STATE); + VerifyOrReturnError(ValueLen >= 1, ASN1_ERROR_INVALID_ENCODING); + VerifyOrReturnError(mElemStart + mHeadLen + ValueLen <= mContainerEnd, ASN1_ERROR_UNDERRUN); VerifyOrReturnError(ValueLen == 15 && Value[14] == 'Z', ASN1_ERROR_UNSUPPORTED_ENCODING); return outTime.ImportFrom_ASN1_TIME_string(CharSpan(reinterpret_cast(Value), ValueLen)); @@ -219,10 +219,10 @@ static uint8_t ReverseBits(uint8_t v) CHIP_ERROR ASN1Reader::GetBitString(uint32_t & outVal) { // NOTE: only supports DER encoding. - ReturnErrorCodeIf(Value == nullptr, ASN1_ERROR_INVALID_STATE); - ReturnErrorCodeIf(ValueLen < 1, ASN1_ERROR_INVALID_ENCODING); - ReturnErrorCodeIf(ValueLen > 5, ASN1_ERROR_UNSUPPORTED_ENCODING); - ReturnErrorCodeIf(mElemStart + mHeadLen + ValueLen > mContainerEnd, ASN1_ERROR_UNDERRUN); + VerifyOrReturnError(Value != nullptr, ASN1_ERROR_INVALID_STATE); + VerifyOrReturnError(ValueLen >= 1, ASN1_ERROR_INVALID_ENCODING); + VerifyOrReturnError(ValueLen <= 5, ASN1_ERROR_UNSUPPORTED_ENCODING); + VerifyOrReturnError(mElemStart + mHeadLen + ValueLen <= mContainerEnd, ASN1_ERROR_UNDERRUN); if (ValueLen == 1) { @@ -244,7 +244,7 @@ CHIP_ERROR ASN1Reader::GetBitString(uint32_t & outVal) CHIP_ERROR ASN1Reader::DecodeHead() { const uint8_t * p = mElemStart; - ReturnErrorCodeIf(p >= mBufEnd, ASN1_ERROR_UNDERRUN); + VerifyOrReturnError(p < mBufEnd, ASN1_ERROR_UNDERRUN); Class = *p & 0xC0; Constructed = (*p & 0x20) != 0; @@ -254,7 +254,7 @@ CHIP_ERROR ASN1Reader::DecodeHead() VerifyOrReturnError(Tag < 0x1F, ASN1_ERROR_UNSUPPORTED_ENCODING); p++; - ReturnErrorCodeIf(p >= mBufEnd, ASN1_ERROR_UNDERRUN); + VerifyOrReturnError(p < mBufEnd, ASN1_ERROR_UNDERRUN); if ((*p & 0x80) == 0) { @@ -275,8 +275,8 @@ CHIP_ERROR ASN1Reader::DecodeHead() p++; for (; lenLen > 0; lenLen--, p++) { - ReturnErrorCodeIf(p >= mBufEnd, ASN1_ERROR_UNDERRUN); - ReturnErrorCodeIf((ValueLen & 0xFF000000) != 0, ASN1_ERROR_LENGTH_OVERFLOW); + VerifyOrReturnError(p < mBufEnd, ASN1_ERROR_UNDERRUN); + VerifyOrReturnError((ValueLen & 0xFF000000) == 0, ASN1_ERROR_LENGTH_OVERFLOW); ValueLen = (ValueLen << 8) | *p; } IndefiniteLen = false; diff --git a/src/lib/asn1/ASN1Writer.cpp b/src/lib/asn1/ASN1Writer.cpp index f916d138ae3c4d..4bdb8eaa04a091 100644 --- a/src/lib/asn1/ASN1Writer.cpp +++ b/src/lib/asn1/ASN1Writer.cpp @@ -72,7 +72,7 @@ size_t ASN1Writer::GetLengthWritten() const CHIP_ERROR ASN1Writer::PutInteger(int64_t val) { - ReturnErrorCodeIf(IsNullWriter(), CHIP_NO_ERROR); + VerifyOrReturnError(!IsNullWriter(), CHIP_NO_ERROR); uint8_t encodedVal[sizeof(int64_t)]; uint8_t valStart, valLen; @@ -94,7 +94,7 @@ CHIP_ERROR ASN1Writer::PutInteger(int64_t val) CHIP_ERROR ASN1Writer::PutBoolean(bool val) { - ReturnErrorCodeIf(IsNullWriter(), CHIP_NO_ERROR); + VerifyOrReturnError(!IsNullWriter(), CHIP_NO_ERROR); ReturnErrorOnFailure(EncodeHead(kASN1TagClass_Universal, kASN1UniversalTag_Boolean, false, 1)); @@ -170,7 +170,7 @@ static uint8_t HighestBit(uint32_t v) CHIP_ERROR ASN1Writer::PutBitString(uint32_t val) { - ReturnErrorCodeIf(IsNullWriter(), CHIP_NO_ERROR); + VerifyOrReturnError(!IsNullWriter(), CHIP_NO_ERROR); uint8_t len; if (val == 0) @@ -218,7 +218,7 @@ CHIP_ERROR ASN1Writer::PutBitString(uint32_t val) CHIP_ERROR ASN1Writer::PutBitString(uint8_t unusedBitCount, const uint8_t * encodedBits, uint16_t encodedBitsLen) { - ReturnErrorCodeIf(IsNullWriter(), CHIP_NO_ERROR); + VerifyOrReturnError(!IsNullWriter(), CHIP_NO_ERROR); ReturnErrorOnFailure(EncodeHead(kASN1TagClass_Universal, kASN1UniversalTag_BitString, false, encodedBitsLen + 1)); @@ -236,7 +236,7 @@ CHIP_ERROR ASN1Writer::PutBitString(uint8_t unusedBitCount, chip::TLV::TLVReader VerifyOrReturnError(CanCastTo(encodedBits.size() + 1), ASN1_ERROR_LENGTH_OVERFLOW); - ReturnErrorCodeIf(IsNullWriter(), CHIP_NO_ERROR); + VerifyOrReturnError(!IsNullWriter(), CHIP_NO_ERROR); ReturnErrorOnFailure( EncodeHead(kASN1TagClass_Universal, kASN1UniversalTag_BitString, false, static_cast(encodedBits.size() + 1))); @@ -250,7 +250,7 @@ CHIP_ERROR ASN1Writer::PutBitString(uint8_t unusedBitCount, chip::TLV::TLVReader CHIP_ERROR ASN1Writer::PutTime(const ASN1UniversalTime & val) { - ReturnErrorCodeIf(IsNullWriter(), CHIP_NO_ERROR); + VerifyOrReturnError(!IsNullWriter(), CHIP_NO_ERROR); char buf[ASN1UniversalTime::kASN1TimeStringMaxLength]; MutableCharSpan bufSpan(buf); @@ -276,7 +276,7 @@ CHIP_ERROR ASN1Writer::PutNull() CHIP_ERROR ASN1Writer::PutConstructedType(const uint8_t * val, uint16_t valLen) { - ReturnErrorCodeIf(IsNullWriter(), CHIP_NO_ERROR); + VerifyOrReturnError(!IsNullWriter(), CHIP_NO_ERROR); // Make sure we have enough space to write VerifyOrReturnError((mWritePoint + valLen) <= mBufEnd, ASN1_ERROR_OVERFLOW); @@ -298,7 +298,7 @@ CHIP_ERROR ASN1Writer::EndConstructedType() CHIP_ERROR ASN1Writer::StartEncapsulatedType(uint8_t cls, uint8_t tag, bool bitStringEncoding) { - ReturnErrorCodeIf(IsNullWriter(), CHIP_NO_ERROR); + VerifyOrReturnError(!IsNullWriter(), CHIP_NO_ERROR); ReturnErrorOnFailure(EncodeHead(cls, tag, false, kUnknownLength)); @@ -321,7 +321,7 @@ CHIP_ERROR ASN1Writer::EndEncapsulatedType() CHIP_ERROR ASN1Writer::PutValue(uint8_t cls, uint8_t tag, bool isConstructed, const uint8_t * val, uint16_t valLen) { - ReturnErrorCodeIf(IsNullWriter(), CHIP_NO_ERROR); + VerifyOrReturnError(!IsNullWriter(), CHIP_NO_ERROR); ReturnErrorOnFailure(EncodeHead(cls, tag, isConstructed, valLen)); @@ -337,7 +337,7 @@ CHIP_ERROR ASN1Writer::PutValue(uint8_t cls, uint8_t tag, bool isConstructed, ch VerifyOrReturnError(CanCastTo(val.size()), ASN1_ERROR_LENGTH_OVERFLOW); - ReturnErrorCodeIf(IsNullWriter(), CHIP_NO_ERROR); + VerifyOrReturnError(!IsNullWriter(), CHIP_NO_ERROR); ReturnErrorOnFailure(EncodeHead(cls, tag, isConstructed, static_cast(val.size()))); @@ -348,7 +348,7 @@ CHIP_ERROR ASN1Writer::PutValue(uint8_t cls, uint8_t tag, bool isConstructed, ch CHIP_ERROR ASN1Writer::EncodeHead(uint8_t cls, uint8_t tag, bool isConstructed, int32_t len) { - ReturnErrorCodeIf(IsNullWriter(), CHIP_NO_ERROR); + VerifyOrReturnError(!IsNullWriter(), CHIP_NO_ERROR); uint8_t bytesForLen; uint32_t totalLen; @@ -399,7 +399,7 @@ CHIP_ERROR ASN1Writer::EncodeHead(uint8_t cls, uint8_t tag, bool isConstructed, CHIP_ERROR ASN1Writer::WriteDeferredLength() { - ReturnErrorCodeIf(IsNullWriter(), CHIP_NO_ERROR); + VerifyOrReturnError(!IsNullWriter(), CHIP_NO_ERROR); VerifyOrReturnError(mDeferredLengthCount > 0, ASN1_ERROR_INVALID_STATE); diff --git a/src/lib/core/OTAImageHeader.cpp b/src/lib/core/OTAImageHeader.cpp index ab4b65635bc5f4..a4f535f50e6a9a 100644 --- a/src/lib/core/OTAImageHeader.cpp +++ b/src/lib/core/OTAImageHeader.cpp @@ -110,16 +110,16 @@ void OTAImageHeaderParser::Append(ByteSpan & buffer, uint32_t numBytes) CHIP_ERROR OTAImageHeaderParser::DecodeFixed() { - ReturnErrorCodeIf(mBufferOffset < kFixedHeaderSize, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mBufferOffset >= kFixedHeaderSize, CHIP_ERROR_BUFFER_TOO_SMALL); Encoding::LittleEndian::Reader reader(mBuffer.Get(), mBufferOffset); uint32_t fileIdentifier; uint64_t totalSize; ReturnErrorOnFailure(reader.Read32(&fileIdentifier).Read64(&totalSize).Read32(&mHeaderTlvSize).StatusCode()); - ReturnErrorCodeIf(fileIdentifier != kOTAImageFileIdentifier, CHIP_ERROR_INVALID_FILE_IDENTIFIER); + VerifyOrReturnError(fileIdentifier == kOTAImageFileIdentifier, CHIP_ERROR_INVALID_FILE_IDENTIFIER); // Safety check against malicious headers. - ReturnErrorCodeIf(mHeaderTlvSize > kMaxHeaderSize, CHIP_ERROR_NO_MEMORY); - ReturnErrorCodeIf(!mBuffer.Alloc(mHeaderTlvSize), CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(mHeaderTlvSize <= kMaxHeaderSize, CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(mBuffer.Alloc(mHeaderTlvSize), CHIP_ERROR_NO_MEMORY); mState = State::kTlv; mBufferOffset = 0; @@ -129,7 +129,7 @@ CHIP_ERROR OTAImageHeaderParser::DecodeFixed() CHIP_ERROR OTAImageHeaderParser::DecodeTlv(OTAImageHeader & header) { - ReturnErrorCodeIf(mBufferOffset < mHeaderTlvSize, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mBufferOffset >= mHeaderTlvSize, CHIP_ERROR_BUFFER_TOO_SMALL); TLV::TLVReader tlvReader; tlvReader.Init(mBuffer.Get(), mBufferOffset); @@ -146,7 +146,7 @@ CHIP_ERROR OTAImageHeaderParser::DecodeTlv(OTAImageHeader & header) ReturnErrorOnFailure(tlvReader.Get(header.mSoftwareVersion)); ReturnErrorOnFailure(tlvReader.Next(TLV::ContextTag(Tag::kSoftwareVersionString))); ReturnErrorOnFailure(tlvReader.Get(header.mSoftwareVersionString)); - ReturnErrorCodeIf(header.mSoftwareVersionString.size() > kMaxSoftwareVersionStringSize, CHIP_ERROR_INVALID_STRING_LENGTH); + VerifyOrReturnError(header.mSoftwareVersionString.size() <= kMaxSoftwareVersionStringSize, CHIP_ERROR_INVALID_STRING_LENGTH); ReturnErrorOnFailure(tlvReader.Next(TLV::ContextTag(Tag::kPayloadSize))); ReturnErrorOnFailure(tlvReader.Get(header.mPayloadSize)); ReturnErrorOnFailure(tlvReader.Next()); @@ -166,7 +166,7 @@ CHIP_ERROR OTAImageHeaderParser::DecodeTlv(OTAImageHeader & header) if (tlvReader.GetTag() == TLV::ContextTag(Tag::kReleaseNotesURL)) { ReturnErrorOnFailure(tlvReader.Get(header.mReleaseNotesURL)); - ReturnErrorCodeIf(header.mReleaseNotesURL.size() > kMaxReleaseNotesURLSize, CHIP_ERROR_INVALID_STRING_LENGTH); + VerifyOrReturnError(header.mReleaseNotesURL.size() <= kMaxReleaseNotesURLSize, CHIP_ERROR_INVALID_STRING_LENGTH); ReturnErrorOnFailure(tlvReader.Next()); } diff --git a/src/lib/dnssd/Advertiser_ImplMinimalMdns.cpp b/src/lib/dnssd/Advertiser_ImplMinimalMdns.cpp index ce46137c9a00e2..de8e8422027866 100644 --- a/src/lib/dnssd/Advertiser_ImplMinimalMdns.cpp +++ b/src/lib/dnssd/Advertiser_ImplMinimalMdns.cpp @@ -558,7 +558,7 @@ CHIP_ERROR AdvertiserMinMdns::Advertise(const OperationalAdvertisingParameters & DiscoveryFilter(DiscoveryFilterType::kCompressedFabricId, params.GetPeerId().GetCompressedFabricId())); FullQName compressedFabricIdSubtype = operationalAllocator->AllocateQName( nameBuffer, kSubtypeServiceNamePart, kOperationalServiceName, kOperationalProtocol, kLocalDomain); - ReturnErrorCodeIf(compressedFabricIdSubtype.nameCount == 0, CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(compressedFabricIdSubtype.nameCount != 0, CHIP_ERROR_NO_MEMORY); if (!operationalAllocator->AddResponder(compressedFabricIdSubtype, instanceName) .SetReportAdditional(instanceName) @@ -676,7 +676,7 @@ CHIP_ERROR AdvertiserMinMdns::Advertise(const CommissionAdvertisingParameters & MakeServiceSubtype(nameBuffer, sizeof(nameBuffer), DiscoveryFilter(DiscoveryFilterType::kVendorId, *vendorId)); FullQName vendorServiceName = allocator->AllocateQName(nameBuffer, kSubtypeServiceNamePart, serviceType, kCommissionProtocol, kLocalDomain); - ReturnErrorCodeIf(vendorServiceName.nameCount == 0, CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(vendorServiceName.nameCount != 0, CHIP_ERROR_NO_MEMORY); if (!allocator->AddResponder(vendorServiceName, instanceName) .SetReportAdditional(instanceName) @@ -693,7 +693,7 @@ CHIP_ERROR AdvertiserMinMdns::Advertise(const CommissionAdvertisingParameters & MakeServiceSubtype(nameBuffer, sizeof(nameBuffer), DiscoveryFilter(DiscoveryFilterType::kDeviceType, *deviceType)); FullQName vendorServiceName = allocator->AllocateQName(nameBuffer, kSubtypeServiceNamePart, serviceType, kCommissionProtocol, kLocalDomain); - ReturnErrorCodeIf(vendorServiceName.nameCount == 0, CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(vendorServiceName.nameCount != 0, CHIP_ERROR_NO_MEMORY); if (!allocator->AddResponder(vendorServiceName, instanceName) .SetReportAdditional(instanceName) @@ -713,7 +713,7 @@ CHIP_ERROR AdvertiserMinMdns::Advertise(const CommissionAdvertisingParameters & DiscoveryFilter(DiscoveryFilterType::kShortDiscriminator, params.GetShortDiscriminator())); FullQName shortServiceName = allocator->AllocateQName(nameBuffer, kSubtypeServiceNamePart, serviceType, kCommissionProtocol, kLocalDomain); - ReturnErrorCodeIf(shortServiceName.nameCount == 0, CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(shortServiceName.nameCount != 0, CHIP_ERROR_NO_MEMORY); if (!allocator->AddResponder(shortServiceName, instanceName) .SetReportAdditional(instanceName) @@ -730,7 +730,7 @@ CHIP_ERROR AdvertiserMinMdns::Advertise(const CommissionAdvertisingParameters & DiscoveryFilter(DiscoveryFilterType::kLongDiscriminator, params.GetLongDiscriminator())); FullQName longServiceName = allocator->AllocateQName(nameBuffer, kSubtypeServiceNamePart, serviceType, kCommissionProtocol, kLocalDomain); - ReturnErrorCodeIf(longServiceName.nameCount == 0, CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(longServiceName.nameCount != 0, CHIP_ERROR_NO_MEMORY); if (!allocator->AddResponder(longServiceName, instanceName) .SetReportAdditional(instanceName) .SetReportInServiceListing(true) @@ -746,7 +746,7 @@ CHIP_ERROR AdvertiserMinMdns::Advertise(const CommissionAdvertisingParameters & MakeServiceSubtype(nameBuffer, sizeof(nameBuffer), DiscoveryFilter(DiscoveryFilterType::kCommissioningMode)); FullQName longServiceName = allocator->AllocateQName(nameBuffer, kSubtypeServiceNamePart, serviceType, kCommissionProtocol, kLocalDomain); - ReturnErrorCodeIf(longServiceName.nameCount == 0, CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(longServiceName.nameCount != 0, CHIP_ERROR_NO_MEMORY); if (!allocator->AddResponder(longServiceName, instanceName) .SetReportAdditional(instanceName) .SetReportInServiceListing(true) diff --git a/src/lib/dnssd/Resolver_ImplMinimalMdns.cpp b/src/lib/dnssd/Resolver_ImplMinimalMdns.cpp index 8e913f2addb1c1..0a615fef4d62fb 100644 --- a/src/lib/dnssd/Resolver_ImplMinimalMdns.cpp +++ b/src/lib/dnssd/Resolver_ImplMinimalMdns.cpp @@ -590,7 +590,7 @@ CHIP_ERROR MinMdnsResolver::BuildQuery(QueryBuilder & builder, const ActiveResol break; } - ReturnErrorCodeIf(!qname.nameCount, CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(qname.nameCount, CHIP_ERROR_NO_MEMORY); mdns::Minimal::Query query(qname); query @@ -665,7 +665,7 @@ CHIP_ERROR MinMdnsResolver::BuildQuery(QueryBuilder & builder, const ActiveResol return CHIP_ERROR_INVALID_ARGUMENT; } - ReturnErrorCodeIf(!builder.Ok(), CHIP_ERROR_INTERNAL); + VerifyOrReturnError(builder.Ok(), CHIP_ERROR_INTERNAL); return CHIP_NO_ERROR; } @@ -681,7 +681,7 @@ CHIP_ERROR MinMdnsResolver::SendAllPendingQueries() } System::PacketBufferHandle buffer = System::PacketBufferHandle::New(kMdnsMaxPacketSize); - ReturnErrorCodeIf(buffer.IsNull(), CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(!buffer.IsNull(), CHIP_ERROR_NO_MEMORY); QueryBuilder builder(std::move(buffer)); builder.Header().SetMessageId(0); @@ -770,7 +770,7 @@ CHIP_ERROR MinMdnsResolver::ScheduleRetries() { MATTER_TRACE_SCOPE("Schedule retries", "MinMdnsResolver"); - ReturnErrorCodeIf(mSystemLayer == nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mSystemLayer != nullptr, CHIP_ERROR_INCORRECT_STATE); mSystemLayer->CancelTimer(&RetryCallback, this); std::optional delay = mActiveResolves.GetTimeUntilNextExpectedResponse(); diff --git a/src/lib/dnssd/ServiceNaming.cpp b/src/lib/dnssd/ServiceNaming.cpp index 405e10a69c6de9..d463a3ae8ebebd 100644 --- a/src/lib/dnssd/ServiceNaming.cpp +++ b/src/lib/dnssd/ServiceNaming.cpp @@ -30,7 +30,7 @@ namespace Dnssd { CHIP_ERROR MakeInstanceName(char * buffer, size_t bufferLen, const PeerId & peerId) { - ReturnErrorCodeIf(bufferLen <= Operational::kInstanceNameMaxLength, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(bufferLen > Operational::kInstanceNameMaxLength, CHIP_ERROR_BUFFER_TOO_SMALL); NodeId nodeId = peerId.GetNodeId(); CompressedFabricId fabricId = peerId.GetCompressedFabricId(); @@ -43,8 +43,8 @@ CHIP_ERROR MakeInstanceName(char * buffer, size_t bufferLen, const PeerId & peer CHIP_ERROR ExtractIdFromInstanceName(const char * name, PeerId * peerId) { - ReturnErrorCodeIf(name == nullptr, CHIP_ERROR_INVALID_ARGUMENT); - ReturnErrorCodeIf(peerId == nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(name != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(peerId != nullptr, CHIP_ERROR_INVALID_ARGUMENT); // Make sure the string is long enough. static constexpr size_t fabricIdByteLength = 8; @@ -55,24 +55,24 @@ CHIP_ERROR ExtractIdFromInstanceName(const char * name, PeerId * peerId) // Ensure we have at least totalLength chars. size_t len = strnlen(name, totalLength); - ReturnErrorCodeIf(len < totalLength, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(len >= totalLength, CHIP_ERROR_INVALID_ARGUMENT); // Check that we have a proper terminator. - ReturnErrorCodeIf(name[totalLength] != '\0' && name[totalLength] != '.', CHIP_ERROR_WRONG_NODE_ID); + VerifyOrReturnError(name[totalLength] == '\0' || name[totalLength] == '.', CHIP_ERROR_WRONG_NODE_ID); // Check what we have a separator where we expect. - ReturnErrorCodeIf(name[fabricIdStringLength] != '-', CHIP_ERROR_WRONG_NODE_ID); + VerifyOrReturnError(name[fabricIdStringLength] == '-', CHIP_ERROR_WRONG_NODE_ID); static constexpr size_t bufferSize = std::max(fabricIdByteLength, nodeIdByteLength); uint8_t buf[bufferSize]; - ReturnErrorCodeIf(Encoding::HexToBytes(name, fabricIdStringLength, buf, bufferSize) == 0, CHIP_ERROR_WRONG_NODE_ID); + VerifyOrReturnError(Encoding::HexToBytes(name, fabricIdStringLength, buf, bufferSize) != 0, CHIP_ERROR_WRONG_NODE_ID); // Buf now stores the fabric id, as big-endian bytes. static_assert(fabricIdByteLength == sizeof(uint64_t), "Wrong number of bytes"); peerId->SetCompressedFabricId(Encoding::BigEndian::Get64(buf)); - ReturnErrorCodeIf(Encoding::HexToBytes(name + fabricIdStringLength + 1, nodeIdStringLength, buf, bufferSize) == 0, - CHIP_ERROR_WRONG_NODE_ID); + VerifyOrReturnError(Encoding::HexToBytes(name + fabricIdStringLength + 1, nodeIdStringLength, buf, bufferSize) != 0, + CHIP_ERROR_WRONG_NODE_ID); // Buf now stores the node id id, as big-endian bytes. static_assert(nodeIdByteLength == sizeof(uint64_t), "Wrong number of bytes"); peerId->SetNodeId(Encoding::BigEndian::Get64(buf)); @@ -82,7 +82,7 @@ CHIP_ERROR ExtractIdFromInstanceName(const char * name, PeerId * peerId) CHIP_ERROR MakeHostName(char * buffer, size_t bufferLen, const chip::ByteSpan & macOrEui64) { - ReturnErrorCodeIf(bufferLen < macOrEui64.size() * 2 + 1, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(bufferLen >= macOrEui64.size() * 2 + 1, CHIP_ERROR_BUFFER_TOO_SMALL); int idx = 0; for (size_t i = 0; i < macOrEui64.size(); ++i) diff --git a/src/lib/dnssd/minimal_mdns/ResponseSender.cpp b/src/lib/dnssd/minimal_mdns/ResponseSender.cpp index 7aec6142f0b555..0128824542c681 100644 --- a/src/lib/dnssd/minimal_mdns/ResponseSender.cpp +++ b/src/lib/dnssd/minimal_mdns/ResponseSender.cpp @@ -200,7 +200,7 @@ CHIP_ERROR ResponseSender::Respond(uint16_t messageId, const QueryData & query, CHIP_ERROR ResponseSender::FlushReply() { - ReturnErrorCodeIf(!mResponseBuilder.HasPacketBuffer(), CHIP_NO_ERROR); // nothing to flush + VerifyOrReturnError(mResponseBuilder.HasPacketBuffer(), CHIP_NO_ERROR); // nothing to flush if (mResponseBuilder.HasResponseRecords()) { @@ -232,7 +232,7 @@ CHIP_ERROR ResponseSender::FlushReply() CHIP_ERROR ResponseSender::PrepareNewReplyPacket() { chip::System::PacketBufferHandle buffer = chip::System::PacketBufferHandle::New(kPacketSizeBytes); - ReturnErrorCodeIf(buffer.IsNull(), CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(!buffer.IsNull(), CHIP_ERROR_NO_MEMORY); mResponseBuilder.Reset(std::move(buffer)); mResponseBuilder.Header().SetMessageId(mSendState.GetMessageId()); diff --git a/src/lib/support/CHIPMem-Simple.cpp b/src/lib/support/CHIPMem-Simple.cpp index 8816afeaed21c5..dbbaa9634d7ba1 100644 --- a/src/lib/support/CHIPMem-Simple.cpp +++ b/src/lib/support/CHIPMem-Simple.cpp @@ -55,8 +55,8 @@ class HeapLocked CHIP_ERROR MemoryAllocatorInit(void * buf, size_t bufSize) { - ReturnErrorCodeIf(buf == nullptr, CHIP_ERROR_INVALID_ARGUMENT); - ReturnErrorCodeIf(gPrivateHeap != nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(buf != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(gPrivateHeap == nullptr, CHIP_ERROR_INCORRECT_STATE); PrivateHeapInit(buf, bufSize); gPrivateHeap = buf; diff --git a/src/lib/support/CodeUtils.h b/src/lib/support/CodeUtils.h index 0142bc8544ecb2..01cc80bffcbe6c 100644 --- a/src/lib/support/CodeUtils.h +++ b/src/lib/support/CodeUtils.h @@ -313,31 +313,6 @@ } while (false) #endif // CHIP_CONFIG_ERROR_SOURCE -/** - * @def ReturnErrorCodeIf(expr, code) - * - * @brief - * Returns a specified error code if expression evaluates to true - * - * Example usage: - * - * @code - * ReturnErrorCodeIf(state == kInitialized, CHIP_NO_ERROR); - * ReturnErrorCodeIf(state == kInitialized, CHIP_ERROR_INCORRECT_STATE); - * @endcode - * - * @param[in] expr A Boolean expression to be evaluated. - * @param[in] code A value to return if @a expr is false. - */ -#define ReturnErrorCodeIf(expr, code) \ - do \ - { \ - if (expr) \ - { \ - return code; \ - } \ - } while (false) - /** * @def SuccessOrExit(error) * diff --git a/src/lib/support/TestPersistentStorageDelegate.h b/src/lib/support/TestPersistentStorageDelegate.h index 7dc1c06008c77c..997448c03d017b 100644 --- a/src/lib/support/TestPersistentStorageDelegate.h +++ b/src/lib/support/TestPersistentStorageDelegate.h @@ -207,7 +207,7 @@ class TestPersistentStorageDelegate : public PersistentStorageDelegate protected: virtual CHIP_ERROR SyncGetKeyValueInternal(const char * key, void * buffer, uint16_t & size) { - ReturnErrorCodeIf(((buffer == nullptr) && (size != 0)), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError((buffer != nullptr) || (size == 0), CHIP_ERROR_INVALID_ARGUMENT); // Making sure poison keys are not accessed if (mPoisonKeys.find(std::string(key)) != mPoisonKeys.end()) @@ -226,8 +226,8 @@ class TestPersistentStorageDelegate : public PersistentStorageDelegate } uint16_t valueSizeUint16 = static_cast(valueSize); - ReturnErrorCodeIf(size == 0 && valueSizeUint16 == 0, CHIP_NO_ERROR); - ReturnErrorCodeIf(buffer == nullptr, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(size != 0 || valueSizeUint16 != 0, CHIP_NO_ERROR); + VerifyOrReturnError(buffer != nullptr, CHIP_ERROR_BUFFER_TOO_SMALL); uint16_t sizeToCopy = std::min(size, valueSizeUint16); diff --git a/src/messaging/ExchangeMessageDispatch.cpp b/src/messaging/ExchangeMessageDispatch.cpp index a94f1310549eb4..662a2e4d02d0d2 100644 --- a/src/messaging/ExchangeMessageDispatch.cpp +++ b/src/messaging/ExchangeMessageDispatch.cpp @@ -38,7 +38,7 @@ CHIP_ERROR ExchangeMessageDispatch::SendMessage(SessionManager * sessionManager, bool isReliableTransmission, Protocols::Id protocol, uint8_t type, System::PacketBufferHandle && message) { - ReturnErrorCodeIf(!MessagePermitted(protocol, type), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(MessagePermitted(protocol, type), CHIP_ERROR_INVALID_ARGUMENT); PayloadHeader payloadHeader; payloadHeader.SetExchangeID(exchangeId).SetMessageType(protocol, type).SetInitiator(isInitiator); diff --git a/src/platform/ASR/ASRFactoryDataProvider.cpp b/src/platform/ASR/ASRFactoryDataProvider.cpp index c1a436168f6246..204a2497739010 100755 --- a/src/platform/ASR/ASRFactoryDataProvider.cpp +++ b/src/platform/ASR/ASRFactoryDataProvider.cpp @@ -97,7 +97,7 @@ CHIP_ERROR ASRFactoryDataProvider::GetSpake2pSalt(MutableByteSpan & saltBuf) #if !CONFIG_ENABLE_ASR_FACTORY_DATA_PROVIDER #if defined(CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_SALT) saltB64Len = strlen(CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_SALT); - ReturnErrorCodeIf(saltB64Len > sizeof(saltB64), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(saltB64Len <= sizeof(saltB64), CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(saltB64, CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_SALT, saltB64Len); #else return CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; @@ -109,7 +109,7 @@ CHIP_ERROR ASRFactoryDataProvider::GetSpake2pSalt(MutableByteSpan & saltBuf) ReturnErrorOnFailure(err); size_t saltLen = chip::Base64Decode32(saltB64, saltB64Len, reinterpret_cast(saltB64)); - ReturnErrorCodeIf(saltLen > saltBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(saltLen <= saltBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(saltBuf.data(), saltB64, saltLen); saltBuf.reduce_size(saltLen); @@ -128,7 +128,7 @@ CHIP_ERROR ASRFactoryDataProvider::GetSpake2pVerifier(MutableByteSpan & verifier #if !CONFIG_ENABLE_ASR_FACTORY_DATA_PROVIDER #if defined(CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_VERIFIER) verifierB64Len = strlen(CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_VERIFIER); - ReturnErrorCodeIf(verifierB64Len > sizeof(verifierB64), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(verifierB64Len <= sizeof(verifierB64), CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(verifierB64, CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_VERIFIER, verifierB64Len); #else return CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; @@ -140,7 +140,7 @@ CHIP_ERROR ASRFactoryDataProvider::GetSpake2pVerifier(MutableByteSpan & verifier ReturnErrorOnFailure(err); verifierLen = chip::Base64Decode32(verifierB64, verifierB64Len, reinterpret_cast(verifierB64)); - ReturnErrorCodeIf(verifierLen > verifierBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(verifierLen <= verifierBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(verifierBuf.data(), verifierB64, verifierLen); verifierBuf.reduce_size(verifierLen); @@ -352,13 +352,13 @@ CHIP_ERROR ASRFactoryDataProvider::SignWithDeviceAttestationKey(const ByteSpan & CHIP_ERROR ASRFactoryDataProvider::GetVendorName(char * buf, size_t bufSize) { #if !CONFIG_ENABLE_ASR_FACTORY_DEVICE_INFO_PROVIDER - ReturnErrorCodeIf(bufSize < sizeof(CHIP_DEVICE_CONFIG_DEVICE_VENDOR_NAME), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(bufSize >= sizeof(CHIP_DEVICE_CONFIG_DEVICE_VENDOR_NAME), CHIP_ERROR_BUFFER_TOO_SMALL); strcpy(buf, CHIP_DEVICE_CONFIG_DEVICE_VENDOR_NAME); #else size_t buffer_len = ConfigurationManager::kMaxVendorNameLength + 1; uint8_t buffer[ConfigurationManager::kMaxVendorNameLength + 1] = { 0 }; ReturnErrorOnFailure(ASRConfig::ReadFactoryConfigValue(ASR_VENDOR_NAME_PARTITION, buffer, buffer_len, buffer_len)); - ReturnErrorCodeIf(bufSize < buffer_len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(bufSize >= buffer_len, CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(buf, buffer, buffer_len); buf[buffer_len] = 0; #endif @@ -380,13 +380,13 @@ CHIP_ERROR ASRFactoryDataProvider::GetVendorId(uint16_t & vendorId) CHIP_ERROR ASRFactoryDataProvider::GetProductName(char * buf, size_t bufSize) { #if !CONFIG_ENABLE_ASR_FACTORY_DEVICE_INFO_PROVIDER - ReturnErrorCodeIf(bufSize < sizeof(CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_NAME), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(bufSize >= sizeof(CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_NAME), CHIP_ERROR_BUFFER_TOO_SMALL); strcpy(buf, CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_NAME); #else size_t buffer_len = ConfigurationManager::kMaxProductNameLength + 1; uint8_t buffer[ConfigurationManager::kMaxProductNameLength + 1] = { 0 }; ReturnErrorOnFailure(ASRConfig::ReadFactoryConfigValue(ASR_PRODUCT_NAME_PARTITION, buffer, buffer_len, buffer_len)); - ReturnErrorCodeIf(bufSize < buffer_len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(bufSize >= buffer_len, CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(buf, buffer, buffer_len); buf[buffer_len] = 0; #endif @@ -413,7 +413,7 @@ CHIP_ERROR ASRFactoryDataProvider::GetPartNumber(char * buf, size_t bufSize) size_t buffer_len = ConfigurationManager::kMaxPartNumberLength + 1; uint8_t buffer[ConfigurationManager::kMaxPartNumberLength + 1] = { 0 }; ReturnErrorOnFailure(ASRConfig::ReadFactoryConfigValue(ASR_PART_NUMBER_PARTITION, buffer, buffer_len, buffer_len)); - ReturnErrorCodeIf(bufSize < buffer_len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(bufSize >= buffer_len, CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(buf, buffer, buffer_len); buf[buffer_len] = 0; #endif @@ -428,7 +428,7 @@ CHIP_ERROR ASRFactoryDataProvider::GetProductURL(char * buf, size_t bufSize) size_t buffer_len = ConfigurationManager::kMaxProductURLLength + 1; uint8_t buffer[ConfigurationManager::kMaxProductURLLength + 1] = { 0 }; ReturnErrorOnFailure(ASRConfig::ReadFactoryConfigValue(ASR_PRODUCT_URL_PARTITION, buffer, buffer_len, buffer_len)); - ReturnErrorCodeIf(bufSize < buffer_len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(bufSize >= buffer_len, CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(buf, buffer, buffer_len); buf[buffer_len] = 0; #endif @@ -443,7 +443,7 @@ CHIP_ERROR ASRFactoryDataProvider::GetProductLabel(char * buf, size_t bufSize) size_t buffer_len = ConfigurationManager::kMaxProductLabelLength + 1; uint8_t buffer[ConfigurationManager::kMaxProductLabelLength + 1] = { 0 }; ReturnErrorOnFailure(ASRConfig::ReadFactoryConfigValue(ASR_PRODUCT_LABEL_PARTITION, buffer, buffer_len, buffer_len)); - ReturnErrorCodeIf(bufSize < buffer_len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(bufSize >= buffer_len, CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(buf, buffer, buffer_len); buf[buffer_len] = 0; #endif @@ -453,13 +453,13 @@ CHIP_ERROR ASRFactoryDataProvider::GetProductLabel(char * buf, size_t bufSize) CHIP_ERROR ASRFactoryDataProvider::GetSerialNumber(char * buf, size_t bufSize) { #if !CONFIG_ENABLE_ASR_FACTORY_DEVICE_INFO_PROVIDER - ReturnErrorCodeIf(bufSize < sizeof(CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(bufSize >= sizeof(CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER), CHIP_ERROR_BUFFER_TOO_SMALL); strcpy(buf, CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER); #else size_t buffer_len = ConfigurationManager::kMaxSerialNumberLength + 1; uint8_t buffer[ConfigurationManager::kMaxSerialNumberLength + 1] = { 0 }; ReturnErrorOnFailure(ASRConfig::ReadFactoryConfigValue(ASR_SERIAL_NUMBER_PARTITION, buffer, buffer_len, buffer_len)); - ReturnErrorCodeIf(bufSize < buffer_len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(bufSize >= buffer_len, CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(buf, buffer, buffer_len); buf[buffer_len] = 0; #endif @@ -522,13 +522,13 @@ CHIP_ERROR ASRFactoryDataProvider::GetHardwareVersion(uint16_t & hardwareVersion CHIP_ERROR ASRFactoryDataProvider::GetHardwareVersionString(char * buf, size_t bufSize) { #if !CONFIG_ENABLE_ASR_FACTORY_DEVICE_INFO_PROVIDER - ReturnErrorCodeIf(bufSize < sizeof(CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION_STRING), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(bufSize >= sizeof(CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION_STRING), CHIP_ERROR_BUFFER_TOO_SMALL); strcpy(buf, CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION_STRING); #else size_t buffer_len = ConfigurationManager::kMaxHardwareVersionStringLength + 1; uint8_t buffer[ConfigurationManager::kMaxHardwareVersionStringLength + 1] = { 0 }; ReturnErrorOnFailure(ASRConfig::ReadFactoryConfigValue(ASR_HARDWARE_VERSION_STR_PARTITION, buffer, buffer_len, buffer_len)); - ReturnErrorCodeIf(bufSize < buffer_len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(bufSize >= buffer_len, CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(buf, buffer, buffer_len); buf[buffer_len] = 0; #endif @@ -545,8 +545,8 @@ CHIP_ERROR ASRFactoryDataProvider::GetRotatingDeviceIdUniqueId(MutableByteSpan & #ifdef CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID constexpr uint8_t uniqueId[] = CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID; - ReturnErrorCodeIf(sizeof(uniqueId) > uniqueIdSpan.size(), CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(sizeof(uniqueId) != ConfigurationManager::kRotatingDeviceIDUniqueIDLength, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(sizeof(uniqueId) <= uniqueIdSpan.size(), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(sizeof(uniqueId) == ConfigurationManager::kRotatingDeviceIDUniqueIDLength, CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(uniqueIdSpan.data(), uniqueId, sizeof(uniqueId)); uniqueIdSpan.reduce_size(sizeof(uniqueId)); return CHIP_NO_ERROR; @@ -555,11 +555,11 @@ CHIP_ERROR ASRFactoryDataProvider::GetRotatingDeviceIdUniqueId(MutableByteSpan & #define ROTATING_UNIQUE_ID_STRING_LEN ConfigurationManager::kRotatingDeviceIDUniqueIDLength * 2 uint8_t buffer[ROTATING_UNIQUE_ID_STRING_LEN] = { 0 }; size_t buffer_len = ROTATING_UNIQUE_ID_STRING_LEN; - ReturnErrorCodeIf(ConfigurationManager::kRotatingDeviceIDUniqueIDLength > uniqueIdSpan.size(), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(ConfigurationManager::kRotatingDeviceIDUniqueIDLength <= uniqueIdSpan.size(), CHIP_ERROR_BUFFER_TOO_SMALL); ReturnErrorOnFailure(ASRConfig::ReadFactoryConfigValue(ASR_ROTATING_UNIQUE_ID_PARTITION, buffer, buffer_len, buffer_len)); size_t bytesLen = chip::Encoding::HexToBytes(Uint8::to_char(buffer), ROTATING_UNIQUE_ID_STRING_LEN, uniqueIdSpan.data(), uniqueIdSpan.size()); - ReturnErrorCodeIf(bytesLen != ConfigurationManager::kRotatingDeviceIDUniqueIDLength, CHIP_ERROR_INVALID_STRING_LENGTH); + VerifyOrReturnError(bytesLen == ConfigurationManager::kRotatingDeviceIDUniqueIDLength, CHIP_ERROR_INVALID_STRING_LENGTH); uniqueIdSpan.reduce_size(bytesLen); return CHIP_NO_ERROR; #endif // CONFIG_ENABLE_ASR_FACTORY_DEVICE_INFO_PROVIDER diff --git a/src/platform/ASR/ASROTAImageProcessor.cpp b/src/platform/ASR/ASROTAImageProcessor.cpp index d83ba75362cb69..ca853ab5b50faf 100644 --- a/src/platform/ASR/ASROTAImageProcessor.cpp +++ b/src/platform/ASR/ASROTAImageProcessor.cpp @@ -211,7 +211,7 @@ CHIP_ERROR ASROTAImageProcessor::ProcessHeader(ByteSpan & block) CHIP_ERROR error = mHeaderParser.AccumulateAndDecode(block, header); // Needs more data to decode the header - ReturnErrorCodeIf(error == CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR); + VerifyOrReturnError(error != CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR); ReturnErrorOnFailure(error); ChipLogProgress(SoftwareUpdate, "Image Header software version: %ld payload size: %lu", header.mSoftwareVersion, diff --git a/src/platform/Ameba/AmebaOTAImageProcessor.cpp b/src/platform/Ameba/AmebaOTAImageProcessor.cpp index 78c1a8bdd2665c..f2752a6e0daaed 100644 --- a/src/platform/Ameba/AmebaOTAImageProcessor.cpp +++ b/src/platform/Ameba/AmebaOTAImageProcessor.cpp @@ -262,7 +262,7 @@ CHIP_ERROR AmebaOTAImageProcessor::ProcessHeader(ByteSpan & block) CHIP_ERROR error = mHeaderParser.AccumulateAndDecode(block, header); // Needs more data to decode the header - ReturnErrorCodeIf(error == CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR); + VerifyOrReturnError(error != CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR); ReturnErrorOnFailure(error); mParams.totalFileBytes = header.mPayloadSize; diff --git a/src/platform/Ameba/FactoryDataProvider.cpp b/src/platform/Ameba/FactoryDataProvider.cpp index d41f85669014b8..e7251a6f8084fd 100644 --- a/src/platform/Ameba/FactoryDataProvider.cpp +++ b/src/platform/Ameba/FactoryDataProvider.cpp @@ -174,8 +174,8 @@ CHIP_ERROR FactoryDataProvider::GetCertificationDeclaration(MutableByteSpan & ou if (kReadFromFlash) { - ReturnErrorCodeIf(outBuffer.size() < mFactoryData.dac.cd.len, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!mFactoryData.dac.cd.value, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(outBuffer.size() >= mFactoryData.dac.cd.len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData.dac.cd.value, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); memcpy(outBuffer.data(), mFactoryData.dac.cd.value, mFactoryData.dac.cd.len); @@ -204,8 +204,8 @@ CHIP_ERROR FactoryDataProvider::GetDeviceAttestationCert(MutableByteSpan & outBu if (kReadFromFlash) { - ReturnErrorCodeIf(outBuffer.size() < mFactoryData.dac.dac_cert.len, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!mFactoryData.dac.dac_cert.value, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(outBuffer.size() >= mFactoryData.dac.dac_cert.len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData.dac.dac_cert.value, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); memcpy(outBuffer.data(), mFactoryData.dac.dac_cert.value, mFactoryData.dac.dac_cert.len); @@ -226,8 +226,8 @@ CHIP_ERROR FactoryDataProvider::GetProductAttestationIntermediateCert(MutableByt if (kReadFromFlash) { - ReturnErrorCodeIf(outBuffer.size() < mFactoryData.dac.pai_cert.len, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!mFactoryData.dac.pai_cert.value, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(outBuffer.size() >= mFactoryData.dac.pai_cert.len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData.dac.pai_cert.value, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); memcpy(outBuffer.data(), mFactoryData.dac.pai_cert.value, mFactoryData.dac.pai_cert.len); @@ -254,7 +254,7 @@ CHIP_ERROR FactoryDataProvider::SignWithDeviceAttestationKey(const ByteSpan & me if (kReadFromFlash) { #if CONFIG_ENABLE_AMEBA_CRYPTO - ReturnErrorCodeIf(!mFactoryData.dac.dac_cert.value, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(mFactoryData.dac.dac_cert.value, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); // Extract public key from DAC cert. ByteSpan dacCertSpan{ reinterpret_cast(mFactoryData.dac.dac_cert.value), mFactoryData.dac.dac_cert.len }; chip::Crypto::P256PublicKey dacPublicKey; @@ -266,8 +266,8 @@ CHIP_ERROR FactoryDataProvider::SignWithDeviceAttestationKey(const ByteSpan & me err = decoder.GetSign(dacPublicKey.Bytes(), dacPublicKey.Length(), messageToSign.data(), messageToSign.size(), signature.Bytes()); #else - ReturnErrorCodeIf(!mFactoryData.dac.dac_cert.value, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); - ReturnErrorCodeIf(!mFactoryData.dac.dac_key.value, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(mFactoryData.dac.dac_cert.value, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(mFactoryData.dac.dac_key.value, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); // Extract public key from DAC cert. ByteSpan dacCertSpan{ reinterpret_cast(mFactoryData.dac.dac_cert.value), mFactoryData.dac.dac_cert.len }; chip::Crypto::P256PublicKey dacPublicKey; @@ -325,7 +325,7 @@ CHIP_ERROR FactoryDataProvider::GetSpake2pIterationCount(uint32_t & iterationCou if (kReadFromFlash) { - ReturnErrorCodeIf(mFactoryData.cdata.spake2_it == 0, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(mFactoryData.cdata.spake2_it != 0, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); iterationCount = mFactoryData.cdata.spake2_it; err = CHIP_NO_ERROR; } @@ -351,7 +351,7 @@ CHIP_ERROR FactoryDataProvider::GetSpake2pSalt(MutableByteSpan & saltBuf) if (kReadFromFlash) { saltB64Len = mFactoryData.cdata.spake2_salt.len; - ReturnErrorCodeIf(saltB64Len > sizeof(saltB64), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(saltB64Len <= sizeof(saltB64), CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(saltB64, mFactoryData.cdata.spake2_salt.value, saltB64Len); err = CHIP_NO_ERROR; } @@ -359,7 +359,7 @@ CHIP_ERROR FactoryDataProvider::GetSpake2pSalt(MutableByteSpan & saltBuf) { #if defined(CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_SALT) saltB64Len = strlen(CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_SALT); - ReturnErrorCodeIf(saltB64Len > sizeof(saltB64), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(saltB64Len <= sizeof(saltB64), CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(saltB64, CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_SALT, saltB64Len); err = CHIP_NO_ERROR; #endif // defined(CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_SALT) @@ -368,7 +368,7 @@ CHIP_ERROR FactoryDataProvider::GetSpake2pSalt(MutableByteSpan & saltBuf) ReturnErrorOnFailure(err); size_t saltLen = chip::Base64Decode32(saltB64, saltB64Len, reinterpret_cast(saltB64)); - ReturnErrorCodeIf(saltLen > saltBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(saltLen <= saltBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(saltBuf.data(), saltB64, saltLen); saltBuf.reduce_size(saltLen); @@ -387,7 +387,7 @@ CHIP_ERROR FactoryDataProvider::GetSpake2pVerifier(MutableByteSpan & verifierBuf if (kReadFromFlash) { verifierB64Len = mFactoryData.cdata.spake2_verifier.len; - ReturnErrorCodeIf(verifierB64Len > sizeof(verifierB64), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(verifierB64Len <= sizeof(verifierB64), CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(verifierB64, mFactoryData.cdata.spake2_verifier.value, verifierB64Len); err = CHIP_NO_ERROR; } @@ -395,7 +395,7 @@ CHIP_ERROR FactoryDataProvider::GetSpake2pVerifier(MutableByteSpan & verifierBuf { #if defined(CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_VERIFIER) verifierB64Len = strlen(CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_VERIFIER); - ReturnErrorCodeIf(verifierB64Len > sizeof(verifierB64), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(verifierB64Len <= sizeof(verifierB64), CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(verifierB64, CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_VERIFIER, verifierB64Len); err = CHIP_NO_ERROR; #endif // defined(CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_VERIFIER) @@ -403,7 +403,7 @@ CHIP_ERROR FactoryDataProvider::GetSpake2pVerifier(MutableByteSpan & verifierBuf ReturnErrorOnFailure(err); verifierLen = chip::Base64Decode32(verifierB64, verifierB64Len, reinterpret_cast(verifierB64)); - ReturnErrorCodeIf(verifierLen > verifierBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(verifierLen <= verifierBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(verifierBuf.data(), verifierB64, verifierLen); verifierBuf.reduce_size(verifierLen); @@ -416,7 +416,7 @@ CHIP_ERROR FactoryDataProvider::GetSetupPasscode(uint32_t & setupPasscode) if (kReadFromFlash) { - ReturnErrorCodeIf(mFactoryData.cdata.passcode == 0, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(mFactoryData.cdata.passcode != 0, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); setupPasscode = mFactoryData.cdata.passcode; err = CHIP_NO_ERROR; } @@ -442,15 +442,15 @@ CHIP_ERROR FactoryDataProvider::GetVendorName(char * buf, size_t bufSize) if (kReadFromFlash) { - ReturnErrorCodeIf(bufSize < mFactoryData.dii.vendor_name.len + 1, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!mFactoryData.dii.vendor_name.value, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(bufSize >= mFactoryData.dii.vendor_name.len + 1, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData.dii.vendor_name.value, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); memcpy(buf, mFactoryData.dii.vendor_name.value, mFactoryData.dii.vendor_name.len); buf[mFactoryData.dii.vendor_name.len] = 0; err = CHIP_NO_ERROR; } else { - ReturnErrorCodeIf(bufSize < sizeof(CHIP_DEVICE_CONFIG_DEVICE_VENDOR_NAME), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(bufSize >= sizeof(CHIP_DEVICE_CONFIG_DEVICE_VENDOR_NAME), CHIP_ERROR_BUFFER_TOO_SMALL); strcpy(buf, CHIP_DEVICE_CONFIG_DEVICE_VENDOR_NAME); err = CHIP_NO_ERROR; } @@ -482,15 +482,15 @@ CHIP_ERROR FactoryDataProvider::GetProductName(char * buf, size_t bufSize) if (kReadFromFlash) { - ReturnErrorCodeIf(bufSize < mFactoryData.dii.product_name.len + 1, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!mFactoryData.dii.product_name.value, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(bufSize >= mFactoryData.dii.product_name.len + 1, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData.dii.product_name.value, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); memcpy(buf, mFactoryData.dii.product_name.value, mFactoryData.dii.product_name.len); buf[mFactoryData.dii.product_name.len] = 0; err = CHIP_NO_ERROR; } else { - ReturnErrorCodeIf(bufSize < sizeof(CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_NAME), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(bufSize >= sizeof(CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_NAME), CHIP_ERROR_BUFFER_TOO_SMALL); strcpy(buf, CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_NAME); err = CHIP_NO_ERROR; } @@ -539,8 +539,8 @@ CHIP_ERROR FactoryDataProvider::GetSerialNumber(char * buf, size_t bufSize) if (kReadFromFlash) { - ReturnErrorCodeIf(bufSize < mFactoryData.dii.serial_num.len + 1, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!mFactoryData.dii.serial_num.value, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(bufSize >= mFactoryData.dii.serial_num.len + 1, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData.dii.serial_num.value, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); memcpy(buf, mFactoryData.dii.serial_num.value, mFactoryData.dii.serial_num.len); buf[mFactoryData.dii.serial_num.len] = 0; err = CHIP_NO_ERROR; @@ -550,15 +550,15 @@ CHIP_ERROR FactoryDataProvider::GetSerialNumber(char * buf, size_t bufSize) #ifdef CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER if (CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER[0] != 0) { - ReturnErrorCodeIf(sizeof(CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER) > bufSize, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(sizeof(CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER) <= bufSize, CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(buf, CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER, sizeof(CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER)); serialNumLen = sizeof(CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER) - 1; err = CHIP_NO_ERROR; } #endif // CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER - ReturnErrorCodeIf(serialNumLen >= bufSize, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(buf[serialNumLen] != 0, CHIP_ERROR_INVALID_STRING_LENGTH); + VerifyOrReturnError(serialNumLen < bufSize, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(buf[serialNumLen] == 0, CHIP_ERROR_INVALID_STRING_LENGTH); err = CHIP_NO_ERROR; } @@ -635,15 +635,16 @@ CHIP_ERROR FactoryDataProvider::GetHardwareVersionString(char * buf, size_t bufS if (kReadFromFlash) { - ReturnErrorCodeIf(bufSize < mFactoryData.dii.hw_ver_string.len + 1, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!mFactoryData.dii.hw_ver_string.value, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(bufSize >= mFactoryData.dii.hw_ver_string.len + 1, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData.dii.hw_ver_string.value, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); memcpy(buf, mFactoryData.dii.hw_ver_string.value, mFactoryData.dii.hw_ver_string.len); buf[mFactoryData.dii.hw_ver_string.len] = 0; err = CHIP_NO_ERROR; } else { - ReturnErrorCodeIf(bufSize < sizeof(CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION_STRING), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(bufSize >= sizeof(CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION_STRING), + CHIP_ERROR_BUFFER_TOO_SMALL); strcpy(buf, CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION_STRING); err = CHIP_NO_ERROR; } @@ -657,8 +658,8 @@ CHIP_ERROR FactoryDataProvider::GetRotatingDeviceIdUniqueId(MutableByteSpan & un if (kReadFromFlash) { - ReturnErrorCodeIf(uniqueIdSpan.size() < mFactoryData.dii.rd_id_uid.len, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!mFactoryData.dii.rd_id_uid.value, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(uniqueIdSpan.size() >= mFactoryData.dii.rd_id_uid.len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData.dii.rd_id_uid.value, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); memcpy(uniqueIdSpan.data(), mFactoryData.dii.rd_id_uid.value, mFactoryData.dii.rd_id_uid.len); err = CHIP_NO_ERROR; } @@ -671,8 +672,8 @@ CHIP_ERROR FactoryDataProvider::GetRotatingDeviceIdUniqueId(MutableByteSpan & un "Length of unique ID for rotating device ID is smaller than minimum."); constexpr uint8_t uniqueId[] = CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID; - ReturnErrorCodeIf(sizeof(uniqueId) > uniqueIdSpan.size(), CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(sizeof(uniqueId) != ConfigurationManager::kRotatingDeviceIDUniqueIDLength, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(sizeof(uniqueId) <= uniqueIdSpan.size(), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(sizeof(uniqueId) == ConfigurationManager::kRotatingDeviceIDUniqueIDLength, CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(uniqueIdSpan.data(), uniqueId, sizeof(uniqueId)); uniqueIdSpan.reduce_size(sizeof(uniqueId)); err = CHIP_NO_ERROR; diff --git a/src/platform/Beken/OTAImageProcessorImpl.cpp b/src/platform/Beken/OTAImageProcessorImpl.cpp index 770dfc223225a3..9fd7dda7ca7fff 100644 --- a/src/platform/Beken/OTAImageProcessorImpl.cpp +++ b/src/platform/Beken/OTAImageProcessorImpl.cpp @@ -346,7 +346,7 @@ CHIP_ERROR OTAImageProcessorImpl::ProcessHeader(ByteSpan & block) CHIP_ERROR error = mHeaderParser.AccumulateAndDecode(block, header); // Needs more data to decode the header - ReturnErrorCodeIf(error == CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR); + VerifyOrReturnError(error != CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR); ReturnErrorOnFailure(error); mParams.totalFileBytes = header.mPayloadSize; diff --git a/src/platform/Darwin/KeyValueStoreManagerImpl.mm b/src/platform/Darwin/KeyValueStoreManagerImpl.mm index ffb28435f642af..d59610eaf7a731 100644 --- a/src/platform/Darwin/KeyValueStoreManagerImpl.mm +++ b/src/platform/Darwin/KeyValueStoreManagerImpl.mm @@ -152,13 +152,13 @@ - (instancetype)initWithContext:(nonnull NSManagedObjectContext *)context key:(n return CHIP_NO_ERROR; } - ReturnErrorCodeIf(gContext != nullptr, CHIP_ERROR_INCORRECT_STATE); - ReturnErrorCodeIf(fileName == nullptr, CHIP_ERROR_INVALID_ARGUMENT); - ReturnErrorCodeIf(fileName[0] == '\0', CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(gContext == nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(fileName != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(fileName[0] != '\0', CHIP_ERROR_INVALID_ARGUMENT); NSURL * url = nullptr; NSString * filepath = [NSString stringWithUTF8String:fileName]; - ReturnErrorCodeIf(filepath == nil, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(filepath != nil, CHIP_ERROR_INVALID_ARGUMENT); // relative paths are relative to Documents folder if (![filepath hasPrefix:@"/"]) { @@ -178,12 +178,12 @@ - (instancetype)initWithContext:(nonnull NSManagedObjectContext *)context key:(n } else { url = [NSURL fileURLWithPath:filepath]; } - ReturnErrorCodeIf(url == nullptr, CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(url != nullptr, CHIP_ERROR_NO_MEMORY); ChipLogProgress(DeviceLayer, "KVS will be written to: %s", [[url absoluteString] UTF8String]); NSManagedObjectModel * model = CreateManagedObjectModel(); - ReturnErrorCodeIf(model == nullptr, CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(model != nullptr, CHIP_ERROR_NO_MEMORY); // setup persistent store coordinator @@ -220,9 +220,9 @@ - (instancetype)initWithContext:(nonnull NSManagedObjectContext *)context key:(n const char * key, void * value, size_t value_size, size_t * read_bytes_size, size_t offset) { @autoreleasepool { - ReturnErrorCodeIf(key == nullptr, CHIP_ERROR_INVALID_ARGUMENT); - ReturnErrorCodeIf(offset != 0, CHIP_ERROR_INVALID_ARGUMENT); - ReturnErrorCodeIf(gContext == nullptr, CHIP_ERROR_UNINITIALIZED); + VerifyOrReturnError(key != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(offset == 0, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(gContext != nullptr, CHIP_ERROR_UNINITIALIZED); KeyValueItem * item = FindItemForKey([[NSString alloc] initWithUTF8String:key], nil, true); if (!item) { @@ -261,8 +261,8 @@ - (instancetype)initWithContext:(nonnull NSManagedObjectContext *)context key:(n CHIP_ERROR KeyValueStoreManagerImpl::_Delete(const char * key) { @autoreleasepool { - ReturnErrorCodeIf(key == nullptr, CHIP_ERROR_INVALID_ARGUMENT); - ReturnErrorCodeIf(gContext == nullptr, CHIP_ERROR_UNINITIALIZED); + VerifyOrReturnError(key != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(gContext != nullptr, CHIP_ERROR_UNINITIALIZED); KeyValueItem * item = FindItemForKey([[NSString alloc] initWithUTF8String:key], nil); if (!item) { @@ -288,13 +288,13 @@ - (instancetype)initWithContext:(nonnull NSManagedObjectContext *)context key:(n CHIP_ERROR KeyValueStoreManagerImpl::_Put(const char * key, const void * value, size_t value_size) { @autoreleasepool { - ReturnErrorCodeIf(key == nullptr, CHIP_ERROR_INVALID_ARGUMENT); - ReturnErrorCodeIf(gContext == nullptr, CHIP_ERROR_UNINITIALIZED); + VerifyOrReturnError(key != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(gContext != nullptr, CHIP_ERROR_UNINITIALIZED); NSData * data = [[NSData alloc] initWithBytes:value length:value_size]; NSString * itemKey = [[NSString alloc] initWithUTF8String:key]; - ReturnErrorCodeIf(itemKey == nil, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(itemKey != nil, CHIP_ERROR_INVALID_ARGUMENT); KeyValueItem * item = FindItemForKey(itemKey, nil); if (!item) { diff --git a/src/platform/ESP32/ConfigurationManagerImpl.cpp b/src/platform/ESP32/ConfigurationManagerImpl.cpp index 78446432c58b0a..a12750c6a45e57 100644 --- a/src/platform/ESP32/ConfigurationManagerImpl.cpp +++ b/src/platform/ESP32/ConfigurationManagerImpl.cpp @@ -238,8 +238,9 @@ CHIP_ERROR ConfigurationManagerImpl::GetSoftwareVersionString(char * buf, size_t appDescription = esp_ota_get_app_description(); #endif - ReturnErrorCodeIf(bufSize < sizeof(appDescription->version), CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(sizeof(appDescription->version) > ConfigurationManager::kMaxSoftwareVersionStringLength, CHIP_ERROR_INTERNAL); + VerifyOrReturnError(bufSize >= sizeof(appDescription->version), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(sizeof(appDescription->version) <= ConfigurationManager::kMaxSoftwareVersionStringLength, + CHIP_ERROR_INTERNAL); strcpy(buf, appDescription->version); return CHIP_NO_ERROR; } diff --git a/src/platform/ESP32/ESP32Config.cpp b/src/platform/ESP32/ESP32Config.cpp index df48f5f2955793..3fd7d9ea777927 100644 --- a/src/platform/ESP32/ESP32Config.cpp +++ b/src/platform/ESP32/ESP32Config.cpp @@ -217,7 +217,7 @@ CHIP_ERROR ESP32Config::ReadConfigValueStr(Key key, char * buf, size_t bufSize, { return CHIP_ERROR_BUFFER_TOO_SMALL; } - ReturnErrorCodeIf(buf[outLen - 1] != 0, CHIP_ERROR_INVALID_STRING_LENGTH); + VerifyOrReturnError(buf[outLen - 1] == 0, CHIP_ERROR_INVALID_STRING_LENGTH); ReturnMappedErrorOnFailure(err); } diff --git a/src/platform/ESP32/ESP32EndpointQueueFilter.h b/src/platform/ESP32/ESP32EndpointQueueFilter.h index aa283d9b7fd770..cbf3304d97e573 100644 --- a/src/platform/ESP32/ESP32EndpointQueueFilter.h +++ b/src/platform/ESP32/ESP32EndpointQueueFilter.h @@ -29,8 +29,8 @@ class ESP32EndpointQueueFilter : public EndpointQueueFilter public: CHIP_ERROR SetMdnsHostName(const chip::CharSpan & hostName) { - ReturnErrorCodeIf(hostName.size() != sizeof(mHostNameBuffer), CHIP_ERROR_INVALID_ARGUMENT); - ReturnErrorCodeIf(!IsValidMdnsHostName(hostName), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(hostName.size() == sizeof(mHostNameBuffer), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(IsValidMdnsHostName(hostName), CHIP_ERROR_INVALID_ARGUMENT); memcpy(mHostNameBuffer, hostName.data(), hostName.size()); return CHIP_NO_ERROR; } diff --git a/src/platform/ESP32/ESP32FactoryDataProvider.cpp b/src/platform/ESP32/ESP32FactoryDataProvider.cpp index ace2a087de144b..03936c96c7421e 100644 --- a/src/platform/ESP32/ESP32FactoryDataProvider.cpp +++ b/src/platform/ESP32/ESP32FactoryDataProvider.cpp @@ -66,7 +66,7 @@ CHIP_ERROR ESP32FactoryDataProvider::GetSpake2pSalt(MutableByteSpan & saltBuf) ReturnErrorOnFailure(err); size_t saltLen = chip::Base64Decode32(saltB64, saltB64Len, reinterpret_cast(saltB64)); - ReturnErrorCodeIf(saltLen > saltBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(saltLen <= saltBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(saltBuf.data(), saltB64, saltLen); saltBuf.reduce_size(saltLen); @@ -88,7 +88,7 @@ CHIP_ERROR ESP32FactoryDataProvider::GetSpake2pVerifier(MutableByteSpan & verifi ReturnErrorOnFailure(err); verifierLen = chip::Base64Decode32(verifierB64, verifierB64Len, reinterpret_cast(verifierB64)); - ReturnErrorCodeIf(verifierLen > verifierBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(verifierLen <= verifierBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(verifierBuf.data(), verifierB64, verifierLen); verifierBuf.reduce_size(verifierLen); @@ -251,7 +251,7 @@ CHIP_ERROR ESP32FactoryDataProvider::GetProductFinish(app::Clusters::BasicInform uint32_t productFinish = 0; err = ESP32Config::ReadConfigValue(ESP32Config::kConfigKey_ProductFinish, productFinish); - ReturnErrorCodeIf(err != CHIP_NO_ERROR, CHIP_ERROR_NOT_IMPLEMENTED); + VerifyOrReturnError(err == CHIP_NO_ERROR, CHIP_ERROR_NOT_IMPLEMENTED); *finish = static_cast(productFinish); @@ -264,7 +264,7 @@ CHIP_ERROR ESP32FactoryDataProvider::GetProductPrimaryColor(app::Clusters::Basic uint32_t color = 0; err = ESP32Config::ReadConfigValue(ESP32Config::kConfigKey_ProductColor, color); - ReturnErrorCodeIf(err != CHIP_NO_ERROR, CHIP_ERROR_NOT_IMPLEMENTED); + VerifyOrReturnError(err == CHIP_NO_ERROR, CHIP_ERROR_NOT_IMPLEMENTED); *primaryColor = static_cast(color); diff --git a/src/platform/ESP32/KeyValueStoreManagerImpl.cpp b/src/platform/ESP32/KeyValueStoreManagerImpl.cpp index 3c587167334de2..96e68a6c2f8e5f 100644 --- a/src/platform/ESP32/KeyValueStoreManagerImpl.cpp +++ b/src/platform/ESP32/KeyValueStoreManagerImpl.cpp @@ -49,10 +49,10 @@ namespace { // Returns true if key is hashed, false otherwise. bool HashIfLongKey(const char * key, char * keyHash) { - ReturnErrorCodeIf(strlen(key) < NVS_KEY_NAME_MAX_SIZE, false); + VerifyOrReturnError(strlen(key) >= NVS_KEY_NAME_MAX_SIZE, false); uint8_t hashBuffer[chip::Crypto::kSHA1_Hash_Length]; - ReturnErrorCodeIf(Crypto::Hash_SHA1(Uint8::from_const_char(key), strlen(key), hashBuffer) != CHIP_NO_ERROR, false); + VerifyOrReturnError(Crypto::Hash_SHA1(Uint8::from_const_char(key), strlen(key), hashBuffer) == CHIP_NO_ERROR, false); BitFlags flags(Encoding::HexFlags::kNone); Encoding::BytesToHex(hashBuffer, NVS_KEY_NAME_MAX_SIZE / 2, keyHash, NVS_KEY_NAME_MAX_SIZE, flags); diff --git a/src/platform/ESP32/NetworkCommissioningDriver.cpp b/src/platform/ESP32/NetworkCommissioningDriver.cpp index 3845287cfdb919..9b1280f83d72b6 100644 --- a/src/platform/ESP32/NetworkCommissioningDriver.cpp +++ b/src/platform/ESP32/NetworkCommissioningDriver.cpp @@ -143,7 +143,7 @@ CHIP_ERROR ESPWiFiDriver::RevertConfiguration() size_t credentialsLen = 0; CHIP_ERROR error = PersistedStorage::KeyValueStoreMgr().Get(kWiFiSSIDKeyName, network.ssid, sizeof(network.ssid), &ssidLen); - ReturnErrorCodeIf(error == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND, CHIP_NO_ERROR); + VerifyOrReturnError(error != CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND, CHIP_NO_ERROR); VerifyOrExit(CanCastTo(ssidLen), error = CHIP_ERROR_INTERNAL); VerifyOrExit(PersistedStorage::KeyValueStoreMgr().Get(kWiFiCredentialsKeyName, network.credentials, sizeof(network.credentials), &credentialsLen) == CHIP_NO_ERROR, diff --git a/src/platform/ESP32/OTAImageProcessorImpl.cpp b/src/platform/ESP32/OTAImageProcessorImpl.cpp index ab27b9c50df0cb..284f21c0639eec 100644 --- a/src/platform/ESP32/OTAImageProcessorImpl.cpp +++ b/src/platform/ESP32/OTAImageProcessorImpl.cpp @@ -573,7 +573,7 @@ CHIP_ERROR OTAImageProcessorImpl::ProcessHeader(ByteSpan & block) CHIP_ERROR error = mHeaderParser.AccumulateAndDecode(block, header); // Need more data to decode the header - ReturnErrorCodeIf(error == CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR); + VerifyOrReturnError(error != CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR); ReturnErrorOnFailure(error); mParams.totalFileBytes = header.mPayloadSize; diff --git a/src/platform/ESP32/bluedroid/ChipDeviceScanner.cpp b/src/platform/ESP32/bluedroid/ChipDeviceScanner.cpp index 81421cf8d5f79a..fc8ac74384982b 100644 --- a/src/platform/ESP32/bluedroid/ChipDeviceScanner.cpp +++ b/src/platform/ESP32/bluedroid/ChipDeviceScanner.cpp @@ -70,7 +70,7 @@ void ChipDeviceScanner::RemoveDevice() CHIP_ERROR ChipDeviceScanner::StartScan(uint16_t timeout) { - ReturnErrorCodeIf(mIsScanning, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(!mIsScanning, CHIP_ERROR_INCORRECT_STATE); static esp_ble_scan_params_t ble_scan_params = { .scan_type = BLE_SCAN_TYPE_PASSIVE, .own_addr_type = BLE_ADDR_TYPE_RANDOM, @@ -98,7 +98,7 @@ CHIP_ERROR ChipDeviceScanner::StartScan(uint16_t timeout) CHIP_ERROR ChipDeviceScanner::StopScan() { - ReturnErrorCodeIf(!mIsScanning, CHIP_NO_ERROR); + VerifyOrReturnError(mIsScanning, CHIP_NO_ERROR); int rc = esp_ble_gap_stop_scanning(); if (rc != 0) diff --git a/src/platform/ESP32/nimble/ChipDeviceScanner.cpp b/src/platform/ESP32/nimble/ChipDeviceScanner.cpp index 4e01340558503f..89dbbd91f06594 100644 --- a/src/platform/ESP32/nimble/ChipDeviceScanner.cpp +++ b/src/platform/ESP32/nimble/ChipDeviceScanner.cpp @@ -95,7 +95,7 @@ int ChipDeviceScanner::OnBleCentralEvent(struct ble_gap_event * event, void * ar CHIP_ERROR ChipDeviceScanner::StartScan(uint16_t timeout) { - ReturnErrorCodeIf(mIsScanning, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(!mIsScanning, CHIP_ERROR_INCORRECT_STATE); uint8_t ownAddrType; struct ble_gap_disc_params discParams; @@ -135,7 +135,7 @@ CHIP_ERROR ChipDeviceScanner::StartScan(uint16_t timeout) CHIP_ERROR ChipDeviceScanner::StopScan() { - ReturnErrorCodeIf(!mIsScanning, CHIP_NO_ERROR); + VerifyOrReturnError(mIsScanning, CHIP_NO_ERROR); int rc = ble_gap_disc_cancel(); if (rc != 0) diff --git a/src/platform/Infineon/CYW30739/FactoryDataProvider.cpp b/src/platform/Infineon/CYW30739/FactoryDataProvider.cpp index 412259bda75013..6ed897bfd4859b 100644 --- a/src/platform/Infineon/CYW30739/FactoryDataProvider.cpp +++ b/src/platform/Infineon/CYW30739/FactoryDataProvider.cpp @@ -204,8 +204,8 @@ CHIP_ERROR FactoryDataProvider::GetRotatingDeviceIdUniqueId(MutableByteSpan & un constexpr uint8_t uniqueId[] = CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID; - ReturnErrorCodeIf(sizeof(uniqueId) > uniqueIdSpan.size(), CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(sizeof(uniqueId) != ConfigurationManager::kRotatingDeviceIDUniqueIDLength, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(sizeof(uniqueId) <= uniqueIdSpan.size(), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(sizeof(uniqueId) == ConfigurationManager::kRotatingDeviceIDUniqueIDLength, CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(uniqueIdSpan.data(), uniqueId, sizeof(uniqueId)); uniqueIdSpan.reduce_size(sizeof(uniqueId)); } diff --git a/src/platform/Infineon/CYW30739/KeyValueStoreManagerImpl.cpp b/src/platform/Infineon/CYW30739/KeyValueStoreManagerImpl.cpp index 079acbe90682d6..a77fc2c549be79 100644 --- a/src/platform/Infineon/CYW30739/KeyValueStoreManagerImpl.cpp +++ b/src/platform/Infineon/CYW30739/KeyValueStoreManagerImpl.cpp @@ -195,11 +195,11 @@ KeyValueStoreManagerImpl::KeyConfigIdEntry * KeyValueStoreManagerImpl::AllocateE { Optional freeConfigID; KeyConfigIdEntry * newEntry = FindEntry(key, &freeConfigID); - ReturnErrorCodeIf(newEntry != nullptr, newEntry); - ReturnErrorCodeIf(!freeConfigID.HasValue(), nullptr); + VerifyOrReturnError(newEntry == nullptr, newEntry); + VerifyOrReturnError(freeConfigID.HasValue(), nullptr); newEntry = Platform::New(freeConfigID.Value(), KeyStorage(key)); - ReturnErrorCodeIf(newEntry == nullptr, nullptr); + VerifyOrReturnError(newEntry != nullptr, nullptr); KeyConfigIdEntry * entry = static_cast(slist_tail(&mKeyConfigIdList)); if (entry == nullptr) diff --git a/src/platform/Infineon/CYW30739/OTAImageProcessorImpl.cpp b/src/platform/Infineon/CYW30739/OTAImageProcessorImpl.cpp index 087295247278b1..02c654d9294f16 100644 --- a/src/platform/Infineon/CYW30739/OTAImageProcessorImpl.cpp +++ b/src/platform/Infineon/CYW30739/OTAImageProcessorImpl.cpp @@ -228,7 +228,7 @@ CHIP_ERROR OTAImageProcessorImpl::ProcessHeader(ByteSpan & block) CHIP_ERROR error = mHeaderParser.AccumulateAndDecode(block, header); // Needs more data to decode the header - ReturnErrorCodeIf(error == CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR); + VerifyOrReturnError(error != CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR); ReturnErrorOnFailure(error); mParams.totalFileBytes = header.mPayloadSize; diff --git a/src/platform/Infineon/PSOC6/OTAImageProcessorImpl.cpp b/src/platform/Infineon/PSOC6/OTAImageProcessorImpl.cpp index d47434a80d4fb0..b6b3dfb9ed528c 100644 --- a/src/platform/Infineon/PSOC6/OTAImageProcessorImpl.cpp +++ b/src/platform/Infineon/PSOC6/OTAImageProcessorImpl.cpp @@ -68,7 +68,7 @@ CHIP_ERROR OTAImageProcessorImpl::ProcessHeader(ByteSpan & block) // If we have not received all the bytes of the OTAImageHeader yet, that is OK. // Return CHIP_NO_ERROR and expect that future blocks will contain the rest. - ReturnErrorCodeIf(error == CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR); + VerifyOrReturnError(error != CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR); // If there is some error other than "too small", return that so future // processing will be aborted. @@ -107,10 +107,10 @@ CHIP_ERROR OTAImageProcessorImpl::ProcessBlock(ByteSpan & block) bool OTAImageProcessorImpl::IsFirstImageRun() { OTARequestorInterface * requestor = GetRequestorInstance(); - ReturnErrorCodeIf(requestor == nullptr, false); + VerifyOrReturnError(requestor != nullptr, false); uint32_t currentVersion; - ReturnErrorCodeIf(ConfigurationMgr().GetSoftwareVersion(currentVersion) != CHIP_NO_ERROR, false); + VerifyOrReturnError(ConfigurationMgr().GetSoftwareVersion(currentVersion) == CHIP_NO_ERROR, false); ChipLogProgress(SoftwareUpdate, "%ld", currentVersion); ChipLogProgress(SoftwareUpdate, "%ld", requestor->GetTargetVersion()); diff --git a/src/platform/Linux/OTAImageProcessorImpl.cpp b/src/platform/Linux/OTAImageProcessorImpl.cpp index b6fe393e01e19d..207de208ee0188 100644 --- a/src/platform/Linux/OTAImageProcessorImpl.cpp +++ b/src/platform/Linux/OTAImageProcessorImpl.cpp @@ -226,7 +226,7 @@ CHIP_ERROR OTAImageProcessorImpl::ProcessHeader(ByteSpan & block) CHIP_ERROR error = mHeaderParser.AccumulateAndDecode(block, header); // Needs more data to decode the header - ReturnErrorCodeIf(error == CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR); + VerifyOrReturnError(error != CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR); ReturnErrorOnFailure(error); mParams.totalFileBytes = header.mPayloadSize; diff --git a/src/platform/NuttX/OTAImageProcessorImpl.cpp b/src/platform/NuttX/OTAImageProcessorImpl.cpp index b6fe393e01e19d..207de208ee0188 100644 --- a/src/platform/NuttX/OTAImageProcessorImpl.cpp +++ b/src/platform/NuttX/OTAImageProcessorImpl.cpp @@ -226,7 +226,7 @@ CHIP_ERROR OTAImageProcessorImpl::ProcessHeader(ByteSpan & block) CHIP_ERROR error = mHeaderParser.AccumulateAndDecode(block, header); // Needs more data to decode the header - ReturnErrorCodeIf(error == CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR); + VerifyOrReturnError(error != CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR); ReturnErrorOnFailure(error); mParams.totalFileBytes = header.mPayloadSize; diff --git a/src/platform/OpenThread/GenericNetworkCommissioningThreadDriver.cpp b/src/platform/OpenThread/GenericNetworkCommissioningThreadDriver.cpp index cb0b05a57e3510..0c1d482f84c751 100644 --- a/src/platform/OpenThread/GenericNetworkCommissioningThreadDriver.cpp +++ b/src/platform/OpenThread/GenericNetworkCommissioningThreadDriver.cpp @@ -95,7 +95,7 @@ CHIP_ERROR GenericThreadDriver::RevertConfiguration() // If no backup could be found, it means that the network configuration has not been modified // since the fail-safe was armed, so return with no error. - ReturnErrorCodeIf(error == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND, CHIP_NO_ERROR); + VerifyOrReturnError(error != CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND, CHIP_NO_ERROR); if (!GetEnabled()) { diff --git a/src/platform/OpenThread/GenericThreadBorderRouterDelegate.cpp b/src/platform/OpenThread/GenericThreadBorderRouterDelegate.cpp index b08b0ab47321b3..69676488adf219 100644 --- a/src/platform/OpenThread/GenericThreadBorderRouterDelegate.cpp +++ b/src/platform/OpenThread/GenericThreadBorderRouterDelegate.cpp @@ -219,7 +219,7 @@ CHIP_ERROR GenericOpenThreadBorderRouterDelegate::SetPendingDataset(const Thread datasetTlvs.mLength = pendingDataset.AsByteSpan().size(); { ScopedThreadLock threadLock; - ReturnErrorCodeIf(otDatasetSetPendingTlvs(otInst, &datasetTlvs) != OT_ERROR_NONE, CHIP_ERROR_INTERNAL); + VerifyOrReturnError(otDatasetSetPendingTlvs(otInst, &datasetTlvs) == OT_ERROR_NONE, CHIP_ERROR_INTERNAL); } return CHIP_NO_ERROR; } diff --git a/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.hpp b/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.hpp index 6916c096c9ce50..f15e22252d6ab9 100644 --- a/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.hpp +++ b/src/platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.hpp @@ -1798,7 +1798,7 @@ CHIP_ERROR GenericThreadStackManagerImpl_OpenThread::FromOtDnsRespons entryIndex++; } - ReturnErrorCodeIf(alloc.AnyAllocFailed(), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(!alloc.AnyAllocFailed(), CHIP_ERROR_BUFFER_TOO_SMALL); mdnsService.mTextEntries = serviceTxtEntries.mTxtEntries; mdnsService.mTextEntrySize = entryIndex; diff --git a/src/platform/OpenThread/OpenThreadDnssdImpl.cpp b/src/platform/OpenThread/OpenThreadDnssdImpl.cpp index f5b0a85f2d0d83..79a8608091b909 100644 --- a/src/platform/OpenThread/OpenThreadDnssdImpl.cpp +++ b/src/platform/OpenThread/OpenThreadDnssdImpl.cpp @@ -47,7 +47,7 @@ const char * GetProtocolString(DnssdServiceProtocol protocol) CHIP_ERROR OpenThreadDnssdPublishService(const DnssdService * service, DnssdPublishCallback callback, void * context) { #if CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT - ReturnErrorCodeIf(service == nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(service != nullptr, CHIP_ERROR_INVALID_ARGUMENT); if (strcmp(service->mHostName, "") != 0) { ReturnErrorOnFailure(ThreadStackMgr().SetupSrpHost(service->mHostName)); diff --git a/src/platform/Tizen/ConnectivityManagerImpl.cpp b/src/platform/Tizen/ConnectivityManagerImpl.cpp index 37a15bb9546c75..063765687b4071 100644 --- a/src/platform/Tizen/ConnectivityManagerImpl.cpp +++ b/src/platform/Tizen/ConnectivityManagerImpl.cpp @@ -115,7 +115,7 @@ ConnectivityManager::WiFiStationMode ConnectivityManagerImpl::_GetWiFiStationMod CHIP_ERROR err = CHIP_NO_ERROR; wifi_manager_device_state_e deviceState = WIFI_MANAGER_DEVICE_STATE_DEACTIVATED; - ReturnErrorCodeIf(mWiFiStationMode == kWiFiStationMode_ApplicationControlled, mWiFiStationMode); + VerifyOrReturnError(mWiFiStationMode != kWiFiStationMode_ApplicationControlled, mWiFiStationMode); err = Internal::WiFiMgr().GetDeviceState(&deviceState); VerifyOrReturnError(err == CHIP_NO_ERROR, mWiFiStationMode); @@ -130,7 +130,7 @@ CHIP_ERROR ConnectivityManagerImpl::_SetWiFiStationMode(ConnectivityManager::WiF CHIP_ERROR err = CHIP_NO_ERROR; wifi_manager_device_state_e deviceState = WIFI_MANAGER_DEVICE_STATE_DEACTIVATED; - ReturnErrorCodeIf(val == kWiFiStationMode_NotSupported, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(val != kWiFiStationMode_NotSupported, CHIP_ERROR_INVALID_ARGUMENT); if (val != kWiFiStationMode_ApplicationControlled) { diff --git a/src/platform/Zephyr/BLEAdvertisingArbiter.cpp b/src/platform/Zephyr/BLEAdvertisingArbiter.cpp index 4356ba9aa146ea..0fafdba94402b8 100644 --- a/src/platform/Zephyr/BLEAdvertisingArbiter.cpp +++ b/src/platform/Zephyr/BLEAdvertisingArbiter.cpp @@ -56,7 +56,7 @@ CHIP_ERROR RestartAdvertising() { // Note: bt_le_adv_stop() returns success when the advertising was not started ReturnErrorOnFailure(System::MapErrorZephyr(bt_le_adv_stop())); - ReturnErrorCodeIf(sys_slist_is_empty(&sRequests), CHIP_NO_ERROR); + VerifyOrReturnError(!sys_slist_is_empty(&sRequests), CHIP_NO_ERROR); const Request & top = ToRequest(sys_slist_peek_head(&sRequests)); bt_le_adv_param params = BT_LE_ADV_PARAM_INIT(top.options, top.minInterval, top.maxInterval, nullptr); diff --git a/src/platform/Zephyr/KeyValueStoreManagerImpl.cpp b/src/platform/Zephyr/KeyValueStoreManagerImpl.cpp index 03c82341a8fc31..95c004e7f7a8d8 100644 --- a/src/platform/Zephyr/KeyValueStoreManagerImpl.cpp +++ b/src/platform/Zephyr/KeyValueStoreManagerImpl.cpp @@ -195,9 +195,9 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Delete(const char * key) char fullKey[SETTINGS_MAX_NAME_LEN + 1]; ReturnErrorOnFailure(MakeFullKey(fullKey, key)); - ReturnErrorCodeIf(Get(key, nullptr, 0) == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND, - CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); - ReturnErrorCodeIf(settings_delete(fullKey) != 0, CHIP_ERROR_PERSISTED_STORAGE_FAILED); + VerifyOrReturnError(Get(key, nullptr, 0) != CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND, + CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(settings_delete(fullKey) == 0, CHIP_ERROR_PERSISTED_STORAGE_FAILED); return CHIP_NO_ERROR; } diff --git a/src/platform/Zephyr/SystemTimeSupport.cpp b/src/platform/Zephyr/SystemTimeSupport.cpp index c9ebdf7da2c31d..fc9485556abaa7 100644 --- a/src/platform/Zephyr/SystemTimeSupport.cpp +++ b/src/platform/Zephyr/SystemTimeSupport.cpp @@ -63,7 +63,7 @@ CHIP_ERROR ClockImpl::GetClock_RealTime(Microseconds64 & aCurTime) { // The real time can be configured by an application if it has access to a reliable time source. // Otherwise, just return an error so that Matter stack can fallback to Last Known UTC Time. - ReturnErrorCodeIf(gBootRealTime == kUnknownRealTime, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(gBootRealTime != kUnknownRealTime, CHIP_ERROR_INCORRECT_STATE); aCurTime = gBootRealTime + GetMonotonicMicroseconds64(); diff --git a/src/platform/android/AndroidConfig.cpp b/src/platform/android/AndroidConfig.cpp index 510008f4411947..e3e7f3a58bc064 100644 --- a/src/platform/android/AndroidConfig.cpp +++ b/src/platform/android/AndroidConfig.cpp @@ -196,11 +196,11 @@ CHIP_ERROR AndroidConfig::ReadConfigValue(Key key, uint32_t & val) CHIP_ERROR AndroidConfig::ReadConfigValue(Key key, uint64_t & val) { chip::DeviceLayer::StackUnlock unlock; - ReturnErrorCodeIf(!gAndroidConfigObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); - ReturnErrorCodeIf(gReadConfigValueLongMethod == nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(gAndroidConfigObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(gReadConfigValueLongMethod != nullptr, CHIP_ERROR_INCORRECT_STATE); JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - ReturnErrorCodeIf(env == nullptr, CHIP_ERROR_INTERNAL); + VerifyOrReturnError(env != nullptr, CHIP_ERROR_INTERNAL); UtfString space(env, key.Namespace); UtfString name(env, key.Name); @@ -223,11 +223,11 @@ CHIP_ERROR AndroidConfig::ReadConfigValue(Key key, uint64_t & val) CHIP_ERROR AndroidConfig::ReadConfigValueStr(Key key, char * buf, size_t bufSize, size_t & outLen) { chip::DeviceLayer::StackUnlock unlock; - ReturnErrorCodeIf(!gAndroidConfigObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); - ReturnErrorCodeIf(gReadConfigValueStrMethod == nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(gAndroidConfigObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(gReadConfigValueStrMethod != nullptr, CHIP_ERROR_INCORRECT_STATE); JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - ReturnErrorCodeIf(env == nullptr, CHIP_ERROR_INTERNAL); + VerifyOrReturnError(env != nullptr, CHIP_ERROR_INTERNAL); UtfString space(env, key.Namespace); UtfString name(env, key.Name); @@ -253,11 +253,11 @@ CHIP_ERROR AndroidConfig::ReadConfigValueStr(Key key, char * buf, size_t bufSize CHIP_ERROR AndroidConfig::ReadConfigValueBin(Key key, uint8_t * buf, size_t bufSize, size_t & outLen) { chip::DeviceLayer::StackUnlock unlock; - ReturnErrorCodeIf(!gAndroidConfigObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); - ReturnErrorCodeIf(gReadConfigValueBinMethod == nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(gAndroidConfigObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(gReadConfigValueBinMethod != nullptr, CHIP_ERROR_INCORRECT_STATE); JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - ReturnErrorCodeIf(env == nullptr, CHIP_ERROR_INTERNAL); + VerifyOrReturnError(env != nullptr, CHIP_ERROR_INTERNAL); UtfString space(env, key.Namespace); UtfString name(env, key.Name); @@ -300,11 +300,11 @@ CHIP_ERROR AndroidConfig::WriteConfigValue(Key key, uint32_t val) CHIP_ERROR AndroidConfig::WriteConfigValue(Key key, uint64_t val) { chip::DeviceLayer::StackUnlock unlock; - ReturnErrorCodeIf(!gAndroidConfigObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); - ReturnErrorCodeIf(gWriteConfigValueLongMethod == nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(gAndroidConfigObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(gWriteConfigValueLongMethod != nullptr, CHIP_ERROR_INCORRECT_STATE); JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - ReturnErrorCodeIf(env == nullptr, CHIP_ERROR_INTERNAL); + VerifyOrReturnError(env != nullptr, CHIP_ERROR_INTERNAL); UtfString space(env, key.Namespace); UtfString name(env, key.Name); @@ -325,11 +325,11 @@ CHIP_ERROR AndroidConfig::WriteConfigValue(Key key, uint64_t val) CHIP_ERROR AndroidConfig::WriteConfigValueStr(Key key, const char * str) { chip::DeviceLayer::StackUnlock unlock; - ReturnErrorCodeIf(!gAndroidConfigObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); - ReturnErrorCodeIf(gWriteConfigValueStrMethod == nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(gAndroidConfigObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(gWriteConfigValueStrMethod != nullptr, CHIP_ERROR_INCORRECT_STATE); JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - ReturnErrorCodeIf(env == nullptr, CHIP_ERROR_INTERNAL); + VerifyOrReturnError(env != nullptr, CHIP_ERROR_INTERNAL); UtfString space(env, key.Namespace); UtfString name(env, key.Name); @@ -376,12 +376,12 @@ CHIP_ERROR AndroidConfig::WriteConfigValueStr(Key key, const char * str, size_t CHIP_ERROR AndroidConfig::WriteConfigValueBin(Key key, const uint8_t * data, size_t dataLen) { chip::DeviceLayer::StackUnlock unlock; - ReturnErrorCodeIf(!gAndroidConfigObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); - ReturnErrorCodeIf(gWriteConfigValueBinMethod == nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(gAndroidConfigObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(gWriteConfigValueBinMethod != nullptr, CHIP_ERROR_INCORRECT_STATE); VerifyOrReturnError(chip::CanCastTo(dataLen), CHIP_ERROR_INVALID_ARGUMENT); JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - ReturnErrorCodeIf(env == nullptr, CHIP_ERROR_INTERNAL); + VerifyOrReturnError(env != nullptr, CHIP_ERROR_INTERNAL); UtfString space(env, key.Namespace); UtfString name(env, key.Name); @@ -403,11 +403,11 @@ CHIP_ERROR AndroidConfig::WriteConfigValueBin(Key key, const uint8_t * data, siz CHIP_ERROR AndroidConfig::ClearConfigValue(Key key) { chip::DeviceLayer::StackUnlock unlock; - ReturnErrorCodeIf(!gAndroidConfigObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); - ReturnErrorCodeIf(gClearConfigValueMethod == nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(gAndroidConfigObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(gClearConfigValueMethod != nullptr, CHIP_ERROR_INCORRECT_STATE); JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - ReturnErrorCodeIf(env == nullptr, CHIP_ERROR_INTERNAL); + VerifyOrReturnError(env != nullptr, CHIP_ERROR_INTERNAL); UtfString space(env, key.Namespace); UtfString name(env, key.Name); @@ -427,11 +427,11 @@ CHIP_ERROR AndroidConfig::ClearConfigValue(Key key) bool AndroidConfig::ConfigValueExists(Key key) { chip::DeviceLayer::StackUnlock unlock; - ReturnErrorCodeIf(!gAndroidConfigObject.HasValidObjectRef(), false); - ReturnErrorCodeIf(gConfigValueExistsMethod == nullptr, false); + VerifyOrReturnError(gAndroidConfigObject.HasValidObjectRef(), false); + VerifyOrReturnError(gConfigValueExistsMethod != nullptr, false); JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - ReturnErrorCodeIf(env == nullptr, false); + VerifyOrReturnError(env != nullptr, false); UtfString space(env, key.Namespace); UtfString name(env, key.Name); diff --git a/src/platform/android/ConfigurationManagerImpl.cpp b/src/platform/android/ConfigurationManagerImpl.cpp index defbb77f89b6f6..762e70f6079707 100644 --- a/src/platform/android/ConfigurationManagerImpl.cpp +++ b/src/platform/android/ConfigurationManagerImpl.cpp @@ -169,7 +169,7 @@ CHIP_ERROR ConfigurationManagerImpl::GetSoftwareVersionString(char * buf, size_t if (err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND) { - ReturnErrorCodeIf(bufSize < sizeof(CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(bufSize >= sizeof(CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING), CHIP_ERROR_BUFFER_TOO_SMALL); strcpy(buf, CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING); } @@ -208,7 +208,7 @@ CHIP_ERROR ConfigurationManagerImpl::GetCommissionableDeviceName(char * buf, siz if (err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND) { - ReturnErrorCodeIf(bufSize < sizeof(CHIP_DEVICE_CONFIG_DEVICE_NAME), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(bufSize >= sizeof(CHIP_DEVICE_CONFIG_DEVICE_NAME), CHIP_ERROR_BUFFER_TOO_SMALL); strcpy(buf, CHIP_DEVICE_CONFIG_DEVICE_NAME); } diff --git a/src/platform/android/DeviceInstanceInfoProviderImpl.cpp b/src/platform/android/DeviceInstanceInfoProviderImpl.cpp index cd07215c378e74..3faac5ba05fd22 100644 --- a/src/platform/android/DeviceInstanceInfoProviderImpl.cpp +++ b/src/platform/android/DeviceInstanceInfoProviderImpl.cpp @@ -32,7 +32,8 @@ CHIP_ERROR DeviceInstanceInfoProviderImpl::GetHardwareVersionString(char * buf, hardwareVersionLen); if (err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND) { - ReturnErrorCodeIf(bufSize < sizeof(CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION_STRING), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(bufSize >= sizeof(CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION_STRING), + CHIP_ERROR_BUFFER_TOO_SMALL); strcpy(buf, CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION_STRING); } @@ -81,7 +82,7 @@ CHIP_ERROR DeviceInstanceInfoProviderImpl::GetProductName(char * buf, size_t buf Internal::AndroidConfig::ReadConfigValueStr(Internal::AndroidConfig::kConfigKey_ProductName, buf, bufSize, productNameSize); if (err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND) { - ReturnErrorCodeIf(bufSize < sizeof(CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_NAME), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(bufSize >= sizeof(CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_NAME), CHIP_ERROR_BUFFER_TOO_SMALL); strcpy(buf, CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_NAME); } return CHIP_NO_ERROR; diff --git a/src/platform/android/DnssdImpl.cpp b/src/platform/android/DnssdImpl.cpp index 290b3497ea11d4..d93ec2c52d22a6 100644 --- a/src/platform/android/DnssdImpl.cpp +++ b/src/platform/android/DnssdImpl.cpp @@ -244,10 +244,10 @@ template CHIP_ERROR extractProtocol(const char * serviceType, char (&outServiceName)[N], DnssdServiceProtocol & outProtocol) { const char * dotPos = strrchr(serviceType, '.'); - ReturnErrorCodeIf(dotPos == nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(dotPos != nullptr, CHIP_ERROR_INVALID_ARGUMENT); size_t lengthWithoutProtocol = static_cast(dotPos - serviceType); - ReturnErrorCodeIf(lengthWithoutProtocol + 1 > N, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(lengthWithoutProtocol + 1 <= N, CHIP_ERROR_INVALID_ARGUMENT); memcpy(outServiceName, serviceType, lengthWithoutProtocol); outServiceName[lengthWithoutProtocol] = '\0'; // Set a null terminator @@ -267,7 +267,7 @@ CHIP_ERROR extractProtocol(const char * serviceType, char (&outServiceName)[N], return CHIP_ERROR_INVALID_ARGUMENT; } - ReturnErrorCodeIf(outProtocol == DnssdServiceProtocol::kDnssdProtocolUnknown, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(outProtocol != DnssdServiceProtocol::kDnssdProtocolUnknown, CHIP_ERROR_INVALID_ARGUMENT); return CHIP_NO_ERROR; } diff --git a/src/platform/android/KeyValueStoreManagerImpl.cpp b/src/platform/android/KeyValueStoreManagerImpl.cpp index 658532f6524137..9d382150ca3c91 100644 --- a/src/platform/android/KeyValueStoreManagerImpl.cpp +++ b/src/platform/android/KeyValueStoreManagerImpl.cpp @@ -80,11 +80,11 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Get(const char * key, void * value, size_t size_t offset_bytes) { CHIP_ERROR err = CHIP_NO_ERROR; - ReturnErrorCodeIf(!mKeyValueStoreManagerObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); - ReturnErrorCodeIf(mGetMethod == nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mKeyValueStoreManagerObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mGetMethod != nullptr, CHIP_ERROR_INCORRECT_STATE); JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - ReturnErrorCodeIf(env == nullptr, CHIP_JNI_ERROR_NO_ENV); + VerifyOrReturnError(env != nullptr, CHIP_JNI_ERROR_NO_ENV); chip::UtfString javaKey(env, key); @@ -118,7 +118,7 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Get(const char * key, void * value, size_t ChipLogError(DeviceLayer, "KeyValueStoreManager base64 decoding failed"); return CHIP_ERROR_INTEGRITY_CHECK_FAILED; } - ReturnErrorCodeIf(offset_bytes != 0 && offset_bytes >= decodedLength, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(offset_bytes == 0 || offset_bytes < decodedLength, CHIP_ERROR_INVALID_ARGUMENT); size_t read_size = std::min(value_size, decodedLength - offset_bytes); if (value_size + offset_bytes < decodedLength) { @@ -140,12 +140,12 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Get(const char * key, void * value, size_t CHIP_ERROR KeyValueStoreManagerImpl::_Put(const char * key, const void * value, size_t value_size) { - ReturnErrorCodeIf(!mKeyValueStoreManagerObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); - ReturnErrorCodeIf(mSetMethod == nullptr, CHIP_ERROR_INCORRECT_STATE); - ReturnErrorCodeIf(value_size > kMaxKvsValueBytes, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(mKeyValueStoreManagerObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mSetMethod != nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(value_size <= kMaxKvsValueBytes, CHIP_ERROR_INVALID_ARGUMENT); JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - ReturnErrorCodeIf(env == nullptr, CHIP_ERROR_INTERNAL); + VerifyOrReturnError(env != nullptr, CHIP_ERROR_INTERNAL); std::unique_ptr buffer(new char[BASE64_ENCODED_LEN(value_size) + 1]); @@ -170,11 +170,11 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Put(const char * key, const void * value, CHIP_ERROR KeyValueStoreManagerImpl::_Delete(const char * key) { - ReturnErrorCodeIf(!mKeyValueStoreManagerObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); - ReturnErrorCodeIf(mDeleteMethod == nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mKeyValueStoreManagerObject.HasValidObjectRef(), CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mDeleteMethod != nullptr, CHIP_ERROR_INCORRECT_STATE); JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - ReturnErrorCodeIf(env == nullptr, CHIP_ERROR_INTERNAL); + VerifyOrReturnError(env != nullptr, CHIP_ERROR_INTERNAL); UtfString javaKey(env, key); diff --git a/src/platform/cc13xx_26xx/FactoryDataProvider.cpp b/src/platform/cc13xx_26xx/FactoryDataProvider.cpp index 695d7e5f757f39..4244fd48b2a34d 100644 --- a/src/platform/cc13xx_26xx/FactoryDataProvider.cpp +++ b/src/platform/cc13xx_26xx/FactoryDataProvider.cpp @@ -135,8 +135,8 @@ CHIP_ERROR FactoryDataProvider::GetFirmwareInformation(MutableByteSpan & out_fir } CHIP_ERROR FactoryDataProvider::GetDeviceAttestationCert(MutableByteSpan & outBuffer) { - ReturnErrorCodeIf(outBuffer.size() < mFactoryData.dac_cert.len, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!mFactoryData.dac_cert.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(outBuffer.size() >= mFactoryData.dac_cert.len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData.dac_cert.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); memcpy(outBuffer.data(), mFactoryData.dac_cert.data, mFactoryData.dac_cert.len); outBuffer.reduce_size(mFactoryData.dac_cert.len); @@ -145,8 +145,8 @@ CHIP_ERROR FactoryDataProvider::GetDeviceAttestationCert(MutableByteSpan & outBu CHIP_ERROR FactoryDataProvider::GetProductAttestationIntermediateCert(MutableByteSpan & outBuffer) { - ReturnErrorCodeIf(outBuffer.size() < mFactoryData.pai_cert.len, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!mFactoryData.pai_cert.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(outBuffer.size() >= mFactoryData.pai_cert.len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData.pai_cert.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); memcpy(outBuffer.data(), mFactoryData.pai_cert.data, mFactoryData.pai_cert.len); outBuffer.reduce_size(mFactoryData.pai_cert.len); @@ -165,7 +165,7 @@ CHIP_ERROR FactoryDataProvider::SignWithDeviceAttestationKey(const ByteSpan & me // Extract public key from DAC cert. uint8_t dacBuf[600] = { 0 }; MutableByteSpan dacCertSpan(dacBuf); - ReturnErrorCodeIf(dacCertSpan.size() < mFactoryData.dac_cert.len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(dacCertSpan.size() >= mFactoryData.dac_cert.len, CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(dacCertSpan.data(), mFactoryData.dac_cert.data, mFactoryData.dac_cert.len); dacCertSpan.reduce_size(mFactoryData.dac_cert.len); chip::Crypto::P256PublicKey dacPublicKey; @@ -174,13 +174,13 @@ CHIP_ERROR FactoryDataProvider::SignWithDeviceAttestationKey(const ByteSpan & me uint8_t privKeyBuf[600] = { 0 }; MutableByteSpan privKeySpan(privKeyBuf); - ReturnErrorCodeIf(privKeySpan.size() < mFactoryData.dac_priv_key.len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(privKeySpan.size() >= mFactoryData.dac_priv_key.len, CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(privKeySpan.data(), mFactoryData.dac_priv_key.data, mFactoryData.dac_priv_key.len); privKeySpan.reduce_size(mFactoryData.dac_priv_key.len); uint8_t pubKeyBuf[600] = { 0 }; MutableByteSpan pubKeySpan(pubKeyBuf); - ReturnErrorCodeIf(pubKeySpan.size() < dacPublicKey.Length(), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(pubKeySpan.size() >= dacPublicKey.Length(), CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(pubKeySpan.data(), dacPublicKey.Bytes(), dacPublicKey.Length()); pubKeySpan.reduce_size(dacPublicKey.Length()); @@ -191,8 +191,8 @@ CHIP_ERROR FactoryDataProvider::SignWithDeviceAttestationKey(const ByteSpan & me } CHIP_ERROR FactoryDataProvider::GetSetupDiscriminator(uint16_t & setupDiscriminator) { - ReturnErrorCodeIf(sizeof(setupDiscriminator) < mFactoryData.discriminator.len, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!mFactoryData.discriminator.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(sizeof(setupDiscriminator) >= mFactoryData.discriminator.len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData.discriminator.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); memcpy(&setupDiscriminator, mFactoryData.discriminator.data, mFactoryData.discriminator.len); return CHIP_NO_ERROR; } @@ -202,24 +202,24 @@ CHIP_ERROR FactoryDataProvider::SetSetupDiscriminator(uint16_t setupDiscriminato } CHIP_ERROR FactoryDataProvider::GetSpake2pIterationCount(uint32_t & iterationCount) { - ReturnErrorCodeIf(sizeof(iterationCount) < mFactoryData.spake2p_it.len, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!mFactoryData.spake2p_it.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(sizeof(iterationCount) >= mFactoryData.spake2p_it.len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData.spake2p_it.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); memset(&iterationCount, 0, sizeof(iterationCount)); memcpy(&iterationCount, mFactoryData.spake2p_it.data, mFactoryData.spake2p_it.len); return CHIP_NO_ERROR; } CHIP_ERROR FactoryDataProvider::GetSpake2pSalt(MutableByteSpan & saltBuf) { - ReturnErrorCodeIf(saltBuf.size() < mFactoryData.spake2p_salt.len, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!mFactoryData.spake2p_salt.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(saltBuf.size() >= mFactoryData.spake2p_salt.len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData.spake2p_salt.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); memcpy(saltBuf.data(), mFactoryData.spake2p_salt.data, mFactoryData.spake2p_salt.len); saltBuf.reduce_size(mFactoryData.spake2p_salt.len); return CHIP_NO_ERROR; } CHIP_ERROR FactoryDataProvider::GetSpake2pVerifier(MutableByteSpan & verifierBuf, size_t & verifierLen) { - ReturnErrorCodeIf(verifierBuf.size() < mFactoryData.spake2p_verifier.len, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!mFactoryData.spake2p_verifier.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(verifierBuf.size() >= mFactoryData.spake2p_verifier.len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData.spake2p_verifier.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); memcpy(verifierBuf.data(), mFactoryData.spake2p_verifier.data, mFactoryData.spake2p_verifier.len); verifierLen = mFactoryData.spake2p_verifier.len; verifierBuf.reduce_size(verifierLen); @@ -227,8 +227,8 @@ CHIP_ERROR FactoryDataProvider::GetSpake2pVerifier(MutableByteSpan & verifierBuf } CHIP_ERROR FactoryDataProvider::GetSetupPasscode(uint32_t & setupPasscode) { - ReturnErrorCodeIf(sizeof(setupPasscode) < mFactoryData.passcode.len, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!mFactoryData.passcode.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(sizeof(setupPasscode) >= mFactoryData.passcode.len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData.passcode.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); memcpy(&setupPasscode, mFactoryData.passcode.data, mFactoryData.passcode.len); return CHIP_NO_ERROR; } @@ -238,23 +238,23 @@ CHIP_ERROR FactoryDataProvider::SetSetupPasscode(uint32_t setupPasscode) } CHIP_ERROR FactoryDataProvider::GetVendorName(char * buf, size_t bufSize) { - ReturnErrorCodeIf(bufSize < mFactoryData.vendor_name.len + 1, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!mFactoryData.vendor_name.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(bufSize >= mFactoryData.vendor_name.len + 1, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData.vendor_name.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); memcpy(buf, mFactoryData.vendor_name.data, mFactoryData.vendor_name.len); buf[mFactoryData.vendor_name.len] = '\0'; return CHIP_NO_ERROR; } CHIP_ERROR FactoryDataProvider::GetVendorId(uint16_t & vendorId) { - ReturnErrorCodeIf(sizeof(vendorId) < mFactoryData.vendor_id.len, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!mFactoryData.vendor_id.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(sizeof(vendorId) >= mFactoryData.vendor_id.len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData.vendor_id.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); memcpy(&vendorId, mFactoryData.vendor_id.data, mFactoryData.vendor_id.len); return CHIP_NO_ERROR; } CHIP_ERROR FactoryDataProvider::GetProductName(char * buf, size_t bufSize) { - ReturnErrorCodeIf(bufSize < mFactoryData.product_name.len + 1, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!mFactoryData.product_name.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(bufSize >= mFactoryData.product_name.len + 1, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData.product_name.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); memset(buf, 0, bufSize); memcpy(buf, mFactoryData.product_name.data, mFactoryData.product_name.len); buf[mFactoryData.product_name.len] = '\0'; @@ -262,8 +262,8 @@ CHIP_ERROR FactoryDataProvider::GetProductName(char * buf, size_t bufSize) } CHIP_ERROR FactoryDataProvider::GetProductId(uint16_t & productId) { - ReturnErrorCodeIf(sizeof(productId) < mFactoryData.product_id.len, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!mFactoryData.product_id.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(sizeof(productId) >= mFactoryData.product_id.len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData.product_id.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); memcpy(&productId, mFactoryData.product_id.data, mFactoryData.product_id.len); return CHIP_NO_ERROR; } @@ -282,8 +282,8 @@ CHIP_ERROR FactoryDataProvider::GetProductLabel(char * buf, size_t bufSize) CHIP_ERROR FactoryDataProvider::GetSerialNumber(char * buf, size_t bufSize) { - ReturnErrorCodeIf(bufSize < mFactoryData.serial_number.len + 1, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!mFactoryData.serial_number.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(bufSize >= mFactoryData.serial_number.len + 1, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData.serial_number.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); memset(buf, 0, bufSize); memcpy(buf, mFactoryData.serial_number.data, mFactoryData.serial_number.len); buf[mFactoryData.serial_number.len] = '\0'; @@ -292,7 +292,7 @@ CHIP_ERROR FactoryDataProvider::GetSerialNumber(char * buf, size_t bufSize) CHIP_ERROR FactoryDataProvider::GetManufacturingDate(uint16_t & year, uint8_t & month, uint8_t & day) { - ReturnErrorCodeIf(!mFactoryData.manufacturing_date.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(mFactoryData.manufacturing_date.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); uint8_t tmp[10] = { 0 }; memcpy(tmp, mFactoryData.manufacturing_date.data, 10); year = ((tmp[0] - 0x30) * 1000) + ((tmp[1] - 0x30) * 100) + ((tmp[2] - 0x30) * 10) + (tmp[3] - 0x30); @@ -303,15 +303,15 @@ CHIP_ERROR FactoryDataProvider::GetManufacturingDate(uint16_t & year, uint8_t & CHIP_ERROR FactoryDataProvider::GetHardwareVersion(uint16_t & hardwareVersion) { - ReturnErrorCodeIf(sizeof(hardwareVersion) < mFactoryData.hw_ver.len, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!mFactoryData.hw_ver.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(sizeof(hardwareVersion) >= mFactoryData.hw_ver.len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData.hw_ver.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); memcpy(&hardwareVersion, mFactoryData.hw_ver.data, mFactoryData.hw_ver.len); return CHIP_NO_ERROR; } CHIP_ERROR FactoryDataProvider::GetHardwareVersionString(char * buf, size_t bufSize) { - ReturnErrorCodeIf(bufSize < mFactoryData.hw_ver_str.len + 1, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!mFactoryData.hw_ver_str.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(bufSize >= mFactoryData.hw_ver_str.len + 1, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData.hw_ver_str.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); memset(buf, 0, bufSize); memcpy(buf, mFactoryData.hw_ver_str.data, mFactoryData.hw_ver_str.len); buf[mFactoryData.hw_ver_str.len] = '\0'; @@ -321,8 +321,8 @@ CHIP_ERROR FactoryDataProvider::GetHardwareVersionString(char * buf, size_t bufS CHIP_ERROR FactoryDataProvider::GetRotatingDeviceIdUniqueId(MutableByteSpan & uniqueIdSpan) { - ReturnErrorCodeIf(uniqueIdSpan.size() < mFactoryData.rd_uniqueid.len, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!mFactoryData.rd_uniqueid.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(uniqueIdSpan.size() >= mFactoryData.rd_uniqueid.len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData.rd_uniqueid.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); memcpy(uniqueIdSpan.data(), mFactoryData.rd_uniqueid.data, mFactoryData.rd_uniqueid.len); uniqueIdSpan.reduce_size(mFactoryData.rd_uniqueid.len); diff --git a/src/platform/mt793x/OTAImageProcessorImpl.cpp b/src/platform/mt793x/OTAImageProcessorImpl.cpp index 98685242aa4347..03a1d87dccacf5 100644 --- a/src/platform/mt793x/OTAImageProcessorImpl.cpp +++ b/src/platform/mt793x/OTAImageProcessorImpl.cpp @@ -255,7 +255,7 @@ CHIP_ERROR OTAImageProcessorImpl::ProcessHeader(ByteSpan & block) CHIP_ERROR error = mHeaderParser.AccumulateAndDecode(block, header); // Needs more data to decode the header - ReturnErrorCodeIf(error == CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR); + VerifyOrReturnError(error != CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR); ReturnErrorOnFailure(error); ChipLogProgress(SoftwareUpdate, "Image Header software version: %ld payload size: %lu", header.mSoftwareVersion, (long unsigned int) header.mPayloadSize); diff --git a/src/platform/nrfconnect/DeviceInstanceInfoProviderImpl.cpp b/src/platform/nrfconnect/DeviceInstanceInfoProviderImpl.cpp index ed4f2124edf754..1d30d5a9d38f5a 100644 --- a/src/platform/nrfconnect/DeviceInstanceInfoProviderImpl.cpp +++ b/src/platform/nrfconnect/DeviceInstanceInfoProviderImpl.cpp @@ -28,13 +28,13 @@ CHIP_ERROR DeviceInstanceInfoProviderImpl::GetRotatingDeviceIdUniqueId(MutableBy static_assert(ConfigurationManager::kRotatingDeviceIDUniqueIDLength >= ConfigurationManager::kMinRotatingDeviceIDUniqueIDLength, "Length of unique ID for rotating device ID is smaller than minimum."); - ReturnErrorCodeIf(ConfigurationManager::kRotatingDeviceIDUniqueIDLength > uniqueIdSpan.size(), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(ConfigurationManager::kRotatingDeviceIDUniqueIDLength <= uniqueIdSpan.size(), CHIP_ERROR_BUFFER_TOO_SMALL); size_t bytesLen = chip::Encoding::HexToBytes(CONFIG_CHIP_DEVICE_ROTATING_DEVICE_UID, ConfigurationManager::kRotatingDeviceIDUniqueIDLength * 2, uniqueIdSpan.data(), uniqueIdSpan.size()); - ReturnErrorCodeIf(bytesLen != ConfigurationManager::kRotatingDeviceIDUniqueIDLength, CHIP_ERROR_INVALID_STRING_LENGTH); + VerifyOrReturnError(bytesLen == ConfigurationManager::kRotatingDeviceIDUniqueIDLength, CHIP_ERROR_INVALID_STRING_LENGTH); uniqueIdSpan.reduce_size(bytesLen); return CHIP_NO_ERROR; diff --git a/src/platform/nrfconnect/DiagnosticDataProviderImplNrf.cpp b/src/platform/nrfconnect/DiagnosticDataProviderImplNrf.cpp index e71e6e392c9edd..2c4b3b4ff934f4 100644 --- a/src/platform/nrfconnect/DiagnosticDataProviderImplNrf.cpp +++ b/src/platform/nrfconnect/DiagnosticDataProviderImplNrf.cpp @@ -46,7 +46,7 @@ CHIP_ERROR DiagnosticDataProviderImplNrf::GetWiFiBssId(MutableByteSpan & value) { WiFiManager::WiFiInfo info; ReturnErrorOnFailure(WiFiManager::Instance().GetWiFiInfo(info)); - ReturnErrorCodeIf(sizeof(info.mBssId) >= value.size(), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(sizeof(info.mBssId) < value.size(), CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(value.data(), info.mBssId, sizeof(info.mBssId)); value.reduce_size(sizeof(info.mBssId)); diff --git a/src/platform/nrfconnect/FactoryDataProvider.cpp b/src/platform/nrfconnect/FactoryDataProvider.cpp index aaa6f4b93e12bb..a93239ac98884a 100644 --- a/src/platform/nrfconnect/FactoryDataProvider.cpp +++ b/src/platform/nrfconnect/FactoryDataProvider.cpp @@ -40,8 +40,8 @@ CHIP_ERROR LoadKeypairFromRaw(ByteSpan privateKey, ByteSpan publicKey, Crypto::P CHIP_ERROR GetFactoryDataString(const FactoryDataString & str, char * buf, size_t bufSize) { - ReturnErrorCodeIf(bufSize < str.len + 1, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!str.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(bufSize >= str.len + 1, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(str.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); memcpy(buf, str.data, str.len); buf[str.len] = 0; @@ -128,8 +128,8 @@ CHIP_ERROR FactoryDataProvider::GetFirmwareInformation(Mutable template CHIP_ERROR FactoryDataProvider::GetDeviceAttestationCert(MutableByteSpan & outBuffer) { - ReturnErrorCodeIf(outBuffer.size() < mFactoryData.dac_cert.len, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!mFactoryData.dac_cert.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(outBuffer.size() >= mFactoryData.dac_cert.len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData.dac_cert.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); memcpy(outBuffer.data(), mFactoryData.dac_cert.data, mFactoryData.dac_cert.len); @@ -141,8 +141,8 @@ CHIP_ERROR FactoryDataProvider::GetDeviceAttestationCert(Mutab template CHIP_ERROR FactoryDataProvider::GetProductAttestationIntermediateCert(MutableByteSpan & outBuffer) { - ReturnErrorCodeIf(outBuffer.size() < mFactoryData.pai_cert.len, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!mFactoryData.pai_cert.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(outBuffer.size() >= mFactoryData.pai_cert.len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData.pai_cert.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); memcpy(outBuffer.data(), mFactoryData.pai_cert.data, mFactoryData.pai_cert.len); @@ -234,7 +234,7 @@ CHIP_ERROR FactoryDataProvider::SetSetupDiscriminator(uint16_t template CHIP_ERROR FactoryDataProvider::GetSpake2pIterationCount(uint32_t & iterationCount) { - ReturnErrorCodeIf(mFactoryData.spake2_it == 0, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(mFactoryData.spake2_it != 0, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); iterationCount = mFactoryData.spake2_it; return CHIP_NO_ERROR; } @@ -242,8 +242,8 @@ CHIP_ERROR FactoryDataProvider::GetSpake2pIterationCount(uint3 template CHIP_ERROR FactoryDataProvider::GetSpake2pSalt(MutableByteSpan & saltBuf) { - ReturnErrorCodeIf(saltBuf.size() < mFactoryData.spake2_salt.len, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!mFactoryData.spake2_salt.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(saltBuf.size() >= mFactoryData.spake2_salt.len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData.spake2_salt.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); memcpy(saltBuf.data(), mFactoryData.spake2_salt.data, mFactoryData.spake2_salt.len); @@ -255,8 +255,8 @@ CHIP_ERROR FactoryDataProvider::GetSpake2pSalt(MutableByteSpan template CHIP_ERROR FactoryDataProvider::GetSpake2pVerifier(MutableByteSpan & verifierBuf, size_t & verifierLen) { - ReturnErrorCodeIf(verifierBuf.size() < mFactoryData.spake2_verifier.len, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!mFactoryData.spake2_verifier.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(verifierBuf.size() >= mFactoryData.spake2_verifier.len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData.spake2_verifier.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); memcpy(verifierBuf.data(), mFactoryData.spake2_verifier.data, mFactoryData.spake2_verifier.len); @@ -270,7 +270,7 @@ CHIP_ERROR FactoryDataProvider::GetSpake2pVerifier(MutableByte template CHIP_ERROR FactoryDataProvider::GetSetupPasscode(uint32_t & setupPasscode) { - ReturnErrorCodeIf(mFactoryData.passcode == 0, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(mFactoryData.passcode != 0, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); setupPasscode = mFactoryData.passcode; return CHIP_NO_ERROR; } @@ -360,8 +360,8 @@ CHIP_ERROR FactoryDataProvider::GetHardwareVersionString(char template CHIP_ERROR FactoryDataProvider::GetRotatingDeviceIdUniqueId(MutableByteSpan & uniqueIdSpan) { - ReturnErrorCodeIf(uniqueIdSpan.size() < mFactoryData.rd_uid.len, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!mFactoryData.rd_uid.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(uniqueIdSpan.size() >= mFactoryData.rd_uid.len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData.rd_uid.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); memcpy(uniqueIdSpan.data(), mFactoryData.rd_uid.data, mFactoryData.rd_uid.len); @@ -373,8 +373,8 @@ CHIP_ERROR FactoryDataProvider::GetRotatingDeviceIdUniqueId(Mu template CHIP_ERROR FactoryDataProvider::GetEnableKey(MutableByteSpan & enableKey) { - ReturnErrorCodeIf(!mFactoryData.enable_key.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); - ReturnErrorCodeIf(enableKey.size() < mFactoryData.enable_key.len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData.enable_key.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(enableKey.size() >= mFactoryData.enable_key.len, CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(enableKey.data(), mFactoryData.enable_key.data, mFactoryData.enable_key.len); @@ -386,8 +386,8 @@ CHIP_ERROR FactoryDataProvider::GetEnableKey(MutableByteSpan & template CHIP_ERROR FactoryDataProvider::GetProductFinish(app::Clusters::BasicInformation::ProductFinishEnum * finish) { - ReturnErrorCodeIf(!finish, CHIP_ERROR_INVALID_ARGUMENT); - ReturnErrorCodeIf(!mFactoryData.productFinishPresent, CHIP_ERROR_NOT_IMPLEMENTED); + VerifyOrReturnError(finish, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(mFactoryData.productFinishPresent, CHIP_ERROR_NOT_IMPLEMENTED); *finish = static_cast(mFactoryData.product_finish); return CHIP_NO_ERROR; @@ -396,8 +396,8 @@ CHIP_ERROR FactoryDataProvider::GetProductFinish(app::Clusters template CHIP_ERROR FactoryDataProvider::GetProductPrimaryColor(app::Clusters::BasicInformation::ColorEnum * primaryColor) { - ReturnErrorCodeIf(!primaryColor, CHIP_ERROR_INVALID_ARGUMENT); - ReturnErrorCodeIf(!mFactoryData.primaryColorPresent, CHIP_ERROR_NOT_IMPLEMENTED); + VerifyOrReturnError(primaryColor, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(mFactoryData.primaryColorPresent, CHIP_ERROR_NOT_IMPLEMENTED); *primaryColor = static_cast(mFactoryData.primary_color); @@ -407,8 +407,8 @@ CHIP_ERROR FactoryDataProvider::GetProductPrimaryColor(app::Cl template CHIP_ERROR FactoryDataProvider::GetUserData(MutableByteSpan & userData) { - ReturnErrorCodeIf(!mFactoryData.user.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); - ReturnErrorCodeIf(userData.size() < mFactoryData.user.len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData.user.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(userData.size() >= mFactoryData.user.len, CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(userData.data(), mFactoryData.user.data, mFactoryData.user.len); @@ -420,12 +420,12 @@ CHIP_ERROR FactoryDataProvider::GetUserData(MutableByteSpan & template CHIP_ERROR FactoryDataProvider::GetUserKey(const char * userKey, void * buf, size_t & len) { - ReturnErrorCodeIf(!mFactoryData.user.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); - ReturnErrorCodeIf(!buf, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData.user.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(buf, CHIP_ERROR_BUFFER_TOO_SMALL); bool success = FindUserDataEntry(&mFactoryData, userKey, buf, len, &len); - ReturnErrorCodeIf(!success, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(success, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); return CHIP_NO_ERROR; } diff --git a/src/platform/nrfconnect/OTAImageProcessorImpl.cpp b/src/platform/nrfconnect/OTAImageProcessorImpl.cpp index 357a2aeb8a4f99..f0baf084b0ead3 100644 --- a/src/platform/nrfconnect/OTAImageProcessorImpl.cpp +++ b/src/platform/nrfconnect/OTAImageProcessorImpl.cpp @@ -195,10 +195,10 @@ CHIP_ERROR OTAImageProcessorImpl::ProcessBlock(ByteSpan & aBlock) bool OTAImageProcessorImpl::IsFirstImageRun() { OTARequestorInterface * requestor = GetRequestorInstance(); - ReturnErrorCodeIf(requestor == nullptr, false); + VerifyOrReturnError(requestor != nullptr, false); uint32_t currentVersion; - ReturnErrorCodeIf(ConfigurationMgr().GetSoftwareVersion(currentVersion) != CHIP_NO_ERROR, false); + VerifyOrReturnError(ConfigurationMgr().GetSoftwareVersion(currentVersion) == CHIP_NO_ERROR, false); return requestor->GetCurrentUpdateState() == OTARequestorInterface::OTAUpdateStateEnum::kApplying && requestor->GetTargetVersion() == currentVersion; @@ -218,7 +218,7 @@ CHIP_ERROR OTAImageProcessorImpl::ProcessHeader(ByteSpan & aBlock) CHIP_ERROR error = mHeaderParser.AccumulateAndDecode(aBlock, header); // Needs more data to decode the header - ReturnErrorCodeIf(error == CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR); + VerifyOrReturnError(error != CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR); ReturnErrorOnFailure(error); mParams.totalFileBytes = header.mPayloadSize; diff --git a/src/platform/nxp/common/ConfigurationManagerImpl.cpp b/src/platform/nxp/common/ConfigurationManagerImpl.cpp index 09fb98abac6a3f..70912a4d6ebaa9 100644 --- a/src/platform/nxp/common/ConfigurationManagerImpl.cpp +++ b/src/platform/nxp/common/ConfigurationManagerImpl.cpp @@ -177,8 +177,8 @@ CHIP_ERROR ConfigurationManagerImpl::GetUniqueId(char * buf, size_t bufSize) ReturnErrorOnFailure(err); - ReturnErrorCodeIf(uniqueIdLen >= bufSize, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(buf[uniqueIdLen] != 0, CHIP_ERROR_INVALID_STRING_LENGTH); + VerifyOrReturnError(uniqueIdLen < bufSize, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(buf[uniqueIdLen] == 0, CHIP_ERROR_INVALID_STRING_LENGTH); return err; } diff --git a/src/platform/nxp/common/DnssdImplBr.cpp b/src/platform/nxp/common/DnssdImplBr.cpp index 56ccb6f13ade52..5eab86fe197963 100644 --- a/src/platform/nxp/common/DnssdImplBr.cpp +++ b/src/platform/nxp/common/DnssdImplBr.cpp @@ -224,7 +224,7 @@ CHIP_ERROR NxpChipDnssdRemoveServices() CHIP_ERROR NxpChipDnssdPublishService(const DnssdService * service, DnssdPublishCallback callback, void * context) { - ReturnErrorCodeIf(service == nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(service != nullptr, CHIP_ERROR_INVALID_ARGUMENT); otInstance * thrInstancePtr = ThreadStackMgrImpl().OTInstance(); uint32_t txtBufferOffset = 0; @@ -634,7 +634,7 @@ CHIP_ERROR FromSrpCacheToMdnsData(const otSrpServerService * service, const otSr entryIndex++; } - ReturnErrorCodeIf(alloc.AnyAllocFailed(), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(!alloc.AnyAllocFailed(), CHIP_ERROR_BUFFER_TOO_SMALL); mdnsService.mTextEntries = serviceTxtEntries.mTxtEntries; mdnsService.mTextEntrySize = entryIndex; diff --git a/src/platform/nxp/common/NXPConfigNVS.cpp b/src/platform/nxp/common/NXPConfigNVS.cpp index 4cd997b218d473..1aa1320383b662 100644 --- a/src/platform/nxp/common/NXPConfigNVS.cpp +++ b/src/platform/nxp/common/NXPConfigNVS.cpp @@ -160,11 +160,11 @@ CHIP_ERROR NXPConfig::Init() /* Initialize flash components */ const struct flash_area * fa; - ReturnErrorCodeIf(flash_area_open(SETTINGS_PARTITION, &fa), CHIP_ERROR_PERSISTED_STORAGE_FAILED); - ReturnErrorCodeIf(flash_init(fa->fa_dev), CHIP_ERROR_PERSISTED_STORAGE_FAILED); + VerifyOrReturnError(!flash_area_open(SETTINGS_PARTITION, &fa), CHIP_ERROR_PERSISTED_STORAGE_FAILED); + VerifyOrReturnError(!flash_init(fa->fa_dev), CHIP_ERROR_PERSISTED_STORAGE_FAILED); /* End flash init */ - ReturnErrorCodeIf(settings_subsys_init(), CHIP_ERROR_PERSISTED_STORAGE_FAILED); + VerifyOrReturnError(!settings_subsys_init(), CHIP_ERROR_PERSISTED_STORAGE_FAILED); #if (CHIP_DEVICE_CONFIG_KVS_WEAR_STATS == 1) ReturnErrorOnFailure(InitStorageWearStats()); @@ -183,7 +183,7 @@ CHIP_ERROR NXPConfig::InitStorageWearStats(void) /* Create an empty flash wear profile */ flash_wear_profile = (nvs_storage_wear_profile_t *) calloc(1, flash_wear_profile_size); - ReturnErrorCodeIf(flash_wear_profile == NULL, CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(flash_wear_profile != NULL, CHIP_ERROR_NO_MEMORY); /* Try to read the flash wear profile from the User Support diagnostic log key */ CHIP_ERROR err = ReadConfigValueBin((const char *) keyUser, (uint8_t *) flash_wear_profile, flash_wear_profile_size, size); @@ -213,26 +213,26 @@ CHIP_ERROR NXPConfig::InitStorageWearStats(void) CHIP_ERROR NXPConfig::ReadConfigValue(Key key, bool & val) { - ReturnErrorCodeIf(!ValidConfigKey(key), CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND); // Verify key id. + VerifyOrReturnError(ValidConfigKey(key), CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND); // Verify key id. return ReadSimpleConfigValue(key, val); } CHIP_ERROR NXPConfig::ReadConfigValue(Key key, uint32_t & val) { - ReturnErrorCodeIf(!ValidConfigKey(key), CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND); // Verify key id. + VerifyOrReturnError(ValidConfigKey(key), CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND); // Verify key id. return ReadSimpleConfigValue(key, val); } CHIP_ERROR NXPConfig::ReadConfigValue(Key key, uint64_t & val) { - ReturnErrorCodeIf(!ValidConfigKey(key), CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND); // Verify key id. + VerifyOrReturnError(ValidConfigKey(key), CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND); // Verify key id. return ReadSimpleConfigValue(key, val); } CHIP_ERROR NXPConfig::ReadConfigValueStr(Key key, char * buf, size_t bufSize, size_t & outLen) { CHIP_ERROR err = CHIP_NO_ERROR; - ReturnErrorCodeIf(!ValidConfigKey(key), err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND); // Verify key id. + VerifyOrReturnError(ValidConfigKey(key), err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND); // Verify key id. // Pretend that the buffer is smaller by 1 to secure space for null-character err = ReadConfigValueImpl(key, buf, bufSize ? bufSize - 1 : 0, outLen); @@ -259,7 +259,7 @@ CHIP_ERROR NXPConfig::ReadConfigValueBin(const char * keyString, uint8_t * buf, // to be able to concat CHIP_DEVICE_STRING_SETTINGS_KEY"/" and keyString, + 1 for end char key_name_len = strlen(keyString) + strlen(CHIP_DEVICE_STRING_SETTINGS_KEY) + 1; - ReturnErrorCodeIf(key_name_len > (SETTINGS_MAX_NAME_LEN + 1), CHIP_ERROR_PERSISTED_STORAGE_FAILED); + VerifyOrReturnError(key_name_len <= (SETTINGS_MAX_NAME_LEN + 1), CHIP_ERROR_PERSISTED_STORAGE_FAILED); sprintf(key_name, CHIP_DEVICE_STRING_SETTINGS_KEY "/%s", keyString); settings_load_subtree_direct(key_name, ConfigValueCallback, &request); @@ -295,7 +295,7 @@ CHIP_ERROR NXPConfig::WriteConfigValueStr(Key key, const char * str) CHIP_ERROR NXPConfig::WriteConfigValueStr(Key key, const char * str, size_t strLen) { - ReturnErrorCodeIf(!ValidConfigKey(key), CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND); // Verify key id. + VerifyOrReturnError(ValidConfigKey(key), CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND); // Verify key id. return WriteConfigValueImpl(key, str, strLen); } @@ -311,7 +311,7 @@ CHIP_ERROR NXPConfig::WriteConfigValueBin(const char * keyString, const uint8_t // to be able to concat CHIP_DEVICE_STRING_SETTINGS_KEY"/" and keyString, + 1 for end char key_name_len = strlen(keyString) + strlen(CHIP_DEVICE_STRING_SETTINGS_KEY) + 1; - ReturnErrorCodeIf(key_name_len > (SETTINGS_MAX_NAME_LEN + 1), CHIP_ERROR_PERSISTED_STORAGE_FAILED); + VerifyOrReturnError(key_name_len <= (SETTINGS_MAX_NAME_LEN + 1), CHIP_ERROR_PERSISTED_STORAGE_FAILED); sprintf(key_name, CHIP_DEVICE_STRING_SETTINGS_KEY "/%s", keyString); if (settings_save_one(key_name, data, dataLen) != 0) @@ -340,7 +340,7 @@ CHIP_ERROR NXPConfig::ClearConfigValue(const char * keyString) // to be able to concat CHIP_DEVICE_STRING_SETTINGS_KEY"/" and keyString, + 1 for end char key_name_len = strlen(keyString) + strlen(CHIP_DEVICE_STRING_SETTINGS_KEY) + 1; - ReturnErrorCodeIf(key_name_len > (SETTINGS_MAX_NAME_LEN + 1), CHIP_ERROR_PERSISTED_STORAGE_FAILED); + VerifyOrReturnError(key_name_len <= (SETTINGS_MAX_NAME_LEN + 1), CHIP_ERROR_PERSISTED_STORAGE_FAILED); sprintf(key_name, CHIP_DEVICE_STRING_SETTINGS_KEY "/%s", keyString); if (settings_delete(key_name) != 0) diff --git a/src/platform/nxp/common/OTAImageProcessorImpl.cpp b/src/platform/nxp/common/OTAImageProcessorImpl.cpp index a471b57f512105..1d8dfa02e6a1ce 100644 --- a/src/platform/nxp/common/OTAImageProcessorImpl.cpp +++ b/src/platform/nxp/common/OTAImageProcessorImpl.cpp @@ -229,7 +229,7 @@ CHIP_ERROR OTAImageProcessorImpl::ProcessHeader(ByteSpan & block) CHIP_ERROR error = mHeaderParser.AccumulateAndDecode(block, header); /* Needs more data to decode the header */ - ReturnErrorCodeIf(error == CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR); + VerifyOrReturnError(error != CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR); ReturnErrorOnFailure(error); mParams.totalFileBytes = header.mPayloadSize; diff --git a/src/platform/nxp/common/ble_zephyr/BLEAdvertisingArbiter.cpp b/src/platform/nxp/common/ble_zephyr/BLEAdvertisingArbiter.cpp index e977708fe4862a..ee6b91da3f9c7e 100644 --- a/src/platform/nxp/common/ble_zephyr/BLEAdvertisingArbiter.cpp +++ b/src/platform/nxp/common/ble_zephyr/BLEAdvertisingArbiter.cpp @@ -53,7 +53,7 @@ CHIP_ERROR RestartAdvertising() { // Note: bt_le_adv_stop() returns success when the advertising was not started ReturnErrorOnFailure(MapErrorZephyr(bt_le_adv_stop())); - ReturnErrorCodeIf(sys_slist_is_empty(&sRequests), CHIP_NO_ERROR); + VerifyOrReturnError(!sys_slist_is_empty(&sRequests), CHIP_NO_ERROR); const Request & top = ToRequest(sys_slist_peek_head(&sRequests)); const bt_le_adv_param params = BT_LE_ADV_PARAM_INIT(top.options, top.minInterval, top.maxInterval, nullptr); diff --git a/src/platform/nxp/common/crypto/CHIPCryptoPALTinyCrypt.cpp b/src/platform/nxp/common/crypto/CHIPCryptoPALTinyCrypt.cpp index b0ed35595fa602..9c6334bded2da6 100644 --- a/src/platform/nxp/common/crypto/CHIPCryptoPALTinyCrypt.cpp +++ b/src/platform/nxp/common/crypto/CHIPCryptoPALTinyCrypt.cpp @@ -1965,7 +1965,7 @@ CHIP_ERROR ExtractRawDNFromX509Cert(bool extractSubject, const ByteSpan & certif size_t len = 0; mbedtls_x509_crt mbedCertificate; - ReturnErrorCodeIf(certificate.empty(), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(!certificate.empty(), CHIP_ERROR_INVALID_ARGUMENT); mbedtls_x509_crt_init(&mbedCertificate); result = mbedtls_x509_crt_parse(&mbedCertificate, Uint8::to_const_uchar(certificate.data()), certificate.size()); @@ -2021,7 +2021,7 @@ CHIP_ERROR ReplaceCertIfResignedCertFound(const ByteSpan & referenceCertificate, outCertificate = referenceCertificate; - ReturnErrorCodeIf(candidateCertificates == nullptr || candidateCertificatesCount == 0, CHIP_NO_ERROR); + VerifyOrReturnError(candidateCertificates != nullptr && candidateCertificatesCount != 0, CHIP_NO_ERROR); ReturnErrorOnFailure(ExtractSubjectFromX509Cert(referenceCertificate, referenceSubject)); ReturnErrorOnFailure(ExtractSKIDFromX509Cert(referenceCertificate, referenceSKID)); diff --git a/src/platform/nxp/common/factory_data/FactoryDataProvider.cpp b/src/platform/nxp/common/factory_data/FactoryDataProvider.cpp index b60d7e49c0ad81..43c78a02428a08 100644 --- a/src/platform/nxp/common/factory_data/FactoryDataProvider.cpp +++ b/src/platform/nxp/common/factory_data/FactoryDataProvider.cpp @@ -125,7 +125,7 @@ CHIP_ERROR FactoryDataProvider::GetSpake2pSalt(MutableByteSpan & saltBuf) size_t saltLen = chip::Base64Decode32((char *) saltB64, saltB64Len, reinterpret_cast(saltB64)); - ReturnErrorCodeIf(saltLen > saltBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(saltLen <= saltBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(saltBuf.data(), saltB64, saltLen); saltBuf.reduce_size(saltLen); @@ -142,7 +142,7 @@ CHIP_ERROR FactoryDataProvider::GetSpake2pVerifier(MutableByteSpan & verifierBuf ReturnErrorOnFailure(SearchForId(FactoryDataId::kVerifierId, &verifierB64[0], sizeof(verifierB64), verifierB64Len)); verifierLen = chip::Base64Decode32((char *) verifierB64, verifierB64Len, reinterpret_cast(verifierB64)); - ReturnErrorCodeIf(verifierLen > verifierBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(verifierLen <= verifierBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(verifierBuf.data(), verifierB64, verifierLen); verifierBuf.reduce_size(verifierLen); @@ -288,7 +288,7 @@ CHIP_ERROR FactoryDataProvider::GetRotatingDeviceIdUniqueId(MutableByteSpan & un { constexpr uint8_t uniqueId[] = CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID; - ReturnErrorCodeIf(sizeof(uniqueId) > uniqueIdSpan.size(), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(sizeof(uniqueId) <= uniqueIdSpan.size(), CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(uniqueIdSpan.data(), uniqueId, sizeof(uniqueId)); uniqueIdLen = sizeof(uniqueId); err = CHIP_NO_ERROR; @@ -306,7 +306,7 @@ CHIP_ERROR FactoryDataProvider::GetProductFinish(app::Clusters::BasicInformation uint8_t productFinish; uint16_t length = 0; auto err = SearchForId(FactoryDataId::kProductFinish, &productFinish, sizeof(productFinish), length); - ReturnErrorCodeIf(err != CHIP_NO_ERROR, CHIP_ERROR_NOT_IMPLEMENTED); + VerifyOrReturnError(err == CHIP_NO_ERROR, CHIP_ERROR_NOT_IMPLEMENTED); *finish = static_cast(productFinish); @@ -318,7 +318,7 @@ CHIP_ERROR FactoryDataProvider::GetProductPrimaryColor(app::Clusters::BasicInfor uint8_t color; uint16_t length = 0; auto err = SearchForId(FactoryDataId::kProductPrimaryColor, &color, sizeof(color), length); - ReturnErrorCodeIf(err != CHIP_NO_ERROR, CHIP_ERROR_NOT_IMPLEMENTED); + VerifyOrReturnError(err == CHIP_NO_ERROR, CHIP_ERROR_NOT_IMPLEMENTED); *primaryColor = static_cast(color); diff --git a/src/platform/nxp/common/factory_data/legacy/FactoryDataDriverImpl.cpp b/src/platform/nxp/common/factory_data/legacy/FactoryDataDriverImpl.cpp index 18ea65cdf18e26..cb7f7c110924e6 100644 --- a/src/platform/nxp/common/factory_data/legacy/FactoryDataDriverImpl.cpp +++ b/src/platform/nxp/common/factory_data/legacy/FactoryDataDriverImpl.cpp @@ -70,7 +70,7 @@ CHIP_ERROR FactoryDataDriverImpl::InitRamBackup(void) VerifyOrReturnError(mFactoryDataRamBuff == nullptr, CHIP_ERROR_INTERNAL); mFactoryDataRamBuff = static_cast(chip::Platform::MemoryAlloc(mMaxSize)); - ReturnErrorCodeIf(mFactoryDataRamBuff == nullptr, CHIP_ERROR_INTERNAL); + VerifyOrReturnError(mFactoryDataRamBuff != nullptr, CHIP_ERROR_INTERNAL); memset(mFactoryDataRamBuff, 0, mMaxSize); memcpy(mFactoryDataRamBuff, (void *) &mFactoryData->app_factory_data[0], mSize); @@ -97,7 +97,7 @@ CHIP_ERROR FactoryDataDriverImpl::ReadBackupInRam() if (mFactoryDataRamBuff == nullptr) { mFactoryDataRamBuff = static_cast(chip::Platform::MemoryAlloc(mMaxSize)); - ReturnErrorCodeIf(mFactoryDataRamBuff == nullptr, CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(mFactoryDataRamBuff != nullptr, CHIP_ERROR_NO_MEMORY); memset(mFactoryDataRamBuff, 0, mMaxSize); } @@ -111,7 +111,7 @@ CHIP_ERROR FactoryDataDriverImpl::ReadBackupInRam() CHIP_ERROR FactoryDataDriverImpl::BackupFactoryData() { CHIP_ERROR error = CHIP_NO_ERROR; - ReturnErrorCodeIf(mFactoryData == nullptr, CHIP_ERROR_INTERNAL); + VerifyOrReturnError(mFactoryData != nullptr, CHIP_ERROR_INTERNAL); error = KeyValueStoreMgr().Put(FactoryDataDriverImpl::GetFactoryBackupKey().KeyName(), &mFactoryData->app_factory_data[0], mMaxSize); diff --git a/src/platform/nxp/common/factory_data/legacy/FactoryDataProvider.cpp b/src/platform/nxp/common/factory_data/legacy/FactoryDataProvider.cpp index 38998ed3c5bde6..d7cac2e8f12835 100644 --- a/src/platform/nxp/common/factory_data/legacy/FactoryDataProvider.cpp +++ b/src/platform/nxp/common/factory_data/legacy/FactoryDataProvider.cpp @@ -129,10 +129,10 @@ CHIP_ERROR FactoryDataProvider::Validate() uint8_t output[Crypto::kSHA256_Hash_Length] = { 0 }; memcpy(&mHeader, (void *) mConfig.start, sizeof(Header)); - ReturnErrorCodeIf(mHeader.hashId != kHashId, CHIP_FACTORY_DATA_HASH_ID); + VerifyOrReturnError(mHeader.hashId == kHashId, CHIP_FACTORY_DATA_HASH_ID); ReturnErrorOnFailure(Crypto::Hash_SHA256((uint8_t *) mConfig.payload, mHeader.size, output)); - ReturnErrorCodeIf(memcmp(output, mHeader.hash, kHashLen) != 0, CHIP_FACTORY_DATA_SHA_CHECK); + VerifyOrReturnError(memcmp(output, mHeader.hash, kHashLen) == 0, CHIP_FACTORY_DATA_SHA_CHECK); return CHIP_NO_ERROR; } @@ -150,7 +150,7 @@ CHIP_ERROR FactoryDataProvider::SearchForId(uint8_t searchedType, uint8_t * pBuf if (searchedType == type) { - ReturnErrorCodeIf(bufLength < length, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(bufLength >= length, CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(pBuf, (void *) (addr + kValueOffset), length); if (offset) @@ -241,7 +241,7 @@ CHIP_ERROR FactoryDataProvider::GetSpake2pSalt(MutableByteSpan & saltBuf) ReturnErrorOnFailure(SearchForId(FactoryDataId::kSaltId, (uint8_t *) (&saltB64[0]), sizeof(saltB64), saltB64Len)); size_t saltLen = chip::Base64Decode32(saltB64, saltB64Len, reinterpret_cast(saltB64)); - ReturnErrorCodeIf(saltLen > saltBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(saltLen <= saltBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(saltBuf.data(), saltB64, saltLen); saltBuf.reduce_size(saltLen); @@ -255,7 +255,7 @@ CHIP_ERROR FactoryDataProvider::GetSpake2pVerifier(MutableByteSpan & verifierBuf ReturnErrorOnFailure(SearchForId(FactoryDataId::kVerifierId, (uint8_t *) &verifierB64[0], sizeof(verifierB64), verifierB64Len)); verifierLen = chip::Base64Decode32(verifierB64, verifierB64Len, reinterpret_cast(verifierB64)); - ReturnErrorCodeIf(verifierLen > verifierBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(verifierLen <= verifierBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(verifierBuf.data(), verifierB64, verifierLen); verifierBuf.reduce_size(verifierLen); @@ -401,7 +401,7 @@ CHIP_ERROR FactoryDataProvider::GetRotatingDeviceIdUniqueId(MutableByteSpan & un { constexpr uint8_t uniqueId[] = CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID; - ReturnErrorCodeIf(sizeof(uniqueId) > uniqueIdSpan.size(), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(sizeof(uniqueId) <= uniqueIdSpan.size(), CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(uniqueIdSpan.data(), uniqueId, sizeof(uniqueId)); uniqueIdLen = sizeof(uniqueId); err = CHIP_NO_ERROR; @@ -419,7 +419,7 @@ CHIP_ERROR FactoryDataProvider::GetProductFinish(app::Clusters::BasicInformation uint8_t productFinish; uint16_t length = 0; auto err = SearchForId(FactoryDataId::kProductFinish, &productFinish, sizeof(productFinish), length); - ReturnErrorCodeIf(err != CHIP_NO_ERROR, CHIP_ERROR_NOT_IMPLEMENTED); + VerifyOrReturnError(err == CHIP_NO_ERROR, CHIP_ERROR_NOT_IMPLEMENTED); *finish = static_cast(productFinish); @@ -431,7 +431,7 @@ CHIP_ERROR FactoryDataProvider::GetProductPrimaryColor(app::Clusters::BasicInfor uint8_t color; uint16_t length = 0; auto err = SearchForId(FactoryDataId::kProductPrimaryColor, &color, sizeof(color), length); - ReturnErrorCodeIf(err != CHIP_NO_ERROR, CHIP_ERROR_NOT_IMPLEMENTED); + VerifyOrReturnError(err == CHIP_NO_ERROR, CHIP_ERROR_NOT_IMPLEMENTED); *primaryColor = static_cast(color); diff --git a/src/platform/nxp/common/factory_data/legacy/FactoryDataProviderImpl.cpp b/src/platform/nxp/common/factory_data/legacy/FactoryDataProviderImpl.cpp index abb189685bdc7f..1ee2340602a6cc 100644 --- a/src/platform/nxp/common/factory_data/legacy/FactoryDataProviderImpl.cpp +++ b/src/platform/nxp/common/factory_data/legacy/FactoryDataProviderImpl.cpp @@ -273,7 +273,7 @@ extern "C" WEAK CHIP_ERROR FactoryDataDefaultRestoreMechanism() CHIP_ERROR error = CHIP_NO_ERROR; FactoryDataDriver * driver = &FactoryDataDrv(); - ReturnErrorCodeIf(driver == nullptr, CHIP_ERROR_INTERNAL); + VerifyOrReturnError(driver != nullptr, CHIP_ERROR_INTERNAL); // Check if key related to factory data backup exists. // If it does, it means an external event (such as a power loss) diff --git a/src/platform/nxp/common/ota/OTAFirmwareProcessor.cpp b/src/platform/nxp/common/ota/OTAFirmwareProcessor.cpp index 15aa5f271c3ccc..a9015d8e1822d8 100644 --- a/src/platform/nxp/common/ota/OTAFirmwareProcessor.cpp +++ b/src/platform/nxp/common/ota/OTAFirmwareProcessor.cpp @@ -26,16 +26,16 @@ namespace chip { CHIP_ERROR OTAFirmwareProcessor::Init() { - ReturnErrorCodeIf(mCallbackProcessDescriptor == nullptr, CHIP_ERROR_OTA_PROCESSOR_CB_NOT_REGISTERED); + VerifyOrReturnError(mCallbackProcessDescriptor != nullptr, CHIP_ERROR_OTA_PROCESSOR_CB_NOT_REGISTERED); mAccumulator.Init(sizeof(Descriptor)); - ReturnErrorCodeIf(gOtaSuccess_c != OTA_SelectExternalStoragePartition(), CHIP_ERROR_OTA_PROCESSOR_EXTERNAL_STORAGE); + VerifyOrReturnError(gOtaSuccess_c == OTA_SelectExternalStoragePartition(), CHIP_ERROR_OTA_PROCESSOR_EXTERNAL_STORAGE); otaResult_t ota_status; ota_status = OTA_ServiceInit(&mPostedOperationsStorage[0], NB_PENDING_TRANSACTIONS * TRANSACTION_SZ); - ReturnErrorCodeIf(ota_status != gOtaSuccess_c, CHIP_ERROR_OTA_PROCESSOR_CLIENT_INIT); - ReturnErrorCodeIf(gOtaSuccess_c != OTA_StartImage(mLength - sizeof(Descriptor)), CHIP_ERROR_OTA_PROCESSOR_START_IMAGE); + VerifyOrReturnError(ota_status == gOtaSuccess_c, CHIP_ERROR_OTA_PROCESSOR_CLIENT_INIT); + VerifyOrReturnError(gOtaSuccess_c == OTA_StartImage(mLength - sizeof(Descriptor)), CHIP_ERROR_OTA_PROCESSOR_START_IMAGE); return CHIP_NO_ERROR; } diff --git a/src/platform/nxp/common/ota/OTAImageProcessorImpl.cpp b/src/platform/nxp/common/ota/OTAImageProcessorImpl.cpp index f6f42367329e54..59af9449b9af76 100644 --- a/src/platform/nxp/common/ota/OTAImageProcessorImpl.cpp +++ b/src/platform/nxp/common/ota/OTAImageProcessorImpl.cpp @@ -39,7 +39,7 @@ namespace chip { CHIP_ERROR OTAImageProcessorImpl::Init(OTADownloader * downloader) { - ReturnErrorCodeIf(downloader == nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(downloader != nullptr, CHIP_ERROR_INVALID_ARGUMENT); mDownloader = downloader; OtaHookInit(); @@ -297,7 +297,7 @@ CHIP_ERROR OTAImageProcessorImpl::ConfirmCurrentImage() uint32_t targetVersion; OTARequestorInterface * requestor = chip::GetRequestorInstance(); - ReturnErrorCodeIf(requestor == nullptr, CHIP_ERROR_INTERNAL); + VerifyOrReturnError(requestor != nullptr, CHIP_ERROR_INTERNAL); targetVersion = requestor->GetTargetVersion(); ReturnErrorOnFailure(DeviceLayer::ConfigurationMgr().GetSoftwareVersion(currentVersion)); diff --git a/src/platform/nxp/k32w0/ConfigurationManagerImpl.cpp b/src/platform/nxp/k32w0/ConfigurationManagerImpl.cpp index 7343c75b5d5865..4e24fa71996290 100644 --- a/src/platform/nxp/k32w0/ConfigurationManagerImpl.cpp +++ b/src/platform/nxp/k32w0/ConfigurationManagerImpl.cpp @@ -121,8 +121,8 @@ CHIP_ERROR ConfigurationManagerImpl::GetUniqueId(char * buf, size_t bufSize) ReturnErrorOnFailure(err); - ReturnErrorCodeIf(uniqueIdLen >= bufSize, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(buf[uniqueIdLen] != 0, CHIP_ERROR_INVALID_STRING_LENGTH); + VerifyOrReturnError(uniqueIdLen < bufSize, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(buf[uniqueIdLen] == 0, CHIP_ERROR_INVALID_STRING_LENGTH); return err; } diff --git a/src/platform/nxp/k32w0/FactoryDataProvider.cpp b/src/platform/nxp/k32w0/FactoryDataProvider.cpp index 23f8ffe7c0586b..28d8c9f3889b76 100644 --- a/src/platform/nxp/k32w0/FactoryDataProvider.cpp +++ b/src/platform/nxp/k32w0/FactoryDataProvider.cpp @@ -55,10 +55,10 @@ CHIP_ERROR FactoryDataProvider::Validate() uint8_t output[Crypto::kSHA256_Hash_Length] = { 0 }; memcpy(&mHeader, (void *) kFactoryDataStart, sizeof(Header)); - ReturnErrorCodeIf(mHeader.hashId != kHashId, CHIP_FACTORY_DATA_HASH_ID); + VerifyOrReturnError(mHeader.hashId == kHashId, CHIP_FACTORY_DATA_HASH_ID); ReturnErrorOnFailure(Crypto::Hash_SHA256((uint8_t *) kFactoryDataPayloadStart, mHeader.size, output)); - ReturnErrorCodeIf(memcmp(output, mHeader.hash, kHashLen) != 0, CHIP_FACTORY_DATA_SHA_CHECK); + VerifyOrReturnError(memcmp(output, mHeader.hash, kHashLen) == 0, CHIP_FACTORY_DATA_SHA_CHECK); return CHIP_NO_ERROR; } @@ -76,7 +76,7 @@ CHIP_ERROR FactoryDataProvider::SearchForId(uint8_t searchedType, uint8_t * pBuf if (searchedType == type) { - ReturnErrorCodeIf(bufLength < length, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(bufLength >= length, CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(pBuf, (void *) (addr + kValueOffset), length); if (offset) @@ -167,7 +167,7 @@ CHIP_ERROR FactoryDataProvider::GetSpake2pSalt(MutableByteSpan & saltBuf) ReturnErrorOnFailure(SearchForId(FactoryDataId::kSaltId, (uint8_t *) (&saltB64[0]), sizeof(saltB64), saltB64Len)); size_t saltLen = chip::Base64Decode32(saltB64, saltB64Len, reinterpret_cast(saltB64)); - ReturnErrorCodeIf(saltLen > saltBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(saltLen <= saltBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(saltBuf.data(), saltB64, saltLen); saltBuf.reduce_size(saltLen); @@ -181,7 +181,7 @@ CHIP_ERROR FactoryDataProvider::GetSpake2pVerifier(MutableByteSpan & verifierBuf ReturnErrorOnFailure(SearchForId(FactoryDataId::kVerifierId, (uint8_t *) &verifierB64[0], sizeof(verifierB64), verifierB64Len)); verifierLen = chip::Base64Decode32(verifierB64, verifierB64Len, reinterpret_cast(verifierB64)); - ReturnErrorCodeIf(verifierLen > verifierBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(verifierLen <= verifierBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(verifierBuf.data(), verifierB64, verifierLen); verifierBuf.reduce_size(verifierLen); @@ -327,7 +327,7 @@ CHIP_ERROR FactoryDataProvider::GetRotatingDeviceIdUniqueId(MutableByteSpan & un { constexpr uint8_t uniqueId[] = CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID; - ReturnErrorCodeIf(sizeof(uniqueId) > uniqueIdSpan.size(), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(sizeof(uniqueId) <= uniqueIdSpan.size(), CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(uniqueIdSpan.data(), uniqueId, sizeof(uniqueId)); uniqueIdLen = sizeof(uniqueId); err = CHIP_NO_ERROR; @@ -345,7 +345,7 @@ CHIP_ERROR FactoryDataProvider::GetProductFinish(app::Clusters::BasicInformation uint8_t productFinish; uint16_t length = 0; auto err = SearchForId(FactoryDataId::kProductFinish, &productFinish, sizeof(productFinish), length); - ReturnErrorCodeIf(err != CHIP_NO_ERROR, CHIP_ERROR_NOT_IMPLEMENTED); + VerifyOrReturnError(err == CHIP_NO_ERROR, CHIP_ERROR_NOT_IMPLEMENTED); *finish = static_cast(productFinish); @@ -357,7 +357,7 @@ CHIP_ERROR FactoryDataProvider::GetProductPrimaryColor(app::Clusters::BasicInfor uint8_t color; uint16_t length = 0; auto err = SearchForId(FactoryDataId::kProductPrimaryColor, &color, sizeof(color), length); - ReturnErrorCodeIf(err != CHIP_NO_ERROR, CHIP_ERROR_NOT_IMPLEMENTED); + VerifyOrReturnError(err == CHIP_NO_ERROR, CHIP_ERROR_NOT_IMPLEMENTED); *primaryColor = static_cast(color); diff --git a/src/platform/nxp/k32w0/FactoryDataProviderImpl.cpp b/src/platform/nxp/k32w0/FactoryDataProviderImpl.cpp index 93c09adf5c749d..e2d5f1db8b9606 100644 --- a/src/platform/nxp/k32w0/FactoryDataProviderImpl.cpp +++ b/src/platform/nxp/k32w0/FactoryDataProviderImpl.cpp @@ -105,11 +105,11 @@ extern "C" WEAK CHIP_ERROR FactoryDataDefaultRestoreMechanism() { chip::Platform::ScopedMemoryBuffer buffer; buffer.Calloc(FactoryDataProvider::kFactoryDataSize); - ReturnErrorCodeIf(buffer.Get() == nullptr, CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(buffer.Get() != nullptr, CHIP_ERROR_NO_MEMORY); auto status = PDM_eReadDataFromRecord(kNvmId_FactoryDataBackup, (void *) buffer.Get(), FactoryDataProvider::kFactoryDataSize, &backupLength); - ReturnErrorCodeIf(PDM_E_STATUS_OK != status, CHIP_FACTORY_DATA_PDM_RESTORE); + VerifyOrReturnError(PDM_E_STATUS_OK == status, CHIP_FACTORY_DATA_PDM_RESTORE); error = FactoryDataProviderImpl::UpdateData(buffer.Get()); if (error == CHIP_NO_ERROR) @@ -157,11 +157,11 @@ CHIP_ERROR FactoryDataProviderImpl::UpdateData(uint8_t * pBuf) NV_Init(); auto status = NV_FlashEraseSector(kFactoryDataStart, kFactoryDataSize); - ReturnErrorCodeIf(status != kStatus_FLASH_Success, CHIP_FACTORY_DATA_FLASH_ERASE); + VerifyOrReturnError(status == kStatus_FLASH_Success, CHIP_FACTORY_DATA_FLASH_ERASE); Header * header = (Header *) pBuf; status = NV_FlashProgramUnaligned(kFactoryDataStart, sizeof(Header) + header->size, pBuf); - ReturnErrorCodeIf(status != kStatus_FLASH_Success, CHIP_FACTORY_DATA_FLASH_PROGRAM); + VerifyOrReturnError(status == kStatus_FLASH_Success, CHIP_FACTORY_DATA_FLASH_PROGRAM); return CHIP_NO_ERROR; } diff --git a/src/platform/nxp/k32w0/KeyValueStoreManagerImpl.cpp b/src/platform/nxp/k32w0/KeyValueStoreManagerImpl.cpp index 50f900583769f7..34666e491ab43e 100644 --- a/src/platform/nxp/k32w0/KeyValueStoreManagerImpl.cpp +++ b/src/platform/nxp/k32w0/KeyValueStoreManagerImpl.cpp @@ -326,7 +326,7 @@ static CHIP_ERROR MoveKeysAndValues() Platform::ScopedMemoryBuffer buffer; buffer.Calloc(len); - ReturnErrorCodeIf(buffer.Get() == nullptr, CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(buffer.Get() != nullptr, CHIP_ERROR_NO_MEMORY); for (uint8_t id = 0; id < kMaxNumberOfKeys; id++) { diff --git a/src/platform/nxp/k32w0/OTAFactoryDataProcessor.cpp b/src/platform/nxp/k32w0/OTAFactoryDataProcessor.cpp index 9114906787a7b6..b3ffdd156313e4 100644 --- a/src/platform/nxp/k32w0/OTAFactoryDataProcessor.cpp +++ b/src/platform/nxp/k32w0/OTAFactoryDataProcessor.cpp @@ -174,7 +174,7 @@ CHIP_ERROR OTAFactoryDataProcessor::Read() memcpy(&header, (void *) FactoryProvider::kFactoryDataStart, sizeof(FactoryProvider::Header)); mFactoryData = static_cast(chip::Platform::MemoryAlloc(FactoryProvider::kFactoryDataSize)); - ReturnErrorCodeIf(mFactoryData == nullptr, CHIP_FACTORY_DATA_NULL); + VerifyOrReturnError(mFactoryData != nullptr, CHIP_FACTORY_DATA_NULL); memset(mFactoryData, 0, FactoryProvider::kFactoryDataSize); memcpy(mFactoryData, (void *) FactoryProvider::kFactoryDataStart, sizeof(FactoryProvider::Header) + header.size); @@ -183,10 +183,10 @@ CHIP_ERROR OTAFactoryDataProcessor::Read() CHIP_ERROR OTAFactoryDataProcessor::Backup() { - ReturnErrorCodeIf(mFactoryData == nullptr, CHIP_FACTORY_DATA_NULL); + VerifyOrReturnError(mFactoryData != nullptr, CHIP_FACTORY_DATA_NULL); auto status = PDM_eSaveRecordData(kNvmId_FactoryDataBackup, (void *) mFactoryData, FactoryProvider::kFactoryDataSize); - ReturnErrorCodeIf(status != PDM_E_STATUS_OK, CHIP_FACTORY_DATA_PDM_SAVE_RECORD); + VerifyOrReturnError(status == PDM_E_STATUS_OK, CHIP_FACTORY_DATA_PDM_SAVE_RECORD); // PDM save will do an encryption in place, so a restore is neeeded in order // to have the decrypted data back in the mFactoryData buffer. ReturnErrorOnFailure(Restore()); @@ -196,13 +196,13 @@ CHIP_ERROR OTAFactoryDataProcessor::Backup() CHIP_ERROR OTAFactoryDataProcessor::Restore() { - ReturnErrorCodeIf(mFactoryData == nullptr, CHIP_FACTORY_DATA_NULL); + VerifyOrReturnError(mFactoryData != nullptr, CHIP_FACTORY_DATA_NULL); uint16_t bytesRead = 0; auto status = PDM_eReadDataFromRecord(kNvmId_FactoryDataBackup, (void *) mFactoryData, FactoryProvider::kFactoryDataSize, &bytesRead); - ReturnErrorCodeIf(status != PDM_E_STATUS_OK, CHIP_FACTORY_DATA_PDM_READ_RECORD); + VerifyOrReturnError(status == PDM_E_STATUS_OK, CHIP_FACTORY_DATA_PDM_READ_RECORD); return CHIP_NO_ERROR; } diff --git a/src/platform/nxp/k32w0/OTAFirmwareProcessor.cpp b/src/platform/nxp/k32w0/OTAFirmwareProcessor.cpp index 3fcb2fd43bf1d9..1ea200313178b6 100644 --- a/src/platform/nxp/k32w0/OTAFirmwareProcessor.cpp +++ b/src/platform/nxp/k32w0/OTAFirmwareProcessor.cpp @@ -28,12 +28,12 @@ namespace chip { CHIP_ERROR OTAFirmwareProcessor::Init() { - ReturnErrorCodeIf(mCallbackProcessDescriptor == nullptr, CHIP_ERROR_OTA_PROCESSOR_CB_NOT_REGISTERED); + VerifyOrReturnError(mCallbackProcessDescriptor != nullptr, CHIP_ERROR_OTA_PROCESSOR_CB_NOT_REGISTERED); mAccumulator.Init(sizeof(Descriptor)); #if OTA_ENCRYPTION_ENABLE mUnalignmentNum = 0; #endif - ReturnErrorCodeIf(gOtaSuccess_c != OTA_ClientInit(), CHIP_ERROR_OTA_PROCESSOR_CLIENT_INIT); + VerifyOrReturnError(gOtaSuccess_c == OTA_ClientInit(), CHIP_ERROR_OTA_PROCESSOR_CLIENT_INIT); auto offset = OTA_GetCurrentEepromAddressOffset(); if (offset != 0) @@ -41,8 +41,8 @@ CHIP_ERROR OTAFirmwareProcessor::Init() offset += 1; } - ReturnErrorCodeIf(OTA_UTILS_IMAGE_INVALID_ADDR == OTA_SetStartEepromOffset(offset), CHIP_ERROR_OTA_PROCESSOR_EEPROM_OFFSET); - ReturnErrorCodeIf(gOtaSuccess_c != OTA_StartImage(mLength - sizeof(Descriptor)), CHIP_ERROR_OTA_PROCESSOR_START_IMAGE); + VerifyOrReturnError(OTA_UTILS_IMAGE_INVALID_ADDR != OTA_SetStartEepromOffset(offset), CHIP_ERROR_OTA_PROCESSOR_EEPROM_OFFSET); + VerifyOrReturnError(gOtaSuccess_c == OTA_StartImage(mLength - sizeof(Descriptor)), CHIP_ERROR_OTA_PROCESSOR_START_IMAGE); return CHIP_NO_ERROR; } diff --git a/src/platform/nxp/mw320/FactoryDataProvider.cpp b/src/platform/nxp/mw320/FactoryDataProvider.cpp index 5b36958f306d5b..5d02bcf9e48ee0 100644 --- a/src/platform/nxp/mw320/FactoryDataProvider.cpp +++ b/src/platform/nxp/mw320/FactoryDataProvider.cpp @@ -234,7 +234,7 @@ CHIP_ERROR FactoryDataProvider::GetSpake2pSalt(MutableByteSpan & saltBuf) ReturnErrorOnFailure(SearchForId(kSaltId, (uint8_t *) (&saltB64[0]), sizeof(saltB64), saltB64Len)); size_t saltLen = chip::Base64Decode32(saltB64, saltB64Len, reinterpret_cast(saltB64)); - ReturnErrorCodeIf(saltLen > saltBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(saltLen <= saltBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(saltBuf.data(), saltB64, saltLen); saltBuf.reduce_size(saltLen); @@ -249,7 +249,7 @@ CHIP_ERROR FactoryDataProvider::GetSpake2pVerifier(MutableByteSpan & verifierBuf ReturnErrorOnFailure(SearchForId(kVerifierId, (uint8_t *) &verifierB64[0], sizeof(verifierB64), verifierB64Len)); verifierLen = chip::Base64Decode32(verifierB64, verifierB64Len, reinterpret_cast(verifierB64)); - ReturnErrorCodeIf(verifierLen > verifierBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(verifierLen <= verifierBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(verifierBuf.data(), verifierB64, verifierLen); verifierBuf.reduce_size(verifierLen); diff --git a/src/platform/nxp/mw320/OTAImageProcessorImpl.cpp b/src/platform/nxp/mw320/OTAImageProcessorImpl.cpp index 1fac68beb2e360..18dc019ba33bc0 100644 --- a/src/platform/nxp/mw320/OTAImageProcessorImpl.cpp +++ b/src/platform/nxp/mw320/OTAImageProcessorImpl.cpp @@ -280,7 +280,7 @@ CHIP_ERROR OTAImageProcessorImpl::ProcessHeader(ByteSpan & block) CHIP_ERROR error = mHeaderParser.AccumulateAndDecode(block, header); // Needs more data to decode the header - ReturnErrorCodeIf(error == CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR); + VerifyOrReturnError(error != CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR); ReturnErrorOnFailure(error); // mParams.totalFileBytes = header.mPayloadSize; diff --git a/src/platform/nxp/zephyr/DeviceInstanceInfoProviderImpl.cpp b/src/platform/nxp/zephyr/DeviceInstanceInfoProviderImpl.cpp index 92029ebd617386..52d0fc65ad19f8 100644 --- a/src/platform/nxp/zephyr/DeviceInstanceInfoProviderImpl.cpp +++ b/src/platform/nxp/zephyr/DeviceInstanceInfoProviderImpl.cpp @@ -28,13 +28,13 @@ CHIP_ERROR DeviceInstanceInfoProviderImpl::GetRotatingDeviceIdUniqueId(MutableBy static_assert(ConfigurationManager::kRotatingDeviceIDUniqueIDLength >= ConfigurationManager::kMinRotatingDeviceIDUniqueIDLength, "Length of unique ID for rotating device ID is smaller than minimum."); - ReturnErrorCodeIf(ConfigurationManager::kRotatingDeviceIDUniqueIDLength > uniqueIdSpan.size(), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(ConfigurationManager::kRotatingDeviceIDUniqueIDLength <= uniqueIdSpan.size(), CHIP_ERROR_BUFFER_TOO_SMALL); size_t bytesLen = chip::Encoding::HexToBytes(CONFIG_CHIP_DEVICE_ROTATING_DEVICE_UID, ConfigurationManager::kRotatingDeviceIDUniqueIDLength * 2, uniqueIdSpan.data(), uniqueIdSpan.size()); - ReturnErrorCodeIf(bytesLen != ConfigurationManager::kRotatingDeviceIDUniqueIDLength, CHIP_ERROR_INVALID_STRING_LENGTH); + VerifyOrReturnError(bytesLen == ConfigurationManager::kRotatingDeviceIDUniqueIDLength, CHIP_ERROR_INVALID_STRING_LENGTH); uniqueIdSpan.reduce_size(bytesLen); return CHIP_NO_ERROR; diff --git a/src/platform/nxp/zephyr/DiagnosticDataProviderImplNxp.cpp b/src/platform/nxp/zephyr/DiagnosticDataProviderImplNxp.cpp index 6c3481da234719..9c7b3c789a72c0 100644 --- a/src/platform/nxp/zephyr/DiagnosticDataProviderImplNxp.cpp +++ b/src/platform/nxp/zephyr/DiagnosticDataProviderImplNxp.cpp @@ -46,7 +46,7 @@ CHIP_ERROR DiagnosticDataProviderImplNxp::GetWiFiBssId(MutableByteSpan & value) { WiFiManager::WiFiInfo info; ReturnErrorOnFailure(WiFiManager::Instance().GetWiFiInfo(info)); - ReturnErrorCodeIf(sizeof(info.mBssId) >= value.size(), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(sizeof(info.mBssId) < value.size(), CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(value.data(), info.mBssId, sizeof(info.mBssId)); value.reduce_size(sizeof(info.mBssId)); diff --git a/src/platform/nxp/zephyr/ota/OTAImageProcessorImpl.cpp b/src/platform/nxp/zephyr/ota/OTAImageProcessorImpl.cpp index 89907c0fff3bdd..d86e662ccc05c8 100644 --- a/src/platform/nxp/zephyr/ota/OTAImageProcessorImpl.cpp +++ b/src/platform/nxp/zephyr/ota/OTAImageProcessorImpl.cpp @@ -151,10 +151,10 @@ CHIP_ERROR OTAImageProcessorImpl::ProcessBlock(ByteSpan & aBlock) bool OTAImageProcessorImpl::IsFirstImageRun() { OTARequestorInterface * requestor = GetRequestorInstance(); - ReturnErrorCodeIf(requestor == nullptr, false); + VerifyOrReturnError(requestor != nullptr, false); uint32_t currentVersion; - ReturnErrorCodeIf(ConfigurationMgr().GetSoftwareVersion(currentVersion) != CHIP_NO_ERROR, false); + VerifyOrReturnError(ConfigurationMgr().GetSoftwareVersion(currentVersion) == CHIP_NO_ERROR, false); return requestor->GetCurrentUpdateState() == OTARequestorInterface::OTAUpdateStateEnum::kApplying && requestor->GetTargetVersion() == currentVersion; @@ -173,7 +173,7 @@ CHIP_ERROR OTAImageProcessorImpl::ProcessHeader(ByteSpan & aBlock) CHIP_ERROR error = mHeaderParser.AccumulateAndDecode(aBlock, header); // Needs more data to decode the header - ReturnErrorCodeIf(error == CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR); + VerifyOrReturnError(error != CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR); ReturnErrorOnFailure(error); mParams.totalFileBytes = header.mPayloadSize; diff --git a/src/platform/openiotsdk/OTAImageProcessorImpl.cpp b/src/platform/openiotsdk/OTAImageProcessorImpl.cpp index 81b3973ff2c0a6..a92a9b1020885a 100644 --- a/src/platform/openiotsdk/OTAImageProcessorImpl.cpp +++ b/src/platform/openiotsdk/OTAImageProcessorImpl.cpp @@ -255,7 +255,7 @@ CHIP_ERROR OTAImageProcessorImpl::ProcessHeader(ByteSpan & block) CHIP_ERROR error = mHeaderParser.AccumulateAndDecode(block, header); // Needs more data to decode the header - ReturnErrorCodeIf(error == CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR); + VerifyOrReturnError(error != CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR); ReturnErrorOnFailure(error); mParams.totalFileBytes = header.mPayloadSize; diff --git a/src/platform/qpg/OTAImageProcessorImpl.cpp b/src/platform/qpg/OTAImageProcessorImpl.cpp index 6293f310bf28d9..e0e2cf4a8029f5 100644 --- a/src/platform/qpg/OTAImageProcessorImpl.cpp +++ b/src/platform/qpg/OTAImageProcessorImpl.cpp @@ -77,7 +77,7 @@ CHIP_ERROR OTAImageProcessorImpl::ProcessHeader(ByteSpan & block) CHIP_ERROR error = mHeaderParser.AccumulateAndDecode(block, header); // Needs more data to decode the header - ReturnErrorCodeIf(error == CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR); + VerifyOrReturnError(error != CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR); ReturnErrorOnFailure(error); mParams.totalFileBytes = header.mPayloadSize; diff --git a/src/platform/silabs/SiWx917/CHIPCryptoPALTinyCrypt.cpp b/src/platform/silabs/SiWx917/CHIPCryptoPALTinyCrypt.cpp index 52f2cb74b9fe86..05fa10c5832ac2 100644 --- a/src/platform/silabs/SiWx917/CHIPCryptoPALTinyCrypt.cpp +++ b/src/platform/silabs/SiWx917/CHIPCryptoPALTinyCrypt.cpp @@ -1983,7 +1983,7 @@ CHIP_ERROR ExtractRawDNFromX509Cert(bool extractSubject, const ByteSpan & certif size_t len = 0; mbedtls_x509_crt mbedCertificate; - ReturnErrorCodeIf(certificate.empty(), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(!certificate.empty(), CHIP_ERROR_INVALID_ARGUMENT); mbedtls_x509_crt_init(&mbedCertificate); result = mbedtls_x509_crt_parse(&mbedCertificate, Uint8::to_const_uchar(certificate.data()), certificate.size()); @@ -2039,7 +2039,7 @@ CHIP_ERROR ReplaceCertIfResignedCertFound(const ByteSpan & referenceCertificate, outCertificate = referenceCertificate; - ReturnErrorCodeIf(candidateCertificates == nullptr || candidateCertificatesCount == 0, CHIP_NO_ERROR); + VerifyOrReturnError(candidateCertificates != nullptr && candidateCertificatesCount != 0, CHIP_NO_ERROR); ReturnErrorOnFailure(ExtractSubjectFromX509Cert(referenceCertificate, referenceSubject)); ReturnErrorOnFailure(ExtractSKIDFromX509Cert(referenceCertificate, referenceSKID)); diff --git a/src/platform/silabs/SiWx917/OTAImageProcessorImpl.cpp b/src/platform/silabs/SiWx917/OTAImageProcessorImpl.cpp index d641bfa61f9888..bccb704ad18cab 100644 --- a/src/platform/silabs/SiWx917/OTAImageProcessorImpl.cpp +++ b/src/platform/silabs/SiWx917/OTAImageProcessorImpl.cpp @@ -51,7 +51,7 @@ uint8_t OTAImageProcessorImpl::writeBuffer[kAlignmentBytes] __attribute__((align CHIP_ERROR OTAImageProcessorImpl::Init(OTADownloader * downloader) { - ReturnErrorCodeIf(downloader == nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(downloader != nullptr, CHIP_ERROR_INVALID_ARGUMENT); gImageProcessor.SetOTADownloader(downloader); @@ -342,7 +342,7 @@ CHIP_ERROR OTAImageProcessorImpl::ProcessHeader(ByteSpan & block) CHIP_ERROR error = mHeaderParser.AccumulateAndDecode(block, header); // Needs more data to decode the header - ReturnErrorCodeIf(error == CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR); + VerifyOrReturnError(error != CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR); ReturnErrorOnFailure(error); // SL TODO -- store version somewhere diff --git a/src/platform/silabs/efr32/CHIPCryptoPALPsaEfr32.cpp b/src/platform/silabs/efr32/CHIPCryptoPALPsaEfr32.cpp index 6989e3a2c67945..8028d84d92c40c 100644 --- a/src/platform/silabs/efr32/CHIPCryptoPALPsaEfr32.cpp +++ b/src/platform/silabs/efr32/CHIPCryptoPALPsaEfr32.cpp @@ -2330,7 +2330,7 @@ CHIP_ERROR ExtractRawDNFromX509Cert(bool extractSubject, const ByteSpan & certif size_t len = 0; mbedtls_x509_crt mbedCertificate; - ReturnErrorCodeIf(certificate.empty(), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(!certificate.empty(), CHIP_ERROR_INVALID_ARGUMENT); mbedtls_x509_crt_init(&mbedCertificate); result = mbedtls_x509_crt_parse(&mbedCertificate, Uint8::to_const_uchar(certificate.data()), certificate.size()); @@ -2386,7 +2386,7 @@ CHIP_ERROR ReplaceCertIfResignedCertFound(const ByteSpan & referenceCertificate, outCertificate = referenceCertificate; - ReturnErrorCodeIf(candidateCertificates == nullptr || candidateCertificatesCount == 0, CHIP_NO_ERROR); + VerifyOrReturnError(candidateCertificates != nullptr && candidateCertificatesCount != 0, CHIP_NO_ERROR); ReturnErrorOnFailure(ExtractSubjectFromX509Cert(referenceCertificate, referenceSubject)); ReturnErrorOnFailure(ExtractSKIDFromX509Cert(referenceCertificate, referenceSKID)); diff --git a/src/platform/silabs/efr32/OTAImageProcessorImpl.cpp b/src/platform/silabs/efr32/OTAImageProcessorImpl.cpp index 846d4f720ac930..4fc7f8d7424cdd 100644 --- a/src/platform/silabs/efr32/OTAImageProcessorImpl.cpp +++ b/src/platform/silabs/efr32/OTAImageProcessorImpl.cpp @@ -45,7 +45,7 @@ uint8_t OTAImageProcessorImpl::writeBuffer[kAlignmentBytes] __attribute__((align CHIP_ERROR OTAImageProcessorImpl::Init(OTADownloader * downloader) { - ReturnErrorCodeIf(downloader == nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(downloader != nullptr, CHIP_ERROR_INVALID_ARGUMENT); gImageProcessor.SetOTADownloader(downloader); @@ -357,7 +357,7 @@ CHIP_ERROR OTAImageProcessorImpl::ProcessHeader(ByteSpan & block) CHIP_ERROR error = mHeaderParser.AccumulateAndDecode(block, header); // Needs more data to decode the header - ReturnErrorCodeIf(error == CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR); + VerifyOrReturnError(error != CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR); ReturnErrorOnFailure(error); // SL TODO -- store version somewhere diff --git a/src/platform/silabs/multi-ota/OTACustomProcessor.cpp b/src/platform/silabs/multi-ota/OTACustomProcessor.cpp index ef761d003e0499..6b87638adb9639 100644 --- a/src/platform/silabs/multi-ota/OTACustomProcessor.cpp +++ b/src/platform/silabs/multi-ota/OTACustomProcessor.cpp @@ -43,7 +43,7 @@ uint8_t OTACustomProcessor::writeBuffer[kAlignmentBytes] __attribute__((aligned( CHIP_ERROR OTACustomProcessor::Init() { - ReturnErrorCodeIf(mCallbackProcessDescriptor == nullptr, CHIP_OTA_PROCESSOR_CB_NOT_REGISTERED); + VerifyOrReturnError(mCallbackProcessDescriptor != nullptr, CHIP_OTA_PROCESSOR_CB_NOT_REGISTERED); mAccumulator.Init(sizeof(Descriptor)); return CHIP_NO_ERROR; diff --git a/src/platform/silabs/multi-ota/OTAFirmwareProcessor.cpp b/src/platform/silabs/multi-ota/OTAFirmwareProcessor.cpp index d8545d01f40996..07dc974dd7b54d 100644 --- a/src/platform/silabs/multi-ota/OTAFirmwareProcessor.cpp +++ b/src/platform/silabs/multi-ota/OTAFirmwareProcessor.cpp @@ -43,7 +43,7 @@ uint8_t OTAFirmwareProcessor::writeBuffer[kAlignmentBytes] __attribute__((aligne CHIP_ERROR OTAFirmwareProcessor::Init() { - ReturnErrorCodeIf(mCallbackProcessDescriptor == nullptr, CHIP_OTA_PROCESSOR_CB_NOT_REGISTERED); + VerifyOrReturnError(mCallbackProcessDescriptor != nullptr, CHIP_OTA_PROCESSOR_CB_NOT_REGISTERED); mAccumulator.Init(sizeof(Descriptor)); #if OTA_ENCRYPTION_ENABLE mUnalignmentNum = 0; diff --git a/src/platform/silabs/multi-ota/OTAMultiImageProcessorImpl.cpp b/src/platform/silabs/multi-ota/OTAMultiImageProcessorImpl.cpp index a95cb4e1ada4b4..42a9788c2868eb 100644 --- a/src/platform/silabs/multi-ota/OTAMultiImageProcessorImpl.cpp +++ b/src/platform/silabs/multi-ota/OTAMultiImageProcessorImpl.cpp @@ -42,7 +42,7 @@ namespace chip { CHIP_ERROR OTAMultiImageProcessorImpl::Init(OTADownloader * downloader) { - ReturnErrorCodeIf(downloader == nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(downloader != nullptr, CHIP_ERROR_INVALID_ARGUMENT); gImageProcessor.SetOTADownloader(downloader); @@ -297,7 +297,7 @@ CHIP_ERROR OTAMultiImageProcessorImpl::ConfirmCurrentImage() uint32_t targetVersion; OTARequestorInterface * requestor = chip::GetRequestorInstance(); - ReturnErrorCodeIf(requestor == nullptr, CHIP_ERROR_INTERNAL); + VerifyOrReturnError(requestor != nullptr, CHIP_ERROR_INTERNAL); targetVersion = requestor->GetTargetVersion(); ReturnErrorOnFailure(DeviceLayer::ConfigurationMgr().GetSoftwareVersion(currentVersion)); diff --git a/src/platform/stm32/FactoryDataProvider.cpp b/src/platform/stm32/FactoryDataProvider.cpp index 8b3d0af05a6ec7..c5a82393df3cd0 100644 --- a/src/platform/stm32/FactoryDataProvider.cpp +++ b/src/platform/stm32/FactoryDataProvider.cpp @@ -268,7 +268,7 @@ CHIP_ERROR FactoryDataProvider::GetVendorName(char * buf, size_t bufSize) { #if (CONFIG_STM32_FACTORY_DATA_ENABLE == 0) - ReturnErrorCodeIf(bufSize < sizeof(CHIP_DEVICE_CONFIG_DEVICE_VENDOR_NAME), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(bufSize >= sizeof(CHIP_DEVICE_CONFIG_DEVICE_VENDOR_NAME), CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(buf, CHIP_DEVICE_CONFIG_DEVICE_VENDOR_NAME, sizeof(CHIP_DEVICE_CONFIG_DEVICE_VENDOR_NAME)); #else @@ -287,7 +287,7 @@ CHIP_ERROR FactoryDataProvider::GetProductName(char * buf, size_t bufSize) { #if (CONFIG_STM32_FACTORY_DATA_ENABLE == 0) - ReturnErrorCodeIf(bufSize < sizeof(CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_NAME), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(bufSize >= sizeof(CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_NAME), CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(buf, CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_NAME, sizeof(CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_NAME)); #else FACTORYDATA_StatusTypeDef err; @@ -319,7 +319,7 @@ CHIP_ERROR FactoryDataProvider::GetSerialNumber(char * buf, size_t bufSize) CHIP_ERROR FactoryDataProvider::GetHardwareVersionString(char * buf, size_t bufSize) { - ReturnErrorCodeIf(bufSize < sizeof(CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION_STRING), CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(bufSize >= sizeof(CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION_STRING), CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(buf, CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION_STRING, sizeof(CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION_STRING)); return CHIP_NO_ERROR; diff --git a/src/platform/stm32/OTAImageProcessorImpl.cpp b/src/platform/stm32/OTAImageProcessorImpl.cpp index 76363befebb005..30967cd6146729 100644 --- a/src/platform/stm32/OTAImageProcessorImpl.cpp +++ b/src/platform/stm32/OTAImageProcessorImpl.cpp @@ -96,7 +96,7 @@ CHIP_ERROR OTAImageProcessorImpl::ProcessHeader(ByteSpan & block) CHIP_ERROR error = mHeaderParser.AccumulateAndDecode(block, header); // Needs more data to decode the header - ReturnErrorCodeIf(error == CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR); + VerifyOrReturnError(error != CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR); ReturnErrorOnFailure(error); mParams.totalFileBytes = header.mPayloadSize; diff --git a/src/platform/telink/FactoryDataProvider.cpp b/src/platform/telink/FactoryDataProvider.cpp index ba02131911370f..b2d58313f6178e 100644 --- a/src/platform/telink/FactoryDataProvider.cpp +++ b/src/platform/telink/FactoryDataProvider.cpp @@ -40,8 +40,8 @@ CHIP_ERROR LoadKeypairFromRaw(ByteSpan privateKey, ByteSpan publicKey, Crypto::P CHIP_ERROR GetFactoryDataString(const FactoryDataString & str, char * buf, size_t bufSize) { - ReturnErrorCodeIf(bufSize < str.len + 1, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!str.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(bufSize >= str.len + 1, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(str.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); memcpy(buf, str.data, str.len); buf[str.len] = 0; @@ -102,8 +102,8 @@ template CHIP_ERROR FactoryDataProvider::GetCertificationDeclaration(MutableByteSpan & outBuffer) { #if CONFIG_CHIP_CERTIFICATION_DECLARATION_STORAGE - ReturnErrorCodeIf(outBuffer.size() < mFactoryData.certificate_declaration.len, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!mFactoryData.certificate_declaration.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(outBuffer.size() >= mFactoryData.certificate_declaration.len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData.certificate_declaration.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); memcpy(outBuffer.data(), mFactoryData.certificate_declaration.data, mFactoryData.certificate_declaration.len); @@ -127,8 +127,8 @@ CHIP_ERROR FactoryDataProvider::GetFirmwareInformation(Mutable template CHIP_ERROR FactoryDataProvider::GetDeviceAttestationCert(MutableByteSpan & outBuffer) { - ReturnErrorCodeIf(outBuffer.size() < mFactoryData.dac_cert.len, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!mFactoryData.dac_cert.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(outBuffer.size() >= mFactoryData.dac_cert.len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData.dac_cert.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); memcpy(outBuffer.data(), mFactoryData.dac_cert.data, mFactoryData.dac_cert.len); @@ -140,8 +140,8 @@ CHIP_ERROR FactoryDataProvider::GetDeviceAttestationCert(Mutab template CHIP_ERROR FactoryDataProvider::GetProductAttestationIntermediateCert(MutableByteSpan & outBuffer) { - ReturnErrorCodeIf(outBuffer.size() < mFactoryData.pai_cert.len, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!mFactoryData.pai_cert.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(outBuffer.size() >= mFactoryData.pai_cert.len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData.pai_cert.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); memcpy(outBuffer.data(), mFactoryData.pai_cert.data, mFactoryData.pai_cert.len); @@ -158,8 +158,8 @@ CHIP_ERROR FactoryDataProvider::SignWithDeviceAttestationKey(c Crypto::P256Keypair keypair; VerifyOrReturnError(outSignBuffer.size() >= signature.Capacity(), CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!mFactoryData.dac_cert.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); - ReturnErrorCodeIf(!mFactoryData.dac_priv_key.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(mFactoryData.dac_cert.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(mFactoryData.dac_priv_key.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); // Extract public key from DAC cert. ByteSpan dacCertSpan{ reinterpret_cast(mFactoryData.dac_cert.data), mFactoryData.dac_cert.len }; @@ -191,7 +191,7 @@ CHIP_ERROR FactoryDataProvider::SetSetupDiscriminator(uint16_t template CHIP_ERROR FactoryDataProvider::GetSpake2pIterationCount(uint32_t & iterationCount) { - ReturnErrorCodeIf(mFactoryData.spake2_it == 0, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(mFactoryData.spake2_it != 0, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); iterationCount = mFactoryData.spake2_it; return CHIP_NO_ERROR; } @@ -199,8 +199,8 @@ CHIP_ERROR FactoryDataProvider::GetSpake2pIterationCount(uint3 template CHIP_ERROR FactoryDataProvider::GetSpake2pSalt(MutableByteSpan & saltBuf) { - ReturnErrorCodeIf(saltBuf.size() < mFactoryData.spake2_salt.len, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!mFactoryData.spake2_salt.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(saltBuf.size() >= mFactoryData.spake2_salt.len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData.spake2_salt.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); memcpy(saltBuf.data(), mFactoryData.spake2_salt.data, mFactoryData.spake2_salt.len); @@ -212,8 +212,8 @@ CHIP_ERROR FactoryDataProvider::GetSpake2pSalt(MutableByteSpan template CHIP_ERROR FactoryDataProvider::GetSpake2pVerifier(MutableByteSpan & verifierBuf, size_t & verifierLen) { - ReturnErrorCodeIf(verifierBuf.size() < mFactoryData.spake2_verifier.len, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!mFactoryData.spake2_verifier.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(verifierBuf.size() >= mFactoryData.spake2_verifier.len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData.spake2_verifier.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); memcpy(verifierBuf.data(), mFactoryData.spake2_verifier.data, mFactoryData.spake2_verifier.len); @@ -227,7 +227,7 @@ CHIP_ERROR FactoryDataProvider::GetSpake2pVerifier(MutableByte template CHIP_ERROR FactoryDataProvider::GetSetupPasscode(uint32_t & setupPasscode) { - ReturnErrorCodeIf(mFactoryData.passcode == 0, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(mFactoryData.passcode != 0, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); setupPasscode = mFactoryData.passcode; return CHIP_NO_ERROR; } @@ -317,8 +317,8 @@ CHIP_ERROR FactoryDataProvider::GetHardwareVersionString(char template CHIP_ERROR FactoryDataProvider::GetRotatingDeviceIdUniqueId(MutableByteSpan & uniqueIdSpan) { - ReturnErrorCodeIf(uniqueIdSpan.size() < mFactoryData.rd_uid.len, CHIP_ERROR_BUFFER_TOO_SMALL); - ReturnErrorCodeIf(!mFactoryData.rd_uid.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(uniqueIdSpan.size() >= mFactoryData.rd_uid.len, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData.rd_uid.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); memcpy(uniqueIdSpan.data(), mFactoryData.rd_uid.data, mFactoryData.rd_uid.len); @@ -328,8 +328,8 @@ CHIP_ERROR FactoryDataProvider::GetRotatingDeviceIdUniqueId(Mu template CHIP_ERROR FactoryDataProvider::GetEnableKey(MutableByteSpan & enableKey) { - ReturnErrorCodeIf(!mFactoryData.enable_key.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); - ReturnErrorCodeIf(enableKey.size() < mFactoryData.enable_key.len / 2, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mFactoryData.enable_key.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + VerifyOrReturnError(enableKey.size() >= mFactoryData.enable_key.len / 2, CHIP_ERROR_BUFFER_TOO_SMALL); Encoding::HexToBytes((const char *) mFactoryData.enable_key.data, mFactoryData.enable_key.len, enableKey.data(), enableKey.size()); diff --git a/src/platform/telink/OTAImageProcessorImpl.cpp b/src/platform/telink/OTAImageProcessorImpl.cpp index b1ce54748e268e..a47a59fadfdb38 100644 --- a/src/platform/telink/OTAImageProcessorImpl.cpp +++ b/src/platform/telink/OTAImageProcessorImpl.cpp @@ -159,10 +159,10 @@ CHIP_ERROR OTAImageProcessorImpl::ProcessBlock(ByteSpan & aBlock) bool OTAImageProcessorImpl::IsFirstImageRun() { OTARequestorInterface * requestor = GetRequestorInstance(); - ReturnErrorCodeIf(requestor == nullptr, false); + VerifyOrReturnError(requestor != nullptr, false); uint32_t currentVersion; - ReturnErrorCodeIf(ConfigurationMgr().GetSoftwareVersion(currentVersion) != CHIP_NO_ERROR, false); + VerifyOrReturnError(ConfigurationMgr().GetSoftwareVersion(currentVersion) == CHIP_NO_ERROR, false); return requestor->GetCurrentUpdateState() == OTARequestorInterface::OTAUpdateStateEnum::kApplying && requestor->GetTargetVersion() == currentVersion; @@ -182,7 +182,7 @@ CHIP_ERROR OTAImageProcessorImpl::ProcessHeader(ByteSpan & aBlock) CHIP_ERROR error = mHeaderParser.AccumulateAndDecode(aBlock, header); // Needs more data to decode the header - ReturnErrorCodeIf(error == CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR); + VerifyOrReturnError(error != CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR); ReturnErrorOnFailure(error); mParams.totalFileBytes = header.mPayloadSize; diff --git a/src/platform/webos/ChipDeviceScanner.cpp b/src/platform/webos/ChipDeviceScanner.cpp index 5a312281d6d8b9..5808b4bf482b61 100644 --- a/src/platform/webos/ChipDeviceScanner.cpp +++ b/src/platform/webos/ChipDeviceScanner.cpp @@ -294,7 +294,7 @@ gboolean ChipDeviceScanner::TriggerScan(GMainLoop * mainLoop, gpointer userData) CHIP_ERROR ChipDeviceScanner::StartChipScan(unsigned timeoutMs) { CHIP_ERROR err = CHIP_NO_ERROR; - ReturnErrorCodeIf(mIsScanning, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(!mIsScanning, CHIP_ERROR_INCORRECT_STATE); kScanTimeout = timeoutMs; @@ -327,7 +327,7 @@ bool ChipDeviceScanner::cancelDiscoveryCb(LSHandle * sh, LSMessage * message, vo CHIP_ERROR ChipDeviceScanner::StopChipScan() { int ret = 0; - ReturnErrorCodeIf(!mIsScanning, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mIsScanning, CHIP_ERROR_INCORRECT_STATE); ret = LSCall(mLSHandle, "luna://com.webos.service.bluetooth2/dadapter/cancelDiscovery", "{}", cancelDiscoveryCb, this, NULL, NULL); diff --git a/src/protocols/secure_channel/CASEServer.cpp b/src/protocols/secure_channel/CASEServer.cpp index fc6b4970ce0829..95d3a9c7714ec3 100644 --- a/src/protocols/secure_channel/CASEServer.cpp +++ b/src/protocols/secure_channel/CASEServer.cpp @@ -61,7 +61,7 @@ CHIP_ERROR CASEServer::ListenForSessionEstablishment(Messaging::ExchangeManager CHIP_ERROR CASEServer::InitCASEHandshake(Messaging::ExchangeContext * ec) { MATTER_TRACE_SCOPE("InitCASEHandshake", "CASEServer"); - ReturnErrorCodeIf(ec == nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(ec != nullptr, CHIP_ERROR_INVALID_ARGUMENT); // Hand over the exchange context to the CASE session. ec->SetDelegate(&GetSession()); diff --git a/src/protocols/secure_channel/CASESession.cpp b/src/protocols/secure_channel/CASESession.cpp index e0a0fa744e4cc3..007a58659f45cd 100644 --- a/src/protocols/secure_channel/CASESession.cpp +++ b/src/protocols/secure_channel/CASESession.cpp @@ -523,15 +523,15 @@ CHIP_ERROR CASESession::EstablishSession(SessionManager & sessionManager, Fabric CHIP_ERROR err = CHIP_NO_ERROR; // Return early on error here, as we have not initialized any state yet - ReturnErrorCodeWithMetricIf(kMetricDeviceCASESession, exchangeCtxt == nullptr, CHIP_ERROR_INVALID_ARGUMENT); - ReturnErrorCodeWithMetricIf(kMetricDeviceCASESession, fabricTable == nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnErrorWithMetric(kMetricDeviceCASESession, exchangeCtxt != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnErrorWithMetric(kMetricDeviceCASESession, fabricTable != nullptr, CHIP_ERROR_INVALID_ARGUMENT); // Use FabricTable directly to avoid situation of dangling index from stale FabricInfo // until we factor-out any FabricInfo direct usage. - ReturnErrorCodeWithMetricIf(kMetricDeviceCASESession, peerScopedNodeId.GetFabricIndex() == kUndefinedFabricIndex, - CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnErrorWithMetric(kMetricDeviceCASESession, peerScopedNodeId.GetFabricIndex() != kUndefinedFabricIndex, + CHIP_ERROR_INVALID_ARGUMENT); const auto * fabricInfo = fabricTable->FindFabricWithIndex(peerScopedNodeId.GetFabricIndex()); - ReturnErrorCodeWithMetricIf(kMetricDeviceCASESession, fabricInfo == nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnErrorWithMetric(kMetricDeviceCASESession, fabricInfo != nullptr, CHIP_ERROR_INVALID_ARGUMENT); err = Init(sessionManager, policy, delegate, peerScopedNodeId); @@ -784,7 +784,7 @@ CHIP_ERROR CASESession::SendSigma1() // Lookup fabric info. const auto * fabricInfo = mFabricsTable->FindFabricWithIndex(mFabricIndex); - ReturnErrorCodeIf(fabricInfo == nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(fabricInfo != nullptr, CHIP_ERROR_INCORRECT_STATE); // Validate that we have a session ID allocated. VerifyOrReturnError(GetLocalSessionId().HasValue(), CHIP_ERROR_INCORRECT_STATE); diff --git a/src/protocols/secure_channel/PASESession.cpp b/src/protocols/secure_channel/PASESession.cpp index 345b307f26c24d..638b99624bae6c 100644 --- a/src/protocols/secure_channel/PASESession.cpp +++ b/src/protocols/secure_channel/PASESession.cpp @@ -126,7 +126,7 @@ CHIP_ERROR PASESession::Init(SessionManager & sessionManager, uint32_t setupCode VerifyOrReturnError(GetLocalSessionId().HasValue(), CHIP_ERROR_INCORRECT_STATE); ChipLogDetail(SecureChannel, "Assigned local session key ID %u", GetLocalSessionId().Value()); - ReturnErrorCodeIf(setupCode >= (1 << kSetupPINCodeFieldLengthInBits), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(setupCode < (1 << kSetupPINCodeFieldLengthInBits), CHIP_ERROR_INVALID_ARGUMENT); mSetupPINCode = setupCode; return CHIP_NO_ERROR; @@ -162,10 +162,10 @@ CHIP_ERROR PASESession::WaitForPairing(SessionManager & sessionManager, const Sp SessionEstablishmentDelegate * delegate) { // Return early on error here, as we have not initialized any state yet - ReturnErrorCodeIf(salt.empty(), CHIP_ERROR_INVALID_ARGUMENT); - ReturnErrorCodeIf(salt.data() == nullptr, CHIP_ERROR_INVALID_ARGUMENT); - ReturnErrorCodeIf(salt.size() < kSpake2p_Min_PBKDF_Salt_Length || salt.size() > kSpake2p_Max_PBKDF_Salt_Length, - CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(!salt.empty(), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(salt.data() != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(salt.size() >= kSpake2p_Min_PBKDF_Salt_Length && salt.size() <= kSpake2p_Max_PBKDF_Salt_Length, + CHIP_ERROR_INVALID_ARGUMENT); CHIP_ERROR err = Init(sessionManager, kSetupPINCodeUndefinedValue, delegate); // From here onwards, let's go to exit on error, as some state might have already @@ -209,7 +209,7 @@ CHIP_ERROR PASESession::Pair(SessionManager & sessionManager, uint32_t peerSetUp SessionEstablishmentDelegate * delegate) { MATTER_TRACE_SCOPE("Pair", "PASESession"); - ReturnErrorCodeIf(exchangeCtxt == nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(exchangeCtxt != nullptr, CHIP_ERROR_INVALID_ARGUMENT); CHIP_ERROR err = Init(sessionManager, peerSetUpPINCode, delegate); SuccessOrExit(err); diff --git a/src/protocols/secure_channel/StatusReport.cpp b/src/protocols/secure_channel/StatusReport.cpp index e31c832b469f51..5ce7656c9ef224 100644 --- a/src/protocols/secure_channel/StatusReport.cpp +++ b/src/protocols/secure_channel/StatusReport.cpp @@ -50,7 +50,7 @@ CHIP_ERROR StatusReport::Parse(System::PacketBufferHandle buf) { uint16_t tempGeneralCode = 0; - ReturnErrorCodeIf(buf.IsNull(), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(!buf.IsNull(), CHIP_ERROR_INVALID_ARGUMENT); uint8_t * bufStart = buf->Start(); LittleEndian::Reader bufReader(bufStart, buf->DataLength()); diff --git a/src/setup_payload/QRCodeSetupPayloadParser.cpp b/src/setup_payload/QRCodeSetupPayloadParser.cpp index 99bf0e4983040b..102de4af69581b 100644 --- a/src/setup_payload/QRCodeSetupPayloadParser.cpp +++ b/src/setup_payload/QRCodeSetupPayloadParser.cpp @@ -267,10 +267,10 @@ CHIP_ERROR QRCodeSetupPayloadParser::populateTLV(SetupPayload & outPayload, cons size_t tlvBytesLength = (bitsLeftToRead + 7) / 8; // ceil(bitsLeftToRead/8) chip::Platform::ScopedMemoryBuffer tlvArray; - ReturnErrorCodeIf(tlvBytesLength == 0, CHIP_NO_ERROR); + VerifyOrReturnError(tlvBytesLength != 0, CHIP_NO_ERROR); tlvArray.Alloc(tlvBytesLength); - ReturnErrorCodeIf(!tlvArray, CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(tlvArray, CHIP_ERROR_NO_MEMORY); for (size_t i = 0; i < tlvBytesLength; i++) { diff --git a/src/system/SystemLayerImplSelect.cpp b/src/system/SystemLayerImplSelect.cpp index 3e8a79f7b6e44f..fe025a5765e659 100644 --- a/src/system/SystemLayerImplSelect.cpp +++ b/src/system/SystemLayerImplSelect.cpp @@ -427,7 +427,7 @@ CHIP_ERROR LayerImplSelect::RequestCallbackOnPendingRead(SocketWatchToken token) { watch->mRdSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, static_cast(watch->mFD), 0, dispatchQueue); - ReturnErrorCodeIf(watch->mRdSource == nullptr, CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(watch->mRdSource != nullptr, CHIP_ERROR_NO_MEMORY); dispatch_source_set_event_handler(watch->mRdSource, ^{ if (watch->mPendingIO.Has(SocketEventFlags::kRead) && watch->mCallback != nullptr) { @@ -487,7 +487,7 @@ CHIP_ERROR LayerImplSelect::RequestCallbackOnPendingWrite(SocketWatchToken token { watch->mWrSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_WRITE, static_cast(watch->mFD), 0, dispatchQueue); - ReturnErrorCodeIf(watch->mWrSource == nullptr, CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(watch->mWrSource != nullptr, CHIP_ERROR_NO_MEMORY); dispatch_source_set_event_handler(watch->mWrSource, ^{ if (watch->mPendingIO.Has(SocketEventFlags::kWrite) && watch->mCallback != nullptr) { diff --git a/src/tracing/metric_macros.h b/src/tracing/metric_macros.h index 3d00e7d9d9677b..1a2596ec2c93e5 100644 --- a/src/tracing/metric_macros.h +++ b/src/tracing/metric_macros.h @@ -241,36 +241,6 @@ } while (false) #endif // CHIP_CONFIG_ERROR_SOURCE -/** - * @def ReturnErrorCodeWithMetricIf(kMetricKey, expr, code) - * - * @brief - * Returns a specified error code if expression evaluates to true - * If the expression evaluates to true, a metric with the specified key is emitted - * with the value set to code. - * - * Example usage: - * - * @code - * ReturnErrorCodeWithMetricIf(kMetricKey, state == kInitialized, CHIP_NO_ERROR); - * ReturnErrorCodeWithMetricIf(kMetricKey, state == kInitialized, CHIP_ERROR_INCORRECT_STATE); - * @endcode - * - * @param[in] kMetricKey Metric key for the metric event to be emitted if the expr evaluates - * to true. Value of the metric is to code. - * @param[in] expr A Boolean expression to be evaluated. - * @param[in] code A value to return if @a expr is false. - */ -#define ReturnErrorCodeWithMetricIf(kMetricKey, expr, code) \ - do \ - { \ - if (expr) \ - { \ - MATTER_LOG_METRIC(kMetricKey, code); \ - return code; \ - } \ - } while (false) - /** * @def SuccessOrExitWithMetric(kMetricKey, error) * @@ -577,14 +547,12 @@ #define VerifyOrReturnWithMetric(kMetricKey, expr, ...) VerifyOrReturn(expr, ##__VA_ARGS__) -#define VerifyOrReturnErrorWithMetric(kMetricKey, expr, code, ...) VerifyOrReturnValue(expr, code, ##__VA_ARGS__) +#define VerifyOrReturnErrorWithMetric(kMetricKey, expr, code, ...) VerifyOrReturnError(expr, code, ##__VA_ARGS__) #define VerifyOrReturnValueWithMetric(kMetricKey, expr, value, ...) VerifyOrReturnValue(expr, value, ##__VA_ARGS__) #define VerifyOrReturnLogErrorWithMetric(kMetricKey, expr, code) VerifyOrReturnLogError(expr, code) -#define ReturnErrorCodeWithMetricIf(kMetricKey, expr, code) ReturnErrorCodeIf(expr, code) - #define SuccessOrExitWithMetric(kMetricKey, aStatus) SuccessOrExit(aStatus) #define VerifyOrExitWithMetric(kMetricKey, aCondition, anAction) VerifyOrExit(aCondition, anAction) diff --git a/src/tracing/tests/TestMetricEvents.cpp b/src/tracing/tests/TestMetricEvents.cpp index 20c6f7788ad69e..d3796477c09f89 100644 --- a/src/tracing/tests/TestMetricEvents.cpp +++ b/src/tracing/tests/TestMetricEvents.cpp @@ -523,39 +523,6 @@ TEST(TestMetricEvents, TestVerifyOrReturnLogErrorWithMetric) EXPECT_TRUE(std::equal(backend.GetMetricEvents().begin(), backend.GetMetricEvents().end(), expected.begin(), expected.end())); } -template -static return_code_type InvokeReturnErrorCodeWithMetricIf(MetricKey key, bool expr, const return_code_type & code) -{ - ReturnErrorCodeWithMetricIf(key, expr, code); - return return_code_type(); -} - -TEST(TestMetricEvents, TestReturnErrorCodeWithMetricIf) -{ - MetricEventBackend backend; - ScopedRegistration scope(backend); - - auto err = InvokeReturnErrorCodeWithMetricIf("event0", DoubleOf(2) == 4, CHIP_ERROR_DUPLICATE_KEY_ID); - EXPECT_EQ(err, CHIP_ERROR_DUPLICATE_KEY_ID); - - auto retval = InvokeReturnErrorCodeWithMetricIf("event1", DoubleOf(3) == 9, 11); - EXPECT_EQ(retval, 0); - - retval = InvokeReturnErrorCodeWithMetricIf("event2", DoubleOf(4) == 8, 22); - EXPECT_EQ(retval, 22); - - err = InvokeReturnErrorCodeWithMetricIf("event3", DoubleOf(5) == 11, CHIP_ERROR_ACCESS_DENIED); - EXPECT_EQ(err, CHIP_NO_ERROR); - - std::vector expected = { - MetricEvent(MetricEvent::Type::kInstantEvent, "event0", CHIP_ERROR_DUPLICATE_KEY_ID), - MetricEvent(MetricEvent::Type::kInstantEvent, "event2", 22), - }; - - EXPECT_EQ(backend.GetMetricEvents().size(), expected.size()); - EXPECT_TRUE(std::equal(backend.GetMetricEvents().begin(), backend.GetMetricEvents().end(), expected.begin(), expected.end())); -} - TEST(TestMetricEvents, TestExitNowWithMetric) { MetricEventBackend backend; diff --git a/src/transport/SecureMessageCodec.cpp b/src/transport/SecureMessageCodec.cpp index 263b4e5e127a5a..4e8cef59beb12b 100644 --- a/src/transport/SecureMessageCodec.cpp +++ b/src/transport/SecureMessageCodec.cpp @@ -61,7 +61,7 @@ CHIP_ERROR Encrypt(const CryptoContext & context, CryptoContext::ConstNonceView CHIP_ERROR Decrypt(const CryptoContext & context, CryptoContext::ConstNonceView nonce, PayloadHeader & payloadHeader, const PacketHeader & packetHeader, System::PacketBufferHandle & msg) { - ReturnErrorCodeIf(msg.IsNull(), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(!msg.IsNull(), CHIP_ERROR_INVALID_ARGUMENT); uint8_t * data = msg->Start(); size_t len = msg->DataLength(); diff --git a/src/transport/raw/BLE.cpp b/src/transport/raw/BLE.cpp index 811969ef0966ea..2872db5bf3ae0b 100644 --- a/src/transport/raw/BLE.cpp +++ b/src/transport/raw/BLE.cpp @@ -96,9 +96,9 @@ CHIP_ERROR BLEBase::SetEndPoint(Ble::BLEEndPoint * endPoint) CHIP_ERROR BLEBase::SendMessage(const Transport::PeerAddress & address, System::PacketBufferHandle && msgBuf) { - ReturnErrorCodeIf(address.GetTransportType() != Type::kBle, CHIP_ERROR_INVALID_ARGUMENT); - ReturnErrorCodeIf(mBleEndPoint == nullptr, CHIP_ERROR_INCORRECT_STATE); - ReturnErrorCodeIf(mState == State::kNotReady, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(address.GetTransportType() == Type::kBle, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(mBleEndPoint != nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(mState != State::kNotReady, CHIP_ERROR_INCORRECT_STATE); if (mState == State::kConnected) { diff --git a/src/transport/raw/WiFiPAF.cpp b/src/transport/raw/WiFiPAF.cpp index 97b465dd261e9b..56c16b3342200c 100644 --- a/src/transport/raw/WiFiPAF.cpp +++ b/src/transport/raw/WiFiPAF.cpp @@ -79,8 +79,8 @@ CHIP_ERROR WiFiPAFBase::Init(const WiFiPAFListenParameters & param) CHIP_ERROR WiFiPAFBase::SendMessage(const Transport::PeerAddress & address, System::PacketBufferHandle && msgBuf) { - ReturnErrorCodeIf(address.GetTransportType() != Type::kWiFiPAF, CHIP_ERROR_INVALID_ARGUMENT); - ReturnErrorCodeIf(mState == State::kNotReady, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(address.GetTransportType() == Type::kWiFiPAF, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(mState != State::kNotReady, CHIP_ERROR_INCORRECT_STATE); DeviceLayer::ConnectivityMgr().WiFiPAFSend(std::move(msgBuf)); return CHIP_NO_ERROR;