diff --git a/src/core/config/openthread-core-config-check.h b/src/core/config/openthread-core-config-check.h index de4fe1559..1f3a7c59c 100644 --- a/src/core/config/openthread-core-config-check.h +++ b/src/core/config/openthread-core-config-check.h @@ -673,4 +673,9 @@ "OPENTHREAD_CONFIG_MIN_RECEIVE_ON_AHEAD and OPENTHREAD_CONFIG_MIN_RECEIVE_ON_AFTER" #endif +#ifdef OPENTHREAD_CONFIG_PLATFORM_RADIO_SPINEL_RX_FRAME_BUFFER_SIZE +#error "OPENTHREAD_CONFIG_PLATFORM_RADIO_SPINEL_RX_FRAME_BUFFER_SIZE was replaced by"\ + "OPENTHREAD_LIB_SPINEL_RX_FRAME_BUFFER_SIZE. Pass the macro to source code under"\ + "src/lib/spinel." +#endif #endif // OPENTHREAD_CORE_CONFIG_CHECK_H_ diff --git a/src/core/config/platform.h b/src/core/config/platform.h index bfc00a46c..b8b48beca 100644 --- a/src/core/config/platform.h +++ b/src/core/config/platform.h @@ -143,17 +143,6 @@ #define OPENTHREAD_CONFIG_PLATFORM_RADIO_COEX_ENABLE 0 #endif -/** - * @def OPENTHREAD_CONFIG_PLATFORM_RADIO_SPINEL_RX_FRAME_BUFFER_SIZE - * - * Specifies the rx frame buffer size used by `SpinelInterface` in RCP host (posix) code. This is applicable/used when - * `RadioSpinel` platform is used. - * - */ -#ifndef OPENTHREAD_CONFIG_PLATFORM_RADIO_SPINEL_RX_FRAME_BUFFER_SIZE -#define OPENTHREAD_CONFIG_PLATFORM_RADIO_SPINEL_RX_FRAME_BUFFER_SIZE 8192 -#endif - /** * @def OPENTHREAD_CONFIG_PLATFORM_RADIO_PROPRIETARY_SUPPORT * diff --git a/src/lib/hdlc/hdlc.cpp b/src/lib/hdlc/hdlc.cpp index cde7ce8d5..b5a7948fc 100644 --- a/src/lib/hdlc/hdlc.cpp +++ b/src/lib/hdlc/hdlc.cpp @@ -34,7 +34,7 @@ #include -#include "common/code_utils.hpp" +#include "lib/utils/utils.hpp" namespace ot { namespace Hdlc { @@ -136,14 +136,14 @@ otError Encoder::Encode(uint8_t aByte) if (HdlcByteNeedsEscape(aByte)) { - VerifyOrExit(mWritePointer.CanWrite(2), error = OT_ERROR_NO_BUFS); + EXPECT(mWritePointer.CanWrite(2), error = OT_ERROR_NO_BUFS); - IgnoreError(mWritePointer.WriteByte(kEscapeSequence)); - IgnoreError(mWritePointer.WriteByte(aByte ^ 0x20)); + IGNORE_RETURN(mWritePointer.WriteByte(kEscapeSequence)); + IGNORE_RETURN(mWritePointer.WriteByte(aByte ^ 0x20)); } else { - SuccessOrExit(error = mWritePointer.WriteByte(aByte)); + EXPECT_NO_ERROR(error = mWritePointer.WriteByte(aByte)); } mFcs = UpdateFcs(mFcs, aByte); @@ -160,7 +160,7 @@ otError Encoder::Encode(const uint8_t *aData, uint16_t aLength) while (aLength--) { - SuccessOrExit(error = Encode(*aData++)); + EXPECT_NO_ERROR(error = Encode(*aData++)); } exit: @@ -183,10 +183,10 @@ otError Encoder::EndFrame(void) fcs ^= 0xffff; - SuccessOrExit(error = Encode(fcs & 0xff)); - SuccessOrExit(error = Encode(fcs >> 8)); + EXPECT_NO_ERROR(error = Encode(fcs & 0xff)); + EXPECT_NO_ERROR(error = Encode(fcs >> 8)); - SuccessOrExit(error = mWritePointer.WriteByte(kFlagSequence)); + EXPECT_NO_ERROR(error = mWritePointer.WriteByte(kFlagSequence)); exit: @@ -276,7 +276,7 @@ void Decoder::Decode(const uint8_t *aData, uint16_t aLength) if (mWritePointer->CanWrite(sizeof(uint8_t))) { mFcs = UpdateFcs(mFcs, byte); - IgnoreError(mWritePointer->WriteByte(byte)); + IGNORE_RETURN(mWritePointer->WriteByte(byte)); mDecodedLength++; } else @@ -295,7 +295,7 @@ void Decoder::Decode(const uint8_t *aData, uint16_t aLength) { byte ^= 0x20; mFcs = UpdateFcs(mFcs, byte); - IgnoreError(mWritePointer->WriteByte(byte)); + IGNORE_RETURN(mWritePointer->WriteByte(byte)); mDecodedLength++; mState = kStateSync; } diff --git a/src/lib/spinel/logger.cpp b/src/lib/spinel/logger.cpp index c01761343..07b358f94 100644 --- a/src/lib/spinel/logger.cpp +++ b/src/lib/spinel/logger.cpp @@ -36,13 +36,17 @@ #include #include -#include "common/code_utils.hpp" -#include "common/num_utils.hpp" +#include "lib/spinel/spinel-config.h" #include "lib/spinel/spinel.h" +#include "lib/utils/math.hpp" +#include "lib/utils/utils.hpp" namespace ot { namespace Spinel { +using Lib::Utils::Min; +using Lib::Utils::ToUlong; + Logger::Logger(const char *aModuleName) : mModuleName(aModuleName) { @@ -117,8 +121,8 @@ uint32_t Logger::Snprintf(char *aDest, uint32_t aSize, const char *aFormat, ...) void Logger::LogSpinelFrame(const uint8_t *aFrame, uint16_t aLength, bool aTx) { - otError error = OT_ERROR_NONE; - char buf[OPENTHREAD_CONFIG_LOG_MAX_SIZE] = {0}; + otError error = OT_ERROR_NONE; + char buf[OPENTHREAD_LIB_SPINEL_LOG_MAX_SIZE] = {0}; spinel_ssize_t unpacked; uint8_t header; uint32_t cmd; @@ -129,19 +133,19 @@ void Logger::LogSpinelFrame(const uint8_t *aFrame, uint16_t aLength, bool aTx) char *start = buf; char *end = buf + sizeof(buf); - VerifyOrExit(otLoggingGetLevel() >= OT_LOG_LEVEL_DEBG); + EXPECT(otLoggingGetLevel() >= OT_LOG_LEVEL_DEBG, NO_ACTION); prefix = aTx ? "Sent spinel frame" : "Received spinel frame"; unpacked = spinel_datatype_unpack(aFrame, aLength, "CiiD", &header, &cmd, &key, &data, &len); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); start += Snprintf(start, static_cast(end - start), "%s, flg:0x%x, iid:%d, tid:%u, cmd:%s", prefix, SPINEL_HEADER_GET_FLAG(header), SPINEL_HEADER_GET_IID(header), SPINEL_HEADER_GET_TID(header), spinel_command_to_cstr(cmd)); - VerifyOrExit(cmd != SPINEL_CMD_RESET); + EXPECT(cmd != SPINEL_CMD_RESET, NO_ACTION); start += Snprintf(start, static_cast(end - start), ", key:%s", spinel_prop_key_to_cstr(key)); - VerifyOrExit(cmd != SPINEL_CMD_PROP_VALUE_GET); + EXPECT(cmd != SPINEL_CMD_PROP_VALUE_GET, NO_ACTION); switch (key) { @@ -150,7 +154,7 @@ void Logger::LogSpinelFrame(const uint8_t *aFrame, uint16_t aLength, bool aTx) spinel_status_t status; unpacked = spinel_datatype_unpack(data, len, SPINEL_DATATYPE_UINT_PACKED_S, &status); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); start += Snprintf(start, static_cast(end - start), ", status:%s", spinel_status_to_cstr(status)); } break; @@ -163,7 +167,7 @@ void Logger::LogSpinelFrame(const uint8_t *aFrame, uint16_t aLength, bool aTx) bool enabled; unpacked = spinel_datatype_unpack(data, len, SPINEL_DATATYPE_BOOL_S, &enabled); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); start += Snprintf(start, static_cast(end - start), ", enabled:%u", enabled); } break; @@ -178,7 +182,7 @@ void Logger::LogSpinelFrame(const uint8_t *aFrame, uint16_t aLength, bool aTx) int8_t value; unpacked = spinel_datatype_unpack(data, len, SPINEL_DATATYPE_INT8_S, &value); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); switch (key) { @@ -213,7 +217,7 @@ void Logger::LogSpinelFrame(const uint8_t *aFrame, uint16_t aLength, bool aTx) uint8_t value; unpacked = spinel_datatype_unpack(data, len, SPINEL_DATATYPE_UINT8_S, &value); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); switch (key) { @@ -247,7 +251,7 @@ void Logger::LogSpinelFrame(const uint8_t *aFrame, uint16_t aLength, bool aTx) uint16_t value; unpacked = spinel_datatype_unpack(data, len, SPINEL_DATATYPE_UINT16_S, &value); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); switch (key) { @@ -287,7 +291,7 @@ void Logger::LogSpinelFrame(const uint8_t *aFrame, uint16_t aLength, bool aTx) while (len >= sizeof(saddr)) { unpacked = spinel_datatype_unpack(data, len, SPINEL_DATATYPE_UINT16_S, &saddr); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); data += unpacked; len -= static_cast(unpacked); start += Snprintf(start, static_cast(end - start), "0x%04x ", saddr); @@ -303,7 +307,7 @@ void Logger::LogSpinelFrame(const uint8_t *aFrame, uint16_t aLength, bool aTx) uint32_t value; unpacked = spinel_datatype_unpack(data, len, SPINEL_DATATYPE_UINT32_S, &value); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); name = (key == SPINEL_PROP_RCP_TIMESTAMP) ? "timestamp" : "counter"; start += Snprintf(start, static_cast(end - start), ", %s:%u", name, value); @@ -318,7 +322,7 @@ void Logger::LogSpinelFrame(const uint8_t *aFrame, uint16_t aLength, bool aTx) unsigned int value; unpacked = spinel_datatype_unpack(data, len, SPINEL_DATATYPE_UINT_PACKED_S, &value); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); switch (key) { @@ -357,7 +361,7 @@ void Logger::LogSpinelFrame(const uint8_t *aFrame, uint16_t aLength, bool aTx) int8_t value; unpacked = spinel_datatype_unpack(data, len, SPINEL_DATATYPE_UINT8_S SPINEL_DATATYPE_INT8_S, &channel, &value); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); name = (key == SPINEL_PROP_MAC_ENERGY_SCAN_RESULT) ? "rssi" : "power"; start += Snprintf(start, static_cast(end - start), ", channel:%u, %s:%d", channel, name, value); @@ -373,7 +377,7 @@ void Logger::LogSpinelFrame(const uint8_t *aFrame, uint16_t aLength, bool aTx) while (len > 0) { unpacked = spinel_datatype_unpack(data, len, SPINEL_DATATYPE_UINT_PACKED_S, &capability); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); data += unpacked; len -= static_cast(unpacked); start += Snprintf(start, static_cast(end - start), "%s ", spinel_capability_to_cstr(capability)); @@ -388,7 +392,7 @@ void Logger::LogSpinelFrame(const uint8_t *aFrame, uint16_t aLength, bool aTx) unpacked = spinel_datatype_unpack(data, len, SPINEL_DATATYPE_UINT_PACKED_S SPINEL_DATATYPE_UINT_PACKED_S, &major, &minor); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); start += Snprintf(start, static_cast(end - start), ", major:%u, minor:%u", major, minor); } break; @@ -402,15 +406,15 @@ void Logger::LogSpinelFrame(const uint8_t *aFrame, uint16_t aLength, bool aTx) spinel_size_t maskLength = sizeof(maskBuffer); unpacked = spinel_datatype_unpack_in_place(data, len, SPINEL_DATATYPE_DATA_S, maskBuffer, &maskLength); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); while (maskLength > 0) { uint8_t channel; unpacked = spinel_datatype_unpack(maskData, maskLength, SPINEL_DATATYPE_UINT8_S, &channel); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); - VerifyOrExit(channel < kChannelMaskBufferSize, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(channel < kChannelMaskBufferSize, error = OT_ERROR_PARSE); channelMask |= (1UL << channel); maskData += unpacked; @@ -426,7 +430,7 @@ void Logger::LogSpinelFrame(const uint8_t *aFrame, uint16_t aLength, bool aTx) const char *version; unpacked = spinel_datatype_unpack(data, len, SPINEL_DATATYPE_UTF8_S, &version); - VerifyOrExit(unpacked >= 0, error = OT_ERROR_PARSE); + EXPECT(unpacked >= 0, error = OT_ERROR_PARSE); start += Snprintf(start, static_cast(end - start), ", version:%s", version); } break; @@ -456,7 +460,7 @@ void Logger::LogSpinelFrame(const uint8_t *aFrame, uint16_t aLength, bool aTx) &frame.mPsdu, &frame.mLength, &frame.mInfo.mRxInfo.mRssi, &noiseFloor, &flags, &frame.mChannel, &frame.mInfo.mRxInfo.mLqi, &frame.mInfo.mRxInfo.mTimestamp, &receiveError); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); start += Snprintf(start, static_cast(end - start), ", len:%u, rssi:%d ...", frame.mLength, frame.mInfo.mRxInfo.mRssi); OT_UNUSED_VARIABLE(start); // Avoid static analysis error @@ -491,7 +495,7 @@ void Logger::LogSpinelFrame(const uint8_t *aFrame, uint16_t aLength, bool aTx) &frame.mInfo.mTxInfo.mMaxFrameRetries, &csmaCaEnabled, &isHeaderUpdated, &isARetx, &skipAes, &frame.mInfo.mTxInfo.mTxDelay, &frame.mInfo.mTxInfo.mTxDelayBaseTime); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); start += Snprintf(start, static_cast(end - start), ", len:%u, channel:%u, maxbackoffs:%u, maxretries:%u ...", frame.mLength, frame.mChannel, frame.mInfo.mTxInfo.mMaxCsmaBackoffs, frame.mInfo.mTxInfo.mMaxFrameRetries); @@ -510,12 +514,12 @@ void Logger::LogSpinelFrame(const uint8_t *aFrame, uint16_t aLength, bool aTx) case SPINEL_PROP_STREAM_DEBUG: { - char debugString[OPENTHREAD_CONFIG_NCP_SPINEL_LOG_MAX_SIZE + 1]; + char debugString[OPENTHREAD_LIB_SPINEL_NCP_LOG_MAX_SIZE + 1]; spinel_size_t stringLength = sizeof(debugString); unpacked = spinel_datatype_unpack_in_place(data, len, SPINEL_DATATYPE_DATA_S, debugString, &stringLength); assert(stringLength < sizeof(debugString)); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); debugString[stringLength] = '\0'; start += Snprintf(start, static_cast(end - start), ", debug:%s", debugString); } @@ -527,12 +531,12 @@ void Logger::LogSpinelFrame(const uint8_t *aFrame, uint16_t aLength, bool aTx) uint8_t logLevel; unpacked = spinel_datatype_unpack(data, len, SPINEL_DATATYPE_UTF8_S, &logString); - VerifyOrExit(unpacked >= 0, error = OT_ERROR_PARSE); + EXPECT(unpacked >= 0, error = OT_ERROR_PARSE); data += unpacked; len -= static_cast(unpacked); unpacked = spinel_datatype_unpack(data, len, SPINEL_DATATYPE_UINT8_S, &logLevel); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); start += Snprintf(start, static_cast(end - start), ", level:%u, log:%s", logLevel, logString); } break; @@ -543,7 +547,7 @@ void Logger::LogSpinelFrame(const uint8_t *aFrame, uint16_t aLength, bool aTx) size_t outputLen; unpacked = spinel_datatype_unpack(data, len, SPINEL_DATATYPE_UTF8_S, &output, &outputLen); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); start += Snprintf(start, static_cast(end - start), ", diag:%s", output); } break; @@ -564,7 +568,7 @@ void Logger::LogSpinelFrame(const uint8_t *aFrame, uint16_t aLength, bool aTx) SPINEL_DATATYPE_DATA_WLEN_S SPINEL_DATATYPE_DATA_WLEN_S, &keyIdMode, &keyId, prevKey.m8, &prevKeyLen, currKey.m8, &currKeyLen, nextKey.m8, &nextKeyLen); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); start += Snprintf(start, static_cast(end - start), ", keyIdMode:%u, keyId:%u, prevKey:***, currKey:***, nextKey:***", keyIdMode, keyId); } @@ -577,7 +581,7 @@ void Logger::LogSpinelFrame(const uint8_t *aFrame, uint16_t aLength, bool aTx) uint8_t m8[OT_EXT_ADDRESS_SIZE] = {0}; unpacked = spinel_datatype_unpack_in_place(data, len, SPINEL_DATATYPE_EUI64_S, &m8[0]); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); name = (key == SPINEL_PROP_HWADDR) ? "eui64" : "laddr"; start += Snprintf(start, static_cast(end - start), ", %s:%02x%02x%02x%02x%02x%02x%02x%02x", name, @@ -600,7 +604,7 @@ void Logger::LogSpinelFrame(const uint8_t *aFrame, uint16_t aLength, bool aTx) while (len >= sizeof(m8)) { unpacked = spinel_datatype_unpack_in_place(data, len, SPINEL_DATATYPE_EUI64_S, m8); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); data += unpacked; len -= static_cast(unpacked); start += Snprintf(start, static_cast(end - start), "%02x%02x%02x%02x%02x%02x%02x%02x ", m8[0], @@ -644,7 +648,7 @@ void Logger::LogSpinelFrame(const uint8_t *aFrame, uint16_t aLength, bool aTx) &metrics.mNumRxGrantDeactivatedDuringRequest, &metrics.mNumRxDelayedGrant, &metrics.mAvgRxRequestToGrantTime, &metrics.mNumRxGrantNone, &metrics.mStopped, &metrics.mNumGrantGlitch); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); LogDebg("%s ...", buf); LogDebg(" txRequest:%lu", ToUlong(metrics.mNumTxRequest)); @@ -678,7 +682,7 @@ void Logger::LogSpinelFrame(const uint8_t *aFrame, uint16_t aLength, bool aTx) spinel_size_t size; unpacked = spinel_datatype_unpack(data, len, SPINEL_DATATYPE_DATA_S, channels, &size); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); start += Snprintf(start, static_cast(end - start), ", channels:"); for (spinel_size_t i = 0; i < size; i++) @@ -697,7 +701,7 @@ void Logger::LogSpinelFrame(const uint8_t *aFrame, uint16_t aLength, bool aTx) unpacked = spinel_datatype_unpack( data, len, SPINEL_DATATYPE_UINT16_S SPINEL_DATATYPE_EUI64_S SPINEL_DATATYPE_UINT8_S, &saddr, m8, &flags); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); start += Snprintf(start, static_cast(end - start), ", saddr:%04x, extaddr:%02x%02x%02x%02x%02x%02x%02x%02x, flags:0x%02x", saddr, m8[0], m8[1], m8[2], m8[3], m8[4], m8[5], m8[6], m8[7], flags); @@ -716,7 +720,7 @@ void Logger::LogSpinelFrame(const uint8_t *aFrame, uint16_t aLength, bool aTx) unpacked = spinel_datatype_unpack( data, len, SPINEL_DATATYPE_UINT8_S SPINEL_DATATYPE_INT16_S SPINEL_DATATYPE_DATA_WLEN_S, &channel, &actualPower, &rawPowerSetting, &rawPowerSettingLength); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); start += Snprintf(start, static_cast(end - start), ", ch:%u, actualPower:%d, rawPowerSetting:", channel, actualPower); @@ -735,7 +739,7 @@ void Logger::LogSpinelFrame(const uint8_t *aFrame, uint16_t aLength, bool aTx) unpacked = spinel_datatype_unpack(data, len, SPINEL_DATATYPE_UINT8_S SPINEL_DATATYPE_INT16_S, &channel, &targetPower); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); start += Snprintf(start, static_cast(end - start), ", ch:%u, targetPower:%d", channel, targetPower); } break; diff --git a/src/lib/spinel/logger.hpp b/src/lib/spinel/logger.hpp index ea86f4d7c..86d31b9c5 100644 --- a/src/lib/spinel/logger.hpp +++ b/src/lib/spinel/logger.hpp @@ -29,13 +29,9 @@ #ifndef SPINEL_LOGGER_HPP_ #define SPINEL_LOGGER_HPP_ -#include "openthread-core-config.h" - #include #include -#include "ncp/ncp_config.h" - namespace ot { namespace Spinel { diff --git a/src/lib/spinel/multi_frame_buffer.hpp b/src/lib/spinel/multi_frame_buffer.hpp index 61945a5ca..0ff30aa23 100644 --- a/src/lib/spinel/multi_frame_buffer.hpp +++ b/src/lib/spinel/multi_frame_buffer.hpp @@ -33,17 +33,13 @@ #ifndef SPINEL_MULTI_FRAME_BUFFER_HPP_ #define SPINEL_MULTI_FRAME_BUFFER_HPP_ +#include #include #include #include #include -#include "common/array.hpp" -#include "common/code_utils.hpp" -#include "common/debug.hpp" -#include "common/encoding.hpp" - namespace ot { namespace Spinel { @@ -367,7 +363,7 @@ public: { otError error = OT_ERROR_NONE; - OT_ASSERT(aFrame == nullptr || (mBuffer <= aFrame && aFrame < GetArrayEnd(mBuffer))); + assert(aFrame == nullptr || (mBuffer <= aFrame && aFrame < GetArrayEnd(mBuffer))); aFrame = (aFrame == nullptr) ? mBuffer : aFrame + aLength; @@ -451,6 +447,32 @@ private: kHeaderSize = sizeof(uint16_t) + sizeof(uint16_t), }; + template Type *GetArrayEnd(Type (&aArray)[kArrayLength]) + { + return &aArray[kArrayLength]; + } + + template const Type *GetArrayEnd(const Type (&aArray)[kArrayLength]) + { + return &aArray[kArrayLength]; + } + + static void IgnoreError(otError aError) { (void)(aError); } + + class LittleEndian + { + public: + static uint16_t ReadUint16(const uint8_t *aBuffer) + { + return static_cast((aBuffer[0] << 8) | aBuffer[1]); + } + static void WriteUint16(uint16_t aValue, uint8_t *aBuffer) + { + aBuffer[0] = (aValue >> 8) & 0xff; + aBuffer[1] = (aValue >> 0) & 0xff; + } + }; + uint8_t mBuffer[kSize]; uint8_t *mWriteFrameStart; // Pointer to start of current frame being written. }; diff --git a/src/lib/spinel/radio_spinel.cpp b/src/lib/spinel/radio_spinel.cpp index 38ce7f318..0ec71066b 100644 --- a/src/lib/spinel/radio_spinel.cpp +++ b/src/lib/spinel/radio_spinel.cpp @@ -42,13 +42,11 @@ #include #include -#include "common/code_utils.hpp" -#include "common/encoding.hpp" -#include "common/new.hpp" #include "lib/platform/exit_code.h" #include "lib/spinel/logger.hpp" #include "lib/spinel/spinel_decoder.hpp" #include "lib/spinel/spinel_driver.hpp" +#include "lib/utils/utils.hpp" namespace ot { namespace Spinel { @@ -137,13 +135,13 @@ void RadioSpinel::Init(bool aSkipRcpCompatibilityCheck, bool aSoftwareReset, Spi mTxRadioFrame.mInfo.mTxInfo.mIeInfo = &mTxIeInfo; #endif - SuccessOrExit(error = Get(SPINEL_PROP_HWADDR, SPINEL_DATATYPE_EUI64_S, sIeeeEui64.m8)); + EXPECT_NO_ERROR(error = Get(SPINEL_PROP_HWADDR, SPINEL_DATATYPE_EUI64_S, sIeeeEui64.m8)); InitializeCaps(supportsRcpApiVersion, supportsRcpMinHostApiVersion); if (sSupportsLogCrashDump) { LogDebg("RCP supports crash dump logging. Requesting crash dump."); - SuccessOrExit(error = Set(SPINEL_PROP_RCP_LOG_CRASH_DUMP, nullptr)); + EXPECT_NO_ERROR(error = Set(SPINEL_PROP_RCP_LOG_CRASH_DUMP, nullptr)); } if (!aSkipRcpCompatibilityCheck) @@ -180,9 +178,9 @@ otError RadioSpinel::CheckSpinelVersion(void) unsigned int versionMajor; unsigned int versionMinor; - SuccessOrExit(error = - Get(SPINEL_PROP_PROTOCOL_VERSION, (SPINEL_DATATYPE_UINT_PACKED_S SPINEL_DATATYPE_UINT_PACKED_S), - &versionMajor, &versionMinor)); + EXPECT_NO_ERROR(error = + Get(SPINEL_PROP_PROTOCOL_VERSION, (SPINEL_DATATYPE_UINT_PACKED_S SPINEL_DATATYPE_UINT_PACKED_S), + &versionMajor, &versionMinor)); if ((versionMajor != SPINEL_PROTOCOL_VERSION_THREAD_MAJOR) || (versionMinor != SPINEL_PROTOCOL_VERSION_THREAD_MINOR)) @@ -228,7 +226,7 @@ otError RadioSpinel::CheckRadioCapabilities(void) otError error = OT_ERROR_NONE; unsigned int radioCaps; - SuccessOrExit(error = Get(SPINEL_PROP_RADIO_CAPS, SPINEL_DATATYPE_UINT_PACKED_S, &radioCaps)); + EXPECT_NO_ERROR(error = Get(SPINEL_PROP_RADIO_CAPS, SPINEL_DATATYPE_UINT_PACKED_S, &radioCaps)); sRadioCaps = static_cast(radioCaps); if ((sRadioCaps & kRequiredRadioCaps) != kRequiredRadioCaps) @@ -267,7 +265,7 @@ otError RadioSpinel::CheckRcpApiVersion(bool aSupportsRcpApiVersion, bool aSuppo unsigned int rcpApiVersion; - SuccessOrExit(error = Get(SPINEL_PROP_RCP_API_VERSION, SPINEL_DATATYPE_UINT_PACKED_S, &rcpApiVersion)); + EXPECT_NO_ERROR(error = Get(SPINEL_PROP_RCP_API_VERSION, SPINEL_DATATYPE_UINT_PACKED_S, &rcpApiVersion)); if (rcpApiVersion < SPINEL_MIN_HOST_SUPPORTED_RCP_API_VERSION) { @@ -286,7 +284,7 @@ otError RadioSpinel::CheckRcpApiVersion(bool aSupportsRcpApiVersion, bool aSuppo unsigned int minHostRcpApiVersion; - SuccessOrExit( + EXPECT_NO_ERROR( error = Get(SPINEL_PROP_RCP_MIN_HOST_API_VERSION, SPINEL_DATATYPE_UINT_PACKED_S, &minHostRcpApiVersion)); if (SPINEL_RCP_API_VERSION < minHostRcpApiVersion) @@ -322,8 +320,8 @@ void RadioSpinel::HandleNotification(const uint8_t *aFrame, uint16_t aLength, bo unpacked = spinel_datatype_unpack(aFrame, aLength, "CiiD", &header, &cmd, &key, &data, &len); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); - VerifyOrExit(SPINEL_HEADER_GET_TID(header) == 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(SPINEL_HEADER_GET_TID(header) == 0, error = OT_ERROR_PARSE); switch (cmd) { @@ -334,7 +332,7 @@ void RadioSpinel::HandleNotification(const uint8_t *aFrame, uint16_t aLength, bo if (!IsSafeToHandleNow(key)) { - ExitNow(aShouldSaveFrame = true); + EXIT_NOW(aShouldSaveFrame = true); } HandleValueIs(key, data, static_cast(len)); @@ -346,7 +344,7 @@ void RadioSpinel::HandleNotification(const uint8_t *aFrame, uint16_t aLength, bo break; default: - ExitNow(error = OT_ERROR_PARSE); + EXIT_NOW(error = OT_ERROR_PARSE); } exit: @@ -366,9 +364,9 @@ void RadioSpinel::HandleNotification(const uint8_t *aFrame, uint16_t aLength) otError error = OT_ERROR_NONE; unpacked = spinel_datatype_unpack(aFrame, aLength, "CiiD", &header, &cmd, &key, &data, &len); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); - VerifyOrExit(SPINEL_HEADER_GET_TID(header) == 0, error = OT_ERROR_PARSE); - VerifyOrExit(cmd == SPINEL_CMD_PROP_VALUE_IS); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(SPINEL_HEADER_GET_TID(header) == 0, error = OT_ERROR_PARSE); + EXPECT(cmd == SPINEL_CMD_PROP_VALUE_IS, NO_ACTION); HandleValueIs(key, data, static_cast(len)); exit: @@ -387,8 +385,7 @@ void RadioSpinel::HandleResponse(const uint8_t *aBuffer, uint16_t aLength) otError error = OT_ERROR_NONE; rval = spinel_datatype_unpack(aBuffer, aLength, "CiiD", &header, &cmd, &key, &data, &len); - VerifyOrExit(rval > 0 && cmd >= SPINEL_CMD_PROP_VALUE_IS && cmd <= SPINEL_CMD_PROP_VALUE_REMOVED, - error = OT_ERROR_PARSE); + EXPECT(rval > 0 && cmd >= SPINEL_CMD_PROP_VALUE_IS && cmd <= SPINEL_CMD_PROP_VALUE_REMOVED, error = OT_ERROR_PARSE); if (mWaitingTid == SPINEL_HEADER_GET_TID(header)) { @@ -427,7 +424,7 @@ void RadioSpinel::HandleWaitingResponse(uint32_t aCommand, spinel_status_t status; spinel_ssize_t unpacked = spinel_datatype_unpack(aBuffer, aLength, "i", &status); - VerifyOrExit(unpacked > 0, mError = OT_ERROR_PARSE); + EXPECT(unpacked > 0, mError = OT_ERROR_PARSE); mError = SpinelStatusToOtError(status); } #if OPENTHREAD_CONFIG_DIAG_ENABLE @@ -436,10 +433,10 @@ void RadioSpinel::HandleWaitingResponse(uint32_t aCommand, spinel_ssize_t unpacked; mError = OT_ERROR_NONE; - VerifyOrExit(mDiagOutput != nullptr); + EXPECT(mDiagOutput != nullptr, NO_ACTION); unpacked = spinel_datatype_unpack_in_place(aBuffer, aLength, SPINEL_DATATYPE_UTF8_S, mDiagOutput, &mDiagOutputMaxLen); - VerifyOrExit(unpacked > 0, mError = OT_ERROR_PARSE); + EXPECT(unpacked > 0, mError = OT_ERROR_PARSE); } #endif else if (aKey == mWaitingKey) @@ -459,7 +456,7 @@ void RadioSpinel::HandleWaitingResponse(uint32_t aCommand, spinel_ssize_t unpacked = spinel_datatype_vunpack_in_place(aBuffer, aLength, mPropertyFormat, mPropertyArgs); - VerifyOrExit(unpacked > 0, mError = OT_ERROR_PARSE); + EXPECT(unpacked > 0, mError = OT_ERROR_PARSE); mError = OT_ERROR_NONE; } } @@ -492,7 +489,7 @@ void RadioSpinel::HandleValueIs(spinel_prop_key_t aKey, const uint8_t *aBuffer, if (aKey == SPINEL_PROP_STREAM_RAW) { - SuccessOrExit(error = ParseRadioFrame(mRxRadioFrame, aBuffer, aLength, unpacked)); + EXPECT_NO_ERROR(error = ParseRadioFrame(mRxRadioFrame, aBuffer, aLength, unpacked)); RadioReceive(); } else if (aKey == SPINEL_PROP_LAST_STATUS) @@ -500,14 +497,14 @@ void RadioSpinel::HandleValueIs(spinel_prop_key_t aKey, const uint8_t *aBuffer, spinel_status_t status = SPINEL_STATUS_OK; unpacked = spinel_datatype_unpack(aBuffer, aLength, "i", &status); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); if (status >= SPINEL_STATUS_RESET__BEGIN && status <= SPINEL_STATUS_RESET__END) { if (IsEnabled()) { HandleRcpUnexpectedReset(status); - ExitNow(); + EXIT_NOW(); } // this clear is necessary in case the RCP has sent messages between disable and reset @@ -535,7 +532,7 @@ void RadioSpinel::HandleValueIs(spinel_prop_key_t aKey, const uint8_t *aBuffer, unpacked = spinel_datatype_unpack(aBuffer, aLength, "Cc", &scanChannel, &maxRssi); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); #if OPENTHREAD_SPINEL_CONFIG_RCP_RESTORATION_MAX_COUNT > 0 mEnergyScanning = false; @@ -550,7 +547,7 @@ void RadioSpinel::HandleValueIs(spinel_prop_key_t aKey, const uint8_t *aBuffer, unpacked = spinel_datatype_unpack_in_place(aBuffer, aLength, SPINEL_DATATYPE_DATA_S, logStream, &len); assert(len < sizeof(logStream)); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); logStream[len] = '\0'; LogDebg("RCP => %s", logStream); } @@ -560,12 +557,12 @@ void RadioSpinel::HandleValueIs(spinel_prop_key_t aKey, const uint8_t *aBuffer, uint8_t logLevel; unpacked = spinel_datatype_unpack(aBuffer, aLength, SPINEL_DATATYPE_UTF8_S, &logString); - VerifyOrExit(unpacked >= 0, error = OT_ERROR_PARSE); + EXPECT(unpacked >= 0, error = OT_ERROR_PARSE); aBuffer += unpacked; aLength -= unpacked; unpacked = spinel_datatype_unpack(aBuffer, aLength, SPINEL_DATATYPE_UINT8_S, &logLevel); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); switch (logLevel) { @@ -627,7 +624,7 @@ otError RadioSpinel::SendReset(uint8_t aResetType) if ((aResetType == SPINEL_RESET_BOOTLOADER) && !sSupportsResetToBootloader) { - ExitNow(error = OT_ERROR_NOT_CAPABLE); + EXIT_NOW(error = OT_ERROR_NOT_CAPABLE); } error = GetSpinelDriver().SendReset(aResetType); @@ -647,7 +644,7 @@ otError RadioSpinel::ParseRadioFrame(otRadioFrame &aFrame, unsigned int receiveError = 0; spinel_ssize_t unpacked; - VerifyOrExit(aLength > 0, aFrame.mLength = 0); + EXPECT(aLength > 0, aFrame.mLength = 0); unpacked = spinel_datatype_unpack_in_place(aBuffer, aLength, SPINEL_DATATYPE_DATA_WLEN_S // Frame @@ -665,7 +662,7 @@ otError RadioSpinel::ParseRadioFrame(otRadioFrame &aFrame, &aFrame.mChannel, &aFrame.mInfo.mRxInfo.mLqi, &aFrame.mInfo.mRxInfo.mTimestamp, &receiveError); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); aUnpacked = unpacked; aBuffer += unpacked; @@ -681,7 +678,7 @@ otError RadioSpinel::ParseRadioFrame(otRadioFrame &aFrame, ), &aFrame.mInfo.mRxInfo.mAckKeyId, &aFrame.mInfo.mRxInfo.mAckFrameCounter); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); aUnpacked += unpacked; #if OPENTHREAD_SPINEL_CONFIG_RCP_RESTORATION_MAX_COUNT > 0 @@ -723,7 +720,7 @@ void RadioSpinel::RadioReceive(void) { case kStateDisabled: case kStateSleep: - ExitNow(); + EXIT_NOW(); case kStateReceive: case kStateTransmitting: @@ -791,7 +788,7 @@ otError RadioSpinel::SetPromiscuous(bool aEnable) otError error; uint8_t mode = (aEnable ? SPINEL_MAC_PROMISCUOUS_MODE_NETWORK : SPINEL_MAC_PROMISCUOUS_MODE_OFF); - SuccessOrExit(error = Set(SPINEL_PROP_MAC_PROMISCUOUS_MODE, SPINEL_DATATYPE_UINT8_S, mode)); + EXPECT_NO_ERROR(error = Set(SPINEL_PROP_MAC_PROMISCUOUS_MODE, SPINEL_DATATYPE_UINT8_S, mode)); mIsPromiscuous = aEnable; exit: @@ -802,8 +799,8 @@ otError RadioSpinel::SetRxOnWhenIdle(bool aEnable) { otError error = OT_ERROR_NONE; - VerifyOrExit(mRxOnWhenIdle != aEnable); - SuccessOrExit(error = Set(SPINEL_PROP_MAC_RX_ON_WHEN_IDLE_MODE, SPINEL_DATATYPE_BOOL_S, aEnable)); + EXPECT(mRxOnWhenIdle != aEnable, NO_ACTION); + EXPECT_NO_ERROR(error = Set(SPINEL_PROP_MAC_RX_ON_WHEN_IDLE_MODE, SPINEL_DATATYPE_BOOL_S, aEnable)); mRxOnWhenIdle = aEnable; exit: @@ -814,8 +811,8 @@ otError RadioSpinel::SetShortAddress(uint16_t aAddress) { otError error = OT_ERROR_NONE; - VerifyOrExit(mShortAddress != aAddress); - SuccessOrExit(error = Set(SPINEL_PROP_MAC_15_4_SADDR, SPINEL_DATATYPE_UINT16_S, aAddress)); + EXPECT(mShortAddress != aAddress, NO_ACTION); + EXPECT_NO_ERROR(error = Set(SPINEL_PROP_MAC_15_4_SADDR, SPINEL_DATATYPE_UINT16_S, aAddress)); mShortAddress = aAddress; exit: @@ -829,8 +826,8 @@ otError RadioSpinel::ReadMacKey(const otMacKeyMaterial &aKeyMaterial, otMacKey & size_t keySize; otError error = otPlatCryptoExportKey(aKeyMaterial.mKeyMaterial.mKeyRef, aKey.m8, sizeof(aKey), &keySize); - SuccessOrExit(error); - VerifyOrExit(keySize == sizeof(otMacKey), error = OT_ERROR_FAILED); + EXPECT_NO_ERROR(error); + EXPECT(keySize == sizeof(otMacKey), error = OT_ERROR_FAILED); exit: return error; @@ -847,9 +844,9 @@ otError RadioSpinel::SetMacKey(uint8_t aKeyIdMode, otMacKey currKey; otMacKey nextKey; - SuccessOrExit(error = ReadMacKey(*aPrevKey, prevKey)); - SuccessOrExit(error = ReadMacKey(*aCurrKey, currKey)); - SuccessOrExit(error = ReadMacKey(*aNextKey, nextKey)); + EXPECT_NO_ERROR(error = ReadMacKey(*aPrevKey, prevKey)); + EXPECT_NO_ERROR(error = ReadMacKey(*aCurrKey, currKey)); + EXPECT_NO_ERROR(error = ReadMacKey(*aNextKey, nextKey)); error = SetMacKey(aKeyIdMode, aKeyId, prevKey, currKey, nextKey); exit: @@ -878,11 +875,11 @@ otError RadioSpinel::SetMacKey(uint8_t aKeyIdMode, { otError error; - SuccessOrExit(error = Set(SPINEL_PROP_RCP_MAC_KEY, - SPINEL_DATATYPE_UINT8_S SPINEL_DATATYPE_UINT8_S SPINEL_DATATYPE_DATA_WLEN_S - SPINEL_DATATYPE_DATA_WLEN_S SPINEL_DATATYPE_DATA_WLEN_S, - aKeyIdMode, aKeyId, aPrevKey.m8, sizeof(aPrevKey), aCurrKey.m8, sizeof(aCurrKey), - aNextKey.m8, sizeof(aNextKey))); + EXPECT_NO_ERROR(error = Set(SPINEL_PROP_RCP_MAC_KEY, + SPINEL_DATATYPE_UINT8_S SPINEL_DATATYPE_UINT8_S SPINEL_DATATYPE_DATA_WLEN_S + SPINEL_DATATYPE_DATA_WLEN_S SPINEL_DATATYPE_DATA_WLEN_S, + aKeyIdMode, aKeyId, aPrevKey.m8, sizeof(aPrevKey), aCurrKey.m8, sizeof(aCurrKey), + aNextKey.m8, sizeof(aNextKey))); #if OPENTHREAD_SPINEL_CONFIG_RCP_RESTORATION_MAX_COUNT > 0 mKeyIdMode = aKeyIdMode; @@ -903,8 +900,8 @@ otError RadioSpinel::SetMacFrameCounter(uint32_t aMacFrameCounter, bool aSetIfLa { otError error; - SuccessOrExit(error = Set(SPINEL_PROP_RCP_MAC_FRAME_COUNTER, SPINEL_DATATYPE_UINT32_S SPINEL_DATATYPE_BOOL_S, - aMacFrameCounter, aSetIfLarger)); + EXPECT_NO_ERROR(error = Set(SPINEL_PROP_RCP_MAC_FRAME_COUNTER, SPINEL_DATATYPE_UINT32_S SPINEL_DATATYPE_BOOL_S, + aMacFrameCounter, aSetIfLarger)); #if OPENTHREAD_SPINEL_CONFIG_RCP_RESTORATION_MAX_COUNT > 0 mMacFrameCounterSet = true; mMacFrameCounter = aMacFrameCounter; @@ -925,7 +922,7 @@ otError RadioSpinel::SetExtendedAddress(const otExtAddress &aExtAddress) { otError error; - SuccessOrExit(error = Set(SPINEL_PROP_MAC_15_4_LADDR, SPINEL_DATATYPE_EUI64_S, aExtAddress.m8)); + EXPECT_NO_ERROR(error = Set(SPINEL_PROP_MAC_15_4_LADDR, SPINEL_DATATYPE_EUI64_S, aExtAddress.m8)); mExtendedAddress = aExtAddress; exit: @@ -936,8 +933,8 @@ otError RadioSpinel::SetPanId(uint16_t aPanId) { otError error = OT_ERROR_NONE; - VerifyOrExit(mPanId != aPanId); - SuccessOrExit(error = Set(SPINEL_PROP_MAC_15_4_PANID, SPINEL_DATATYPE_UINT16_S, aPanId)); + EXPECT(mPanId != aPanId, NO_ACTION); + EXPECT_NO_ERROR(error = Set(SPINEL_PROP_MAC_15_4_PANID, SPINEL_DATATYPE_UINT16_S, aPanId)); mPanId = aPanId; exit: @@ -948,7 +945,7 @@ otError RadioSpinel::EnableSrcMatch(bool aEnable) { otError error; - SuccessOrExit(error = Set(SPINEL_PROP_MAC_SRC_MATCH_ENABLED, SPINEL_DATATYPE_BOOL_S, aEnable)); + EXPECT_NO_ERROR(error = Set(SPINEL_PROP_MAC_SRC_MATCH_ENABLED, SPINEL_DATATYPE_BOOL_S, aEnable)); #if OPENTHREAD_SPINEL_CONFIG_RCP_RESTORATION_MAX_COUNT > 0 mSrcMatchSet = true; @@ -963,7 +960,7 @@ otError RadioSpinel::AddSrcMatchShortEntry(uint16_t aShortAddress) { otError error; - SuccessOrExit(error = Insert(SPINEL_PROP_MAC_SRC_MATCH_SHORT_ADDRESSES, SPINEL_DATATYPE_UINT16_S, aShortAddress)); + EXPECT_NO_ERROR(error = Insert(SPINEL_PROP_MAC_SRC_MATCH_SHORT_ADDRESSES, SPINEL_DATATYPE_UINT16_S, aShortAddress)); #if OPENTHREAD_SPINEL_CONFIG_RCP_RESTORATION_MAX_COUNT > 0 assert(mSrcMatchShortEntryCount < OPENTHREAD_CONFIG_MLE_MAX_CHILDREN); @@ -972,7 +969,7 @@ otError RadioSpinel::AddSrcMatchShortEntry(uint16_t aShortAddress) { if (mSrcMatchShortEntries[i] == aShortAddress) { - ExitNow(); + EXIT_NOW(); } } mSrcMatchShortEntries[mSrcMatchShortEntryCount] = aShortAddress; @@ -987,8 +984,8 @@ otError RadioSpinel::AddSrcMatchExtEntry(const otExtAddress &aExtAddress) { otError error; - SuccessOrExit(error = - Insert(SPINEL_PROP_MAC_SRC_MATCH_EXTENDED_ADDRESSES, SPINEL_DATATYPE_EUI64_S, aExtAddress.m8)); + EXPECT_NO_ERROR(error = + Insert(SPINEL_PROP_MAC_SRC_MATCH_EXTENDED_ADDRESSES, SPINEL_DATATYPE_EUI64_S, aExtAddress.m8)); #if OPENTHREAD_SPINEL_CONFIG_RCP_RESTORATION_MAX_COUNT > 0 assert(mSrcMatchExtEntryCount < OPENTHREAD_CONFIG_MLE_MAX_CHILDREN); @@ -997,7 +994,7 @@ otError RadioSpinel::AddSrcMatchExtEntry(const otExtAddress &aExtAddress) { if (memcmp(aExtAddress.m8, mSrcMatchExtEntries[i].m8, OT_EXT_ADDRESS_SIZE) == 0) { - ExitNow(); + EXIT_NOW(); } } mSrcMatchExtEntries[mSrcMatchExtEntryCount] = aExtAddress; @@ -1012,7 +1009,7 @@ otError RadioSpinel::ClearSrcMatchShortEntry(uint16_t aShortAddress) { otError error; - SuccessOrExit(error = Remove(SPINEL_PROP_MAC_SRC_MATCH_SHORT_ADDRESSES, SPINEL_DATATYPE_UINT16_S, aShortAddress)); + EXPECT_NO_ERROR(error = Remove(SPINEL_PROP_MAC_SRC_MATCH_SHORT_ADDRESSES, SPINEL_DATATYPE_UINT16_S, aShortAddress)); #if OPENTHREAD_SPINEL_CONFIG_RCP_RESTORATION_MAX_COUNT > 0 for (int i = 0; i < mSrcMatchShortEntryCount; ++i) @@ -1034,8 +1031,8 @@ otError RadioSpinel::ClearSrcMatchExtEntry(const otExtAddress &aExtAddress) { otError error; - SuccessOrExit(error = - Remove(SPINEL_PROP_MAC_SRC_MATCH_EXTENDED_ADDRESSES, SPINEL_DATATYPE_EUI64_S, aExtAddress.m8)); + EXPECT_NO_ERROR(error = + Remove(SPINEL_PROP_MAC_SRC_MATCH_EXTENDED_ADDRESSES, SPINEL_DATATYPE_EUI64_S, aExtAddress.m8)); #if OPENTHREAD_SPINEL_CONFIG_RCP_RESTORATION_MAX_COUNT > 0 for (int i = 0; i < mSrcMatchExtEntryCount; ++i) @@ -1057,7 +1054,7 @@ otError RadioSpinel::ClearSrcMatchShortEntries(void) { otError error; - SuccessOrExit(error = Set(SPINEL_PROP_MAC_SRC_MATCH_SHORT_ADDRESSES, nullptr)); + EXPECT_NO_ERROR(error = Set(SPINEL_PROP_MAC_SRC_MATCH_SHORT_ADDRESSES, nullptr)); #if OPENTHREAD_SPINEL_CONFIG_RCP_RESTORATION_MAX_COUNT > 0 mSrcMatchShortEntryCount = 0; @@ -1071,7 +1068,7 @@ otError RadioSpinel::ClearSrcMatchExtEntries(void) { otError error; - SuccessOrExit(error = Set(SPINEL_PROP_MAC_SRC_MATCH_EXTENDED_ADDRESSES, nullptr)); + EXPECT_NO_ERROR(error = Set(SPINEL_PROP_MAC_SRC_MATCH_EXTENDED_ADDRESSES, nullptr)); #if OPENTHREAD_SPINEL_CONFIG_RCP_RESTORATION_MAX_COUNT > 0 mSrcMatchExtEntryCount = 0; @@ -1119,7 +1116,7 @@ otError RadioSpinel::SetCoexEnabled(bool aEnabled) { otError error; - SuccessOrExit(error = Set(SPINEL_PROP_RADIO_COEX_ENABLE, SPINEL_DATATYPE_BOOL_S, aEnabled)); + EXPECT_NO_ERROR(error = Set(SPINEL_PROP_RADIO_COEX_ENABLE, SPINEL_DATATYPE_BOOL_S, aEnabled)); #if OPENTHREAD_SPINEL_CONFIG_RCP_RESTORATION_MAX_COUNT > 0 mCoexEnabled = aEnabled; @@ -1183,7 +1180,7 @@ otError RadioSpinel::SetTransmitPower(int8_t aPower) { otError error; - SuccessOrExit(error = Set(SPINEL_PROP_PHY_TX_POWER, SPINEL_DATATYPE_INT8_S, aPower)); + EXPECT_NO_ERROR(error = Set(SPINEL_PROP_PHY_TX_POWER, SPINEL_DATATYPE_INT8_S, aPower)); #if OPENTHREAD_SPINEL_CONFIG_RCP_RESTORATION_MAX_COUNT > 0 mTransmitPower = aPower; @@ -1199,7 +1196,7 @@ otError RadioSpinel::SetCcaEnergyDetectThreshold(int8_t aThreshold) { otError error; - SuccessOrExit(error = Set(SPINEL_PROP_PHY_CCA_THRESHOLD, SPINEL_DATATYPE_INT8_S, aThreshold)); + EXPECT_NO_ERROR(error = Set(SPINEL_PROP_PHY_CCA_THRESHOLD, SPINEL_DATATYPE_INT8_S, aThreshold)); #if OPENTHREAD_SPINEL_CONFIG_RCP_RESTORATION_MAX_COUNT > 0 mCcaEnergyDetectThreshold = aThreshold; @@ -1215,7 +1212,7 @@ otError RadioSpinel::SetFemLnaGain(int8_t aGain) { otError error; - SuccessOrExit(error = Set(SPINEL_PROP_PHY_FEM_LNA_GAIN, SPINEL_DATATYPE_INT8_S, aGain)); + EXPECT_NO_ERROR(error = Set(SPINEL_PROP_PHY_FEM_LNA_GAIN, SPINEL_DATATYPE_INT8_S, aGain)); #if OPENTHREAD_SPINEL_CONFIG_RCP_RESTORATION_MAX_COUNT > 0 mFemLnaGain = aGain; @@ -1231,7 +1228,7 @@ otError RadioSpinel::EnergyScan(uint8_t aScanChannel, uint16_t aScanDuration) { otError error; - VerifyOrExit(sRadioCaps & OT_RADIO_CAPS_ENERGY_SCAN, error = OT_ERROR_NOT_CAPABLE); + EXPECT(sRadioCaps & OT_RADIO_CAPS_ENERGY_SCAN, error = OT_ERROR_NOT_CAPABLE); #if OPENTHREAD_SPINEL_CONFIG_RCP_RESTORATION_MAX_COUNT > 0 mScanChannel = aScanChannel; @@ -1239,9 +1236,9 @@ otError RadioSpinel::EnergyScan(uint8_t aScanChannel, uint16_t aScanDuration) mEnergyScanning = true; #endif - SuccessOrExit(error = Set(SPINEL_PROP_MAC_SCAN_MASK, SPINEL_DATATYPE_DATA_S, &aScanChannel, sizeof(uint8_t))); - SuccessOrExit(error = Set(SPINEL_PROP_MAC_SCAN_PERIOD, SPINEL_DATATYPE_UINT16_S, aScanDuration)); - SuccessOrExit(error = Set(SPINEL_PROP_MAC_SCAN_STATE, SPINEL_DATATYPE_UINT8_S, SPINEL_SCAN_STATE_ENERGY)); + EXPECT_NO_ERROR(error = Set(SPINEL_PROP_MAC_SCAN_MASK, SPINEL_DATATYPE_DATA_S, &aScanChannel, sizeof(uint8_t))); + EXPECT_NO_ERROR(error = Set(SPINEL_PROP_MAC_SCAN_PERIOD, SPINEL_DATATYPE_UINT16_S, aScanDuration)); + EXPECT_NO_ERROR(error = Set(SPINEL_PROP_MAC_SCAN_STATE, SPINEL_DATATYPE_UINT8_S, SPINEL_SCAN_STATE_ENERGY)); mChannel = aScanChannel; @@ -1381,7 +1378,7 @@ otError RadioSpinel::WaitResponse(bool aHandleRcpTimeout) { HandleRcpTimeout(); } - ExitNow(mError = OT_ERROR_RESPONSE_TIMEOUT); + EXIT_NOW(mError = OT_ERROR_RESPONSE_TIMEOUT); } } while (mWaitingTid); @@ -1406,7 +1403,7 @@ spinel_tid_t RadioSpinel::GetNextTid(void) // We looped back to `mCmdNextTid` indicating that all // TIDs are in-use. - ExitNow(tid = 0); + EXIT_NOW(tid = 0); } } @@ -1422,16 +1419,16 @@ otError RadioSpinel::RequestV(uint32_t command, spinel_prop_key_t aKey, const ch otError error = OT_ERROR_NONE; spinel_tid_t tid = GetNextTid(); - VerifyOrExit(tid > 0, error = OT_ERROR_BUSY); + EXPECT(tid > 0, error = OT_ERROR_BUSY); error = GetSpinelDriver().SendCommand(command, aKey, tid, aFormat, aArgs); - SuccessOrExit(error); + EXPECT_NO_ERROR(error); if (aKey == SPINEL_PROP_STREAM_RAW) { // not allowed to send another frame before the last frame is done. assert(mTxRadioTid == 0); - VerifyOrExit(mTxRadioTid == 0, error = OT_ERROR_BUSY); + EXPECT(mTxRadioTid == 0, error = OT_ERROR_BUSY); mTxRadioTid = tid; } else @@ -1511,29 +1508,29 @@ void RadioSpinel::HandleTransmitDone(uint32_t aCommand, bool headerUpdated = false; spinel_ssize_t unpacked; - VerifyOrExit(aCommand == SPINEL_CMD_PROP_VALUE_IS && aKey == SPINEL_PROP_LAST_STATUS, error = OT_ERROR_FAILED); + EXPECT(aCommand == SPINEL_CMD_PROP_VALUE_IS && aKey == SPINEL_PROP_LAST_STATUS, error = OT_ERROR_FAILED); unpacked = spinel_datatype_unpack(aBuffer, aLength, SPINEL_DATATYPE_UINT_PACKED_S, &status); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); aBuffer += unpacked; aLength -= static_cast(unpacked); unpacked = spinel_datatype_unpack(aBuffer, aLength, SPINEL_DATATYPE_BOOL_S, &framePending); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); aBuffer += unpacked; aLength -= static_cast(unpacked); unpacked = spinel_datatype_unpack(aBuffer, aLength, SPINEL_DATATYPE_BOOL_S, &headerUpdated); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); aBuffer += unpacked; aLength -= static_cast(unpacked); if (status == SPINEL_STATUS_OK) { - SuccessOrExit(error = ParseRadioFrame(mAckRadioFrame, aBuffer, aLength, unpacked)); + EXPECT_NO_ERROR(error = ParseRadioFrame(mAckRadioFrame, aBuffer, aLength, unpacked)); aBuffer += unpacked; aLength -= static_cast(unpacked); } @@ -1553,7 +1550,7 @@ void RadioSpinel::HandleTransmitDone(uint32_t aCommand, // Replace transmit frame security key index and frame counter with the one filled by RCP unpacked = spinel_datatype_unpack(aBuffer, aLength, SPINEL_DATATYPE_UINT8_S SPINEL_DATATYPE_UINT32_S, &keyId, &frameCounter); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); static_cast(mTransmitFrame)->SetKeyId(keyId); static_cast(mTransmitFrame)->SetFrameCounter(frameCounter); @@ -1584,7 +1581,7 @@ otError RadioSpinel::Transmit(otRadioFrame &aFrame) { otError error = OT_ERROR_INVALID_STATE; - VerifyOrExit(mState == kStateReceive || (mState == kStateSleep && (sRadioCaps & OT_RADIO_CAPS_SLEEP_TO_TX))); + EXPECT(mState == kStateReceive || (mState == kStateSleep && (sRadioCaps & OT_RADIO_CAPS_SLEEP_TO_TX)), NO_ACTION); mTransmitFrame = &aFrame; @@ -1663,19 +1660,19 @@ otError RadioSpinel::Receive(uint8_t aChannel) { otError error = OT_ERROR_NONE; - VerifyOrExit(mState != kStateDisabled, error = OT_ERROR_INVALID_STATE); + EXPECT(mState != kStateDisabled, error = OT_ERROR_INVALID_STATE); if (mChannel != aChannel) { error = Set(SPINEL_PROP_PHY_CHAN, SPINEL_DATATYPE_UINT8_S, aChannel); - SuccessOrExit(error); + EXPECT_NO_ERROR(error); mChannel = aChannel; } if (mState == kStateSleep) { error = Set(SPINEL_PROP_MAC_RAW_STREAM_ENABLED, SPINEL_DATATYPE_BOOL_S, true); - SuccessOrExit(error); + EXPECT_NO_ERROR(error); } if (mTxRadioTid != 0) @@ -1698,7 +1695,7 @@ otError RadioSpinel::Sleep(void) { case kStateReceive: error = Set(SPINEL_PROP_MAC_RAW_STREAM_ENABLED, SPINEL_DATATYPE_BOOL_S, false); - SuccessOrExit(error); + EXPECT_NO_ERROR(error); mState = kStateSleep; break; @@ -1719,14 +1716,14 @@ otError RadioSpinel::Enable(otInstance *aInstance) { otError error = OT_ERROR_NONE; - VerifyOrExit(!IsEnabled()); + EXPECT(!IsEnabled(), NO_ACTION); mInstance = aInstance; - SuccessOrExit(error = Set(SPINEL_PROP_PHY_ENABLED, SPINEL_DATATYPE_BOOL_S, true)); - SuccessOrExit(error = Set(SPINEL_PROP_MAC_15_4_PANID, SPINEL_DATATYPE_UINT16_S, mPanId)); - SuccessOrExit(error = Set(SPINEL_PROP_MAC_15_4_SADDR, SPINEL_DATATYPE_UINT16_S, mShortAddress)); - SuccessOrExit(error = Get(SPINEL_PROP_PHY_RX_SENSITIVITY, SPINEL_DATATYPE_INT8_S, &mRxSensitivity)); + EXPECT_NO_ERROR(error = Set(SPINEL_PROP_PHY_ENABLED, SPINEL_DATATYPE_BOOL_S, true)); + EXPECT_NO_ERROR(error = Set(SPINEL_PROP_MAC_15_4_PANID, SPINEL_DATATYPE_UINT16_S, mPanId)); + EXPECT_NO_ERROR(error = Set(SPINEL_PROP_MAC_15_4_SADDR, SPINEL_DATATYPE_UINT16_S, mShortAddress)); + EXPECT_NO_ERROR(error = Get(SPINEL_PROP_PHY_RX_SENSITIVITY, SPINEL_DATATYPE_INT8_S, &mRxSensitivity)); mState = kStateSleep; @@ -1744,8 +1741,8 @@ otError RadioSpinel::Disable(void) { otError error = OT_ERROR_NONE; - VerifyOrExit(IsEnabled()); - VerifyOrExit(mState == kStateSleep, error = OT_ERROR_INVALID_STATE); + EXPECT(IsEnabled(), NO_ACTION); + EXPECT(mState == kStateSleep, error = OT_ERROR_INVALID_STATE); SuccessOrDie(Set(SPINEL_PROP_PHY_ENABLED, SPINEL_DATATYPE_BOOL_S, false)); mState = kStateDisabled; @@ -1789,8 +1786,8 @@ uint32_t RadioSpinel::GetRadioChannelMask(bool aPreferred) spinel_ssize_t unpacked; unpacked = spinel_datatype_unpack(maskData, maskLength, SPINEL_DATATYPE_UINT8_S, &channel); - VerifyOrExit(unpacked > 0, error = OT_ERROR_FAILED); - VerifyOrExit(channel < kChannelMaskBufferSize, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_FAILED); + EXPECT(channel < kChannelMaskBufferSize, error = OT_ERROR_PARSE); channelMask |= (1UL << channel); maskData += unpacked; @@ -1850,12 +1847,12 @@ void RadioSpinel::CalcRcpTimeOffset(void) * D = T1' - ((T0 + T2)/ 2) */ - VerifyOrExit(!mIsTimeSynced || (otPlatTimeGet() >= GetNextRadioTimeRecalcStart())); + EXPECT(!mIsTimeSynced || (otPlatTimeGet() >= GetNextRadioTimeRecalcStart()), NO_ACTION); LogDebg("Trying to get RCP time offset"); packed = spinel_datatype_pack(buffer, sizeof(buffer), SPINEL_DATATYPE_UINT64_S, remoteTimestamp); - VerifyOrExit(packed > 0 && static_cast(packed) <= sizeof(buffer), error = OT_ERROR_NO_BUFS); + EXPECT(packed > 0 && static_cast(packed) <= sizeof(buffer), error = OT_ERROR_NO_BUFS); localTxTimestamp = otPlatTimeGet(); @@ -1865,7 +1862,7 @@ void RadioSpinel::CalcRcpTimeOffset(void) localRxTimestamp = otPlatTimeGet(); - VerifyOrExit(error == OT_ERROR_NONE, mRadioTimeRecalcStart = localRxTimestamp); + EXPECT(error == OT_ERROR_NONE, mRadioTimeRecalcStart = localRxTimestamp); mRadioTimeOffset = (remoteTimestamp - ((localRxTimestamp / 2) + (localTxTimestamp / 2))); mIsTimeSynced = true; @@ -1921,7 +1918,7 @@ void RadioSpinel::RecoverFromRcpFailure(void) if (mRcpFailure == kRcpFailureNone) { - ExitNow(); + EXIT_NOW(); } #if OPENTHREAD_CONFIG_MULTIPAN_RCP_ENABLE @@ -1976,7 +1973,7 @@ void RadioSpinel::RecoverFromRcpFailure(void) case kStateReceive: #if OPENTHREAD_CONFIG_MULTIPAN_RCP_ENABLE // In case multiple PANs are running, don't force RCP to receive state. - IgnoreError(Set(SPINEL_PROP_MAC_RAW_STREAM_ENABLED, SPINEL_DATATYPE_BOOL_S, true)); + IGNORE_RETURN(Set(SPINEL_PROP_MAC_RAW_STREAM_ENABLED, SPINEL_DATATYPE_BOOL_S, true)); #else SuccessOrDie(Set(SPINEL_PROP_MAC_RAW_STREAM_ENABLED, SPINEL_DATATYPE_BOOL_S, true)); #endif @@ -1986,7 +1983,7 @@ void RadioSpinel::RecoverFromRcpFailure(void) case kStateTransmitDone: #if OPENTHREAD_CONFIG_MULTIPAN_RCP_ENABLE // In case multiple PANs are running, don't force RCP to receive state. - IgnoreError(Set(SPINEL_PROP_MAC_RAW_STREAM_ENABLED, SPINEL_DATATYPE_BOOL_S, true)); + IGNORE_RETURN(Set(SPINEL_PROP_MAC_RAW_STREAM_ENABLED, SPINEL_DATATYPE_BOOL_S, true)); #else SuccessOrDie(Set(SPINEL_PROP_MAC_RAW_STREAM_ENABLED, SPINEL_DATATYPE_BOOL_S, true)); #endif @@ -2052,7 +2049,7 @@ void RadioSpinel::RestoreProperties(void) SuccessOrDie(Set(SPINEL_PROP_MAC_15_4_LADDR, SPINEL_DATATYPE_EUI64_S, mExtendedAddress.m8)); #if OPENTHREAD_CONFIG_MULTIPAN_RCP_ENABLE // In case multiple PANs are running, don't force RCP to change channel. - IgnoreError(Set(SPINEL_PROP_PHY_CHAN, SPINEL_DATATYPE_UINT8_S, mChannel)); + IGNORE_RETURN(Set(SPINEL_PROP_PHY_CHAN, SPINEL_DATATYPE_UINT8_S, mChannel)); #else SuccessOrDie(Set(SPINEL_PROP_PHY_CHAN, SPINEL_DATATYPE_UINT8_S, mChannel)); #endif @@ -2167,7 +2164,7 @@ otError RadioSpinel::SetMultipanActiveInterface(spinel_iid_t aIid, bool aComplet otError error; uint8_t value; - VerifyOrExit(aIid == (aIid & SPINEL_MULTIPAN_INTERFACE_ID_MASK), error = OT_ERROR_INVALID_ARGS); + EXPECT(aIid == (aIid & SPINEL_MULTIPAN_INTERFACE_ID_MASK), error = OT_ERROR_INVALID_ARGS); value = static_cast(aIid); if (aCompletePending) @@ -2184,7 +2181,7 @@ exit: otError RadioSpinel::SetChannelMaxTransmitPower(uint8_t aChannel, int8_t aMaxPower) { otError error = OT_ERROR_NONE; - VerifyOrExit(aChannel >= Radio::kChannelMin && aChannel <= Radio::kChannelMax, error = OT_ERROR_INVALID_ARGS); + EXPECT(aChannel >= Radio::kChannelMin && aChannel <= Radio::kChannelMax, error = OT_ERROR_INVALID_ARGS); mMaxPowerTable.SetTransmitPower(aChannel, aMaxPower); error = Set(SPINEL_PROP_PHY_CHAN_MAX_POWER, SPINEL_DATATYPE_UINT8_S SPINEL_DATATYPE_INT8_S, aChannel, aMaxPower); @@ -2216,7 +2213,7 @@ otError RadioSpinel::GetRadioRegion(uint16_t *aRegionCode) { otError error = OT_ERROR_NONE; - VerifyOrExit(aRegionCode != nullptr, error = OT_ERROR_INVALID_ARGS); + EXPECT(aRegionCode != nullptr, error = OT_ERROR_INVALID_ARGS); error = Get(SPINEL_PROP_PHY_REGION_CODE, SPINEL_DATATYPE_UINT16_S, aRegionCode); exit: @@ -2290,9 +2287,9 @@ otError RadioSpinel::AddCalibratedPower(uint8_t aChannel, otError error; assert(aRawPowerSetting != nullptr); - SuccessOrExit(error = Insert(SPINEL_PROP_PHY_CALIBRATED_POWER, - SPINEL_DATATYPE_UINT8_S SPINEL_DATATYPE_INT16_S SPINEL_DATATYPE_DATA_WLEN_S, aChannel, - aActualPower, aRawPowerSetting, aRawPowerSettingLength)); + EXPECT_NO_ERROR(error = Insert(SPINEL_PROP_PHY_CALIBRATED_POWER, + SPINEL_DATATYPE_UINT8_S SPINEL_DATATYPE_INT16_S SPINEL_DATATYPE_DATA_WLEN_S, + aChannel, aActualPower, aRawPowerSetting, aRawPowerSettingLength)); exit: return error; @@ -2303,7 +2300,7 @@ otError RadioSpinel::ClearCalibratedPowers(void) { return Set(SPINEL_PROP_PHY_CA otError RadioSpinel::SetChannelTargetPower(uint8_t aChannel, int16_t aTargetPower) { otError error = OT_ERROR_NONE; - VerifyOrExit(aChannel >= Radio::kChannelMin && aChannel <= Radio::kChannelMax, error = OT_ERROR_INVALID_ARGS); + EXPECT(aChannel >= Radio::kChannelMin && aChannel <= Radio::kChannelMax, error = OT_ERROR_INVALID_ARGS); error = Set(SPINEL_PROP_PHY_CHAN_TARGET_POWER, SPINEL_DATATYPE_UINT8_S SPINEL_DATATYPE_INT16_S, aChannel, aTargetPower); diff --git a/src/lib/spinel/spi_frame.hpp b/src/lib/spinel/spi_frame.hpp index bb5403040..72578ae93 100644 --- a/src/lib/spinel/spi_frame.hpp +++ b/src/lib/spinel/spi_frame.hpp @@ -35,8 +35,6 @@ #include -#include "common/encoding.hpp" - namespace ot { namespace Spinel { @@ -235,6 +233,20 @@ private: kFlagPatternMask = 0x03, // Flag byte PATTERN mask. }; + class LittleEndian + { + public: + static uint16_t ReadUint16(const uint8_t *aBuffer) + { + return static_cast((aBuffer[0] << 8) | aBuffer[1]); + } + static void WriteUint16(uint16_t aValue, uint8_t *aBuffer) + { + aBuffer[0] = (aValue >> 8) & 0xff; + aBuffer[1] = (aValue >> 0) & 0xff; + } + }; + uint8_t *mBuffer; }; diff --git a/src/lib/spinel/spinel-config.h b/src/lib/spinel/spinel-config.h new file mode 100644 index 000000000..253b6e916 --- /dev/null +++ b/src/lib/spinel/spinel-config.h @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2024, The OpenThread Authors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @file + * This file includes compile-time configuration constants for lib spinel. + */ + +#ifndef SPINEL_CONFIG_H_ +#define SPINEL_CONFIG_H_ + +/** + * @def OPENTHREAD_LIB_SPINEL_RX_FRAME_BUFFER_SIZE + * + * Specifies the rx frame buffer size used by `SpinelInterface` in RCP host (posix) code. This is applicable/used when + * `RadioSpinel` platform is used. + * + */ +#ifndef OPENTHREAD_LIB_SPINEL_RX_FRAME_BUFFER_SIZE +#define OPENTHREAD_LIB_SPINEL_RX_FRAME_BUFFER_SIZE 8192 +#endif + +/** + * @def OPENTHREAD_LIB_SPINEL_LOG_MAX_SIZE + * + * The maximum log string size (number of chars). + * + */ +#ifndef OPENTHREAD_LIB_SPINEL_LOG_MAX_SIZE +#define OPENTHREAD_LIB_SPINEL_LOG_MAX_SIZE 1024 +#endif + +/** + * @def OPENTHREAD_LIB_SPINEL_NCP_LOG_MAX_SIZE + * + * The maximum OpenThread log string size (number of chars) supported by NCP using Spinel `StreamWrite`. + * + */ +#ifndef OPENTHREAD_LIB_SPINEL_NCP_LOG_MAX_SIZE +#define OPENTHREAD_LIB_SPINEL_NCP_LOG_MAX_SIZE 150 +#endif + +#endif // SPINEL_CONFIG_H_ diff --git a/src/lib/spinel/spinel_buffer.cpp b/src/lib/spinel/spinel_buffer.cpp index d4c927562..3c41684f9 100644 --- a/src/lib/spinel/spinel_buffer.cpp +++ b/src/lib/spinel/spinel_buffer.cpp @@ -32,8 +32,9 @@ #include "spinel_buffer.hpp" -#include "common/code_utils.hpp" -#include "common/debug.hpp" +#include + +#include "lib/utils/utils.hpp" namespace ot { namespace Spinel { @@ -152,7 +153,7 @@ uint8_t *Buffer::GetUpdatedBufPtr(uint8_t *aBufPtr, uint16_t aOffset, Direction break; case kUnknown: - OT_ASSERT(false); + assert(false); OT_UNREACHABLE_CODE(break); } @@ -195,7 +196,7 @@ uint16_t Buffer::GetDistance(const uint8_t *aStartPtr, const uint8_t *aEndPtr, D break; case kUnknown: - OT_ASSERT(false); + assert(false); OT_UNREACHABLE_CODE(break); } @@ -226,7 +227,7 @@ otError Buffer::InFrameAppend(uint8_t aByte) otError error = OT_ERROR_NONE; uint8_t *newTail; - OT_ASSERT(mWriteDirection != kUnknown); + assert(mWriteDirection != kUnknown); newTail = GetUpdatedBufPtr(mWriteSegmentTail, 1, mWriteDirection); @@ -252,7 +253,7 @@ otError Buffer::InFrameBeginSegment(void) uint16_t headerFlags = kSegmentHeaderNoFlag; // Verify that segment is not yet started (i.e., head and tail are the same). - VerifyOrExit(mWriteSegmentHead == mWriteSegmentTail); + EXPECT(mWriteSegmentHead == mWriteSegmentTail, NO_ACTION); // Check if this is the start of a new frame (i.e., frame start is same as segment head). if (mWriteFrameStart[mWriteDirection] == mWriteSegmentHead) @@ -263,7 +264,7 @@ otError Buffer::InFrameBeginSegment(void) // Reserve space for the segment header. for (uint16_t i = kSegmentHeaderSize; i; i--) { - SuccessOrExit(error = InFrameAppend(0)); + EXPECT_NO_ERROR(error = InFrameAppend(0)); } // Write the flags at the segment head. @@ -309,7 +310,7 @@ void Buffer::InFrameDiscard(void) otMessage *message; #endif - VerifyOrExit(mWriteDirection != kUnknown); + EXPECT(mWriteDirection != kUnknown, NO_ACTION); // Move the write segment head and tail pointers back to frame start. mWriteSegmentHead = mWriteSegmentTail = mWriteFrameStart[mWriteDirection]; @@ -361,10 +362,10 @@ otError Buffer::InFrameFeedByte(uint8_t aByte) { otError error = OT_ERROR_NONE; - VerifyOrExit(mWriteDirection != kUnknown, error = OT_ERROR_INVALID_STATE); + EXPECT(mWriteDirection != kUnknown, error = OT_ERROR_INVALID_STATE); // Begin a new segment (if we are not in middle of segment already). - SuccessOrExit(error = InFrameBeginSegment()); + EXPECT_NO_ERROR(error = InFrameBeginSegment()); error = InFrameAppend(aByte); @@ -376,15 +377,15 @@ otError Buffer::InFrameFeedData(const uint8_t *aDataBuffer, uint16_t aDataBuffer { otError error = OT_ERROR_NONE; - VerifyOrExit(mWriteDirection != kUnknown, error = OT_ERROR_INVALID_STATE); + EXPECT(mWriteDirection != kUnknown, error = OT_ERROR_INVALID_STATE); // Begin a new segment (if we are not in middle of segment already). - SuccessOrExit(error = InFrameBeginSegment()); + EXPECT_NO_ERROR(error = InFrameBeginSegment()); // Write the data buffer while (aDataBufferLength--) { - SuccessOrExit(error = InFrameAppend(*aDataBuffer++)); + EXPECT_NO_ERROR(error = InFrameAppend(*aDataBuffer++)); } exit: @@ -396,11 +397,11 @@ otError Buffer::InFrameFeedMessage(otMessage *aMessage) { otError error = OT_ERROR_NONE; - VerifyOrExit(aMessage != nullptr, error = OT_ERROR_INVALID_ARGS); - VerifyOrExit(mWriteDirection != kUnknown, error = OT_ERROR_INVALID_STATE); + EXPECT(aMessage != nullptr, error = OT_ERROR_INVALID_ARGS); + EXPECT(mWriteDirection != kUnknown, error = OT_ERROR_INVALID_STATE); // Begin a new segment (if we are not in middle of segment already). - SuccessOrExit(error = InFrameBeginSegment()); + EXPECT_NO_ERROR(error = InFrameBeginSegment()); // Enqueue the message in the current write frame queue. otMessageQueueEnqueue(&mWriteFrameMessageQueue, aMessage); @@ -417,10 +418,10 @@ otError Buffer::InFrameGetPosition(WritePosition &aPosition) { otError error = OT_ERROR_NONE; - VerifyOrExit(mWriteDirection != kUnknown, error = OT_ERROR_INVALID_STATE); + EXPECT(mWriteDirection != kUnknown, error = OT_ERROR_INVALID_STATE); // Begin a new segment (if we are not in middle of segment already). - SuccessOrExit(error = InFrameBeginSegment()); + EXPECT_NO_ERROR(error = InFrameBeginSegment()); aPosition.mPosition = mWriteSegmentTail; aPosition.mSegmentHead = mWriteSegmentHead; @@ -436,14 +437,14 @@ otError Buffer::InFrameOverwrite(const WritePosition &aPosition, const uint8_t * uint16_t segmentLength; uint16_t distance; - VerifyOrExit(mWriteDirection != kUnknown, error = OT_ERROR_INVALID_STATE); + EXPECT(mWriteDirection != kUnknown, error = OT_ERROR_INVALID_STATE); - VerifyOrExit(aPosition.mSegmentHead == mWriteSegmentHead, error = OT_ERROR_INVALID_ARGS); + EXPECT(aPosition.mSegmentHead == mWriteSegmentHead, error = OT_ERROR_INVALID_ARGS); // Ensure the overwrite does not go beyond current segment tail. segmentLength = GetDistance(mWriteSegmentHead, mWriteSegmentTail, mWriteDirection); distance = GetDistance(mWriteSegmentHead, aPosition.mPosition, mWriteDirection); - VerifyOrExit(distance + aDataBufferLength <= segmentLength, error = OT_ERROR_INVALID_ARGS); + EXPECT(distance + aDataBufferLength <= segmentLength, error = OT_ERROR_INVALID_ARGS); bufPtr = aPosition.mPosition; while (aDataBufferLength > 0) @@ -466,12 +467,12 @@ uint16_t Buffer::InFrameGetDistance(const WritePosition &aPosition) const uint16_t segmentLength; uint16_t offset; - VerifyOrExit(mWriteDirection != kUnknown); - VerifyOrExit(aPosition.mSegmentHead == mWriteSegmentHead); + EXPECT(mWriteDirection != kUnknown, NO_ACTION); + EXPECT(aPosition.mSegmentHead == mWriteSegmentHead, NO_ACTION); segmentLength = GetDistance(mWriteSegmentHead, mWriteSegmentTail, mWriteDirection); offset = GetDistance(mWriteSegmentHead, aPosition.mPosition, mWriteDirection); - VerifyOrExit(offset < segmentLength); + EXPECT(offset < segmentLength, NO_ACTION); distance = GetDistance(aPosition.mPosition, mWriteSegmentTail, mWriteDirection); @@ -485,12 +486,12 @@ otError Buffer::InFrameReset(const WritePosition &aPosition) uint16_t segmentLength; uint16_t offset; - VerifyOrExit(mWriteDirection != kUnknown, error = OT_ERROR_INVALID_STATE); - VerifyOrExit(aPosition.mSegmentHead == mWriteSegmentHead, error = OT_ERROR_INVALID_ARGS); + EXPECT(mWriteDirection != kUnknown, error = OT_ERROR_INVALID_STATE); + EXPECT(aPosition.mSegmentHead == mWriteSegmentHead, error = OT_ERROR_INVALID_ARGS); segmentLength = GetDistance(mWriteSegmentHead, mWriteSegmentTail, mWriteDirection); offset = GetDistance(mWriteSegmentHead, aPosition.mPosition, mWriteDirection); - VerifyOrExit(offset < segmentLength, error = OT_ERROR_INVALID_ARGS); + EXPECT(offset < segmentLength, error = OT_ERROR_INVALID_ARGS); mWriteSegmentTail = aPosition.mPosition; @@ -505,7 +506,7 @@ otError Buffer::InFrameEnd(void) #endif otError error = OT_ERROR_NONE; - VerifyOrExit(mWriteDirection != kUnknown, error = OT_ERROR_INVALID_STATE); + EXPECT(mWriteDirection != kUnknown, error = OT_ERROR_INVALID_STATE); // End/Close the current segment (if any). InFrameEndSegment(kSegmentHeaderNoFlag); @@ -562,7 +563,7 @@ otError Buffer::OutFramePrepareSegment(void) mReadSegmentHead = mReadSegmentTail; // Ensure there is something to read (i.e. segment head is not at start of frame being written). - VerifyOrExit(mReadSegmentHead != mWriteFrameStart[mReadDirection], error = OT_ERROR_NOT_FOUND); + EXPECT(mReadSegmentHead != mWriteFrameStart[mReadDirection], error = OT_ERROR_NOT_FOUND); // Read the segment header. header = ReadUint16At(mReadSegmentHead, mReadDirection); @@ -571,7 +572,7 @@ otError Buffer::OutFramePrepareSegment(void) if (header & kSegmentHeaderNewFrameFlag) { // Ensure that this segment is start of current frame, otherwise the current frame is finished. - VerifyOrExit(mReadSegmentHead == mReadFrameStart[mReadDirection], error = OT_ERROR_NOT_FOUND); + EXPECT(mReadSegmentHead == mReadFrameStart[mReadDirection], error = OT_ERROR_NOT_FOUND); } // Find tail/end of current segment. @@ -587,14 +588,14 @@ otError Buffer::OutFramePrepareSegment(void) // Update the state to `InSegment` and return. mReadState = kReadStateInSegment; - ExitNow(); + EXIT_NOW(); } #if OPENTHREAD_SPINEL_CONFIG_OPENTHREAD_MESSAGE_ENABLE // No data in this segment, prepare any appended/associated message of this segment. if (OutFramePrepareMessage() == OT_ERROR_NONE) { - ExitNow(); + EXIT_NOW(); } // If there is no message (`PrepareMessage()` returned an error), loop back to prepare the next segment. @@ -623,19 +624,19 @@ otError Buffer::OutFramePrepareMessage(void) header = ReadUint16At(mReadSegmentHead, mReadDirection); // Ensure that the segment header indicates that there is an associated message or return `NotFound` error. - VerifyOrExit((header & kSegmentHeaderMessageIndicatorFlag) != 0, error = OT_ERROR_NOT_FOUND); + EXPECT((header & kSegmentHeaderMessageIndicatorFlag) != 0, error = OT_ERROR_NOT_FOUND); // Update the current message from the queue. mReadMessage = (mReadMessage == nullptr) ? otMessageQueueGetHead(&mMessageQueue[mReadDirection]) : otMessageQueueGetNext(&mMessageQueue[mReadDirection], mReadMessage); - VerifyOrExit(mReadMessage != nullptr, error = OT_ERROR_NOT_FOUND); + EXPECT(mReadMessage != nullptr, error = OT_ERROR_NOT_FOUND); // Reset the offset for reading the message. mReadMessageOffset = 0; // Fill the content from current message into the message buffer. - SuccessOrExit(error = OutFrameFillMessageBuffer()); + EXPECT_NO_ERROR(error = OutFrameFillMessageBuffer()); // If all successful, set the state to `InMessage`. mReadState = kReadStateInMessage; @@ -651,14 +652,14 @@ otError Buffer::OutFrameFillMessageBuffer(void) otError error = OT_ERROR_NONE; int readLength; - VerifyOrExit(mReadMessage != nullptr, error = OT_ERROR_NOT_FOUND); + EXPECT(mReadMessage != nullptr, error = OT_ERROR_NOT_FOUND); - VerifyOrExit(mReadMessageOffset < otMessageGetLength(mReadMessage), error = OT_ERROR_NOT_FOUND); + EXPECT(mReadMessageOffset < otMessageGetLength(mReadMessage), error = OT_ERROR_NOT_FOUND); // Read portion of current message from the offset into message buffer. readLength = otMessageRead(mReadMessage, mReadMessageOffset, mMessageBuffer, sizeof(mMessageBuffer)); - VerifyOrExit(readLength > 0, error = OT_ERROR_NOT_FOUND); + EXPECT(readLength > 0, error = OT_ERROR_NOT_FOUND); // Update the message offset, set up the message tail, and set read pointer to start of message buffer. @@ -677,7 +678,7 @@ otError Buffer::OutFrameBegin(void) { otError error = OT_ERROR_NONE; - VerifyOrExit(!IsEmpty(), error = OT_ERROR_NOT_FOUND); + EXPECT(!IsEmpty(), error = OT_ERROR_NOT_FOUND); OutFrameSelectReadDirection(); @@ -732,7 +733,7 @@ uint8_t Buffer::OutFrameReadByte(void) // If there is no message, move to next segment (if any). if (error != OT_ERROR_NONE) { - IgnoreError(OutFramePrepareSegment()); + IGNORE_RETURN(OutFramePrepareSegment()); } } @@ -753,7 +754,7 @@ uint8_t Buffer::OutFrameReadByte(void) // If no more bytes in the message, move to next segment (if any). if (error != OT_ERROR_NONE) { - IgnoreError(OutFramePrepareSegment()); + IGNORE_RETURN(OutFramePrepareSegment()); } } #endif @@ -783,7 +784,7 @@ otError Buffer::OutFrameRemove(void) uint8_t numSegments; FrameTag tag; - VerifyOrExit(!IsEmpty(), error = OT_ERROR_NOT_FOUND); + EXPECT(!IsEmpty(), error = OT_ERROR_NOT_FOUND); OutFrameSelectReadDirection(); @@ -831,7 +832,7 @@ otError Buffer::OutFrameRemove(void) // If this assert fails, it is a likely indicator that the internal structure of the NCP buffer has been // corrupted. - OT_ASSERT(numSegments <= kMaxSegments); + assert(numSegments <= kMaxSegments); } mReadFrameStart[mReadDirection] = bufPtr; @@ -858,7 +859,7 @@ void Buffer::UpdateReadWriteStartPointers(void) // Move the high priority pointers to be right behind the low priority start. mWriteFrameStart[kPriorityHigh] = GetUpdatedBufPtr(mReadFrameStart[kPriorityLow], 1, kBackward); mReadFrameStart[kPriorityHigh] = mWriteFrameStart[kPriorityHigh]; - ExitNow(); + EXIT_NOW(); } // If there is no fully written low priority frame, and not in middle of writing a new frame either. @@ -884,9 +885,9 @@ uint16_t Buffer::OutFrameGetLength(void) #endif // If the frame length was calculated before, return the previously calculated length. - VerifyOrExit(mReadFrameLength == kUnknownFrameLength, frameLength = mReadFrameLength); + EXPECT(mReadFrameLength == kUnknownFrameLength, frameLength = mReadFrameLength); - VerifyOrExit(!IsEmpty(), frameLength = 0); + EXPECT(!IsEmpty(), frameLength = 0); OutFrameSelectReadDirection(); @@ -934,7 +935,7 @@ uint16_t Buffer::OutFrameGetLength(void) // If this assert fails, it is a likely indicator that the internal structure of the NCP buffer has been // corrupted. - OT_ASSERT(numSegments <= kMaxSegments); + assert(numSegments <= kMaxSegments); } // Remember the calculated frame length for current active frame. diff --git a/src/lib/spinel/spinel_decoder.cpp b/src/lib/spinel/spinel_decoder.cpp index 9130bbbec..3f0546b7f 100644 --- a/src/lib/spinel/spinel_decoder.cpp +++ b/src/lib/spinel/spinel_decoder.cpp @@ -32,8 +32,8 @@ #include "spinel_decoder.hpp" -#include "common/code_utils.hpp" #include "common/string.hpp" +#include "lib/utils/utils.hpp" namespace ot { namespace Spinel { @@ -72,7 +72,7 @@ otError Decoder::ReadBool(bool &aBool) otError error = OT_ERROR_NONE; uint8_t byte; - SuccessOrExit(error = ReadUint8(byte)); + EXPECT_NO_ERROR(error = ReadUint8(byte)); // Boolean value are encoded in 8-bits as either 0x00 or 0x01. All other values are illegal. if (byte == 0x00) @@ -96,7 +96,7 @@ otError Decoder::ReadUint8(uint8_t &aUint8) { otError error = OT_ERROR_NONE; - VerifyOrExit(mIndex + sizeof(uint8_t) <= mEnd, error = OT_ERROR_PARSE); + EXPECT(mIndex + sizeof(uint8_t) <= mEnd, error = OT_ERROR_PARSE); aUint8 = mFrame[mIndex]; mIndex += sizeof(uint8_t); @@ -109,7 +109,7 @@ otError Decoder::ReadInt8(int8_t &aInt8) otError error = OT_ERROR_NONE; uint8_t byte; - SuccessOrExit(error = ReadUint8(byte)); + EXPECT_NO_ERROR(error = ReadUint8(byte)); aInt8 = static_cast(byte); exit: @@ -120,7 +120,7 @@ otError Decoder::ReadUint16(uint16_t &aUint16) { otError error = OT_ERROR_NONE; - VerifyOrExit(mIndex + sizeof(uint16_t) <= mEnd, error = OT_ERROR_PARSE); + EXPECT(mIndex + sizeof(uint16_t) <= mEnd, error = OT_ERROR_PARSE); aUint16 = static_cast(mFrame[mIndex] | (mFrame[mIndex + 1] << 8)); @@ -135,7 +135,7 @@ otError Decoder::ReadInt16(int16_t &aInt16) otError error = OT_ERROR_NONE; uint16_t u16; - SuccessOrExit(error = ReadUint16(u16)); + EXPECT_NO_ERROR(error = ReadUint16(u16)); aInt16 = static_cast(u16); exit: @@ -146,7 +146,7 @@ otError Decoder::ReadUint32(uint32_t &aUint32) { otError error = OT_ERROR_NONE; - VerifyOrExit(mIndex + sizeof(uint32_t) <= mEnd, error = OT_ERROR_PARSE); + EXPECT(mIndex + sizeof(uint32_t) <= mEnd, error = OT_ERROR_PARSE); aUint32 = ((static_cast(mFrame[mIndex + 0]) << 0) | (static_cast(mFrame[mIndex + 1]) << 8) | (static_cast(mFrame[mIndex + 2]) << 16) | (static_cast(mFrame[mIndex + 3]) << 24)); @@ -162,7 +162,7 @@ otError Decoder::ReadInt32(int32_t &aInt32) otError error = OT_ERROR_NONE; uint32_t u32; - SuccessOrExit(error = ReadUint32(u32)); + EXPECT_NO_ERROR(error = ReadUint32(u32)); aInt32 = static_cast(u32); exit: @@ -173,7 +173,7 @@ otError Decoder::ReadUint64(uint64_t &aUint64) { otError error = OT_ERROR_NONE; - VerifyOrExit(mIndex + sizeof(uint64_t) <= mEnd, error = OT_ERROR_PARSE); + EXPECT(mIndex + sizeof(uint64_t) <= mEnd, error = OT_ERROR_PARSE); aUint64 = ((static_cast(mFrame[mIndex + 0]) << 0) | (static_cast(mFrame[mIndex + 1]) << 8) | (static_cast(mFrame[mIndex + 2]) << 16) | (static_cast(mFrame[mIndex + 3]) << 24) | @@ -191,7 +191,7 @@ otError Decoder::ReadInt64(int64_t &aInt64) otError error = OT_ERROR_NONE; uint64_t u64; - SuccessOrExit(error = ReadUint64(u64)); + EXPECT_NO_ERROR(error = ReadUint64(u64)); aInt64 = static_cast(u64); exit: @@ -205,7 +205,7 @@ otError Decoder::ReadUintPacked(unsigned int &aUint) unsigned int uint; parsedLen = spinel_packed_uint_decode(&mFrame[mIndex], mEnd - mIndex, &uint); - VerifyOrExit(parsedLen > 0, error = OT_ERROR_PARSE); + EXPECT(parsedLen > 0, error = OT_ERROR_PARSE); mIndex += parsedLen; aUint = uint; @@ -219,7 +219,7 @@ otError Decoder::ReadItem(const uint8_t **aPtr, uint16_t aSize) { otError error = OT_ERROR_NONE; - VerifyOrExit(mIndex + aSize <= mEnd, error = OT_ERROR_PARSE); + EXPECT(mIndex + aSize <= mEnd, error = OT_ERROR_PARSE); *aPtr = &mFrame[mIndex]; @@ -234,8 +234,8 @@ otError Decoder::ReadIp6Address(spinel_ipv6addr_t &aIp6Addr) otError error = OT_ERROR_NONE; const spinel_ipv6addr_t *ipv6AddrPtr = nullptr; - SuccessOrExit(error = ReadIp6Address(ipv6AddrPtr)); - VerifyOrExit(ipv6AddrPtr != nullptr, error = OT_ERROR_PARSE); + EXPECT_NO_ERROR(error = ReadIp6Address(ipv6AddrPtr)); + EXPECT(ipv6AddrPtr != nullptr, error = OT_ERROR_PARSE); aIp6Addr = *ipv6AddrPtr; exit: @@ -247,8 +247,8 @@ otError Decoder::ReadIp6Address(otIp6Address &aIp6Addr) otError error = OT_ERROR_NONE; const otIp6Address *ipv6AddrPtr = nullptr; - SuccessOrExit(error = ReadIp6Address(ipv6AddrPtr)); - VerifyOrExit(ipv6AddrPtr != nullptr, error = OT_ERROR_PARSE); + EXPECT_NO_ERROR(error = ReadIp6Address(ipv6AddrPtr)); + EXPECT(ipv6AddrPtr != nullptr, error = OT_ERROR_PARSE); aIp6Addr = *ipv6AddrPtr; exit: @@ -260,8 +260,8 @@ otError Decoder::ReadEui64(spinel_eui64_t &aEui64) otError error = OT_ERROR_NONE; const spinel_eui64_t *eui64Ptr = nullptr; - SuccessOrExit(error = ReadEui64(eui64Ptr)); - VerifyOrExit(eui64Ptr != nullptr, error = OT_ERROR_PARSE); + EXPECT_NO_ERROR(error = ReadEui64(eui64Ptr)); + EXPECT(eui64Ptr != nullptr, error = OT_ERROR_PARSE); aEui64 = *eui64Ptr; exit: @@ -273,8 +273,8 @@ otError Decoder::ReadEui64(otExtAddress &aEui64) otError error = OT_ERROR_NONE; const otExtAddress *eui64Ptr = nullptr; - SuccessOrExit(error = ReadEui64(eui64Ptr)); - VerifyOrExit(eui64Ptr != nullptr, error = OT_ERROR_PARSE); + EXPECT_NO_ERROR(error = ReadEui64(eui64Ptr)); + EXPECT(eui64Ptr != nullptr, error = OT_ERROR_PARSE); aEui64 = *eui64Ptr; exit: @@ -286,8 +286,8 @@ otError Decoder::ReadEui48(spinel_eui48_t &aEui48) otError error = OT_ERROR_NONE; const spinel_eui48_t *eui48Ptr = nullptr; - SuccessOrExit(error = ReadEui48(eui48Ptr)); - VerifyOrExit(eui48Ptr != nullptr, error = OT_ERROR_PARSE); + EXPECT_NO_ERROR(error = ReadEui48(eui48Ptr)); + EXPECT(eui48Ptr != nullptr, error = OT_ERROR_PARSE); aEui48 = *eui48Ptr; exit: @@ -300,10 +300,10 @@ otError Decoder::ReadUtf8(const char *&aUtf8) size_t len; // Ensure there is at least one byte (for null character). - VerifyOrExit(mIndex + sizeof(uint8_t) <= mEnd, error = OT_ERROR_PARSE); + EXPECT(mIndex + sizeof(uint8_t) <= mEnd, error = OT_ERROR_PARSE); len = StringLength(reinterpret_cast(&mFrame[mIndex]), mEnd - mIndex); - VerifyOrExit(len < static_cast(mEnd - mIndex), error = OT_ERROR_PARSE); + EXPECT(len < static_cast(mEnd - mIndex), error = OT_ERROR_PARSE); aUtf8 = reinterpret_cast(&mFrame[mIndex]); @@ -326,8 +326,8 @@ otError Decoder::ReadDataWithLen(const uint8_t *&aData, uint16_t &aDataLen) otError error = OT_ERROR_NONE; uint16_t len; - SuccessOrExit(error = ReadUint16(len)); - SuccessOrExit(error = ReadItem(&aData, len)); + EXPECT_NO_ERROR(error = ReadUint16(len)); + EXPECT_NO_ERROR(error = ReadItem(&aData, len)); aDataLen = len; exit: @@ -339,10 +339,10 @@ otError Decoder::OpenStruct(void) otError error = OT_ERROR_NONE; uint16_t structLen; - VerifyOrExit(mNumOpenStructs < kMaxNestedStructs, error = OT_ERROR_INVALID_STATE); + EXPECT(mNumOpenStructs < kMaxNestedStructs, error = OT_ERROR_INVALID_STATE); - SuccessOrExit(error = ReadUint16(structLen)); - VerifyOrExit(structLen <= mEnd - mIndex, error = OT_ERROR_PARSE); + EXPECT_NO_ERROR(error = ReadUint16(structLen)); + EXPECT(structLen <= mEnd - mIndex, error = OT_ERROR_PARSE); mPrevEnd[mNumOpenStructs] = mEnd; mEnd = (mIndex + structLen); @@ -356,7 +356,7 @@ otError Decoder::CloseStruct(void) { otError error = OT_ERROR_NONE; - VerifyOrExit(mNumOpenStructs > 0, error = OT_ERROR_INVALID_STATE); + EXPECT(mNumOpenStructs > 0, error = OT_ERROR_INVALID_STATE); // If there is a saved position and it is contained // within the current struct being closed, the saved @@ -387,7 +387,7 @@ otError Decoder::ResetToSaved(void) { otError error = OT_ERROR_NONE; - VerifyOrExit(IsSavedPositionValid(), error = OT_ERROR_INVALID_STATE); + EXPECT(IsSavedPositionValid(), error = OT_ERROR_INVALID_STATE); mIndex = mSavedIndex; mEnd = mSavedEnd; diff --git a/src/lib/spinel/spinel_driver.cpp b/src/lib/spinel/spinel_driver.cpp index 6c7268af1..e802b29b4 100644 --- a/src/lib/spinel/spinel_driver.cpp +++ b/src/lib/spinel/spinel_driver.cpp @@ -32,11 +32,10 @@ #include -#include "common/code_utils.hpp" -#include "common/new.hpp" -#include "common/num_utils.hpp" #include "lib/platform/exit_code.h" #include "lib/spinel/spinel.h" +#include "lib/utils/math.hpp" +#include "lib/utils/utils.hpp" namespace ot { namespace Spinel { @@ -110,9 +109,9 @@ otError SpinelDriver::SendReset(uint8_t aResetType) packed = spinel_datatype_pack(buffer, sizeof(buffer), SPINEL_DATATYPE_COMMAND_S SPINEL_DATATYPE_UINT8_S, SPINEL_HEADER_FLAG | SPINEL_HEADER_IID(mIid), SPINEL_CMD_RESET, aResetType); - VerifyOrExit(packed > 0 && static_cast(packed) <= sizeof(buffer), error = OT_ERROR_NO_BUFS); + EXPECT(packed > 0 && static_cast(packed) <= sizeof(buffer), error = OT_ERROR_NO_BUFS); - SuccessOrExit(error = mSpinelInterface->SendFrame(buffer, static_cast(packed))); + EXPECT_NO_ERROR(error = mSpinelInterface->SendFrame(buffer, static_cast(packed))); LogSpinelFrame(buffer, static_cast(packed), true /* aTx */); exit: @@ -125,22 +124,22 @@ void SpinelDriver::ResetCoprocessor(bool aSoftwareReset) bool resetDone = false; // Avoid resetting the device twice in a row in Multipan RCP architecture - VerifyOrExit(!mIsCoprocessorReady, resetDone = true); + EXPECT(!mIsCoprocessorReady, resetDone = true); mWaitingKey = SPINEL_PROP_LAST_STATUS; if (aSoftwareReset && (SendReset(SPINEL_RESET_STACK) == OT_ERROR_NONE) && (WaitResponse() == OT_ERROR_NONE)) { - VerifyOrExit(mIsCoprocessorReady, resetDone = false); + EXPECT(mIsCoprocessorReady, resetDone = false); LogCrit("Software reset co-processor successfully"); - ExitNow(resetDone = true); + EXIT_NOW(resetDone = true); } hardwareReset = (mSpinelInterface->HardwareReset() == OT_ERROR_NONE); if (hardwareReset) { - SuccessOrExit(WaitResponse()); + EXPECT_NO_ERROR(WaitResponse()); } resetDone = true; @@ -188,11 +187,11 @@ otError SpinelDriver::SendCommand(uint32_t aCommand, spinel_prop_key_t aKey, spi packed = spinel_datatype_pack(buffer, sizeof(buffer), "Cii", SPINEL_HEADER_FLAG | SPINEL_HEADER_IID(mIid) | aTid, aCommand, aKey); - VerifyOrExit(packed > 0 && static_cast(packed) <= sizeof(buffer), error = OT_ERROR_NO_BUFS); + EXPECT(packed > 0 && static_cast(packed) <= sizeof(buffer), error = OT_ERROR_NO_BUFS); offset = static_cast(packed); - SuccessOrExit(error = mSpinelInterface->SendFrame(buffer, offset)); + EXPECT_NO_ERROR(error = mSpinelInterface->SendFrame(buffer, offset)); exit: return error; @@ -213,7 +212,7 @@ otError SpinelDriver::SendCommand(uint32_t aCommand, packed = spinel_datatype_pack(buffer, sizeof(buffer), "Cii", SPINEL_HEADER_FLAG | SPINEL_HEADER_IID(mIid) | aTid, aCommand, aKey); - VerifyOrExit(packed > 0 && static_cast(packed) <= sizeof(buffer), error = OT_ERROR_NO_BUFS); + EXPECT(packed > 0 && static_cast(packed) <= sizeof(buffer), error = OT_ERROR_NO_BUFS); offset = static_cast(packed); @@ -221,12 +220,12 @@ otError SpinelDriver::SendCommand(uint32_t aCommand, if (aFormat) { packed = spinel_datatype_vpack(buffer + offset, sizeof(buffer) - offset, aFormat, aArgs); - VerifyOrExit(packed > 0 && static_cast(packed + offset) <= sizeof(buffer), error = OT_ERROR_NO_BUFS); + EXPECT(packed > 0 && static_cast(packed + offset) <= sizeof(buffer), error = OT_ERROR_NO_BUFS); offset += static_cast(packed); } - SuccessOrExit(error = mSpinelInterface->SendFrame(buffer, offset)); + EXPECT_NO_ERROR(error = mSpinelInterface->SendFrame(buffer, offset)); exit: return error; @@ -246,7 +245,7 @@ otError SpinelDriver::WaitResponse(void) otError error = OT_ERROR_NONE; uint64_t end = otPlatTimeGet() + kMaxWaitTime * kUsPerMs; - LogDebg("Waiting response: key=%lu", ToUlong(mWaitingKey)); + LogDebg("Waiting response: key=%lu", Lib::Utils::ToUlong(mWaitingKey)); do { @@ -255,7 +254,7 @@ otError SpinelDriver::WaitResponse(void) if ((end <= now) || (mSpinelInterface->WaitForFrame(end - now) != OT_ERROR_NONE)) { LogWarn("Wait for response timeout"); - ExitNow(error = OT_ERROR_RESPONSE_TIMEOUT); + EXIT_NOW(error = OT_ERROR_RESPONSE_TIMEOUT); } } while (mIsWaitingForResponse || !mIsCoprocessorReady); @@ -284,10 +283,10 @@ void SpinelDriver::HandleReceivedFrame(void) if (!mIidList.Contains(iid)) { mRxFrameBuffer.DiscardFrame(); - ExitNow(); + EXIT_NOW(); } - VerifyOrExit(unpacked > 0 && (header & SPINEL_HEADER_FLAG) == SPINEL_HEADER_FLAG, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0 && (header & SPINEL_HEADER_FLAG) == SPINEL_HEADER_FLAG, error = OT_ERROR_PARSE); assert(mReceivedFrameHandler != nullptr && mFrameHandlerContext != nullptr); mReceivedFrameHandler(mRxFrameBuffer.GetFrame(), mRxFrameBuffer.GetLength(), header, shouldSave, @@ -333,17 +332,16 @@ void SpinelDriver::HandleInitialFrame(const uint8_t *aFrame, uint16_t aLength, u OT_UNUSED_VARIABLE(aHeader); rval = spinel_datatype_unpack(aFrame, aLength, "CiiD", &header, &cmd, &key, &data, &len); - VerifyOrExit(rval > 0 && cmd >= SPINEL_CMD_PROP_VALUE_IS && cmd <= SPINEL_CMD_PROP_VALUE_REMOVED, - error = OT_ERROR_PARSE); + EXPECT(rval > 0 && cmd >= SPINEL_CMD_PROP_VALUE_IS && cmd <= SPINEL_CMD_PROP_VALUE_REMOVED, error = OT_ERROR_PARSE); - VerifyOrExit(cmd == SPINEL_CMD_PROP_VALUE_IS, error = OT_ERROR_DROP); + EXPECT(cmd == SPINEL_CMD_PROP_VALUE_IS, error = OT_ERROR_DROP); if (key == SPINEL_PROP_LAST_STATUS) { spinel_status_t status = SPINEL_STATUS_OK; unpacked = spinel_datatype_unpack(data, len, "i", &status); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); if (status >= SPINEL_STATUS_RESET__BEGIN && status <= SPINEL_STATUS_RESET__END) { @@ -356,26 +354,26 @@ void SpinelDriver::HandleInitialFrame(const uint8_t *aFrame, uint16_t aLength, u else { LogInfo("co-processor last status: %s", spinel_status_to_cstr(status)); - ExitNow(); + EXIT_NOW(); } } else { // Drop other frames when the key isn't waiting key. - VerifyOrExit(mWaitingKey == key, error = OT_ERROR_DROP); + EXPECT(mWaitingKey == key, error = OT_ERROR_DROP); if (key == SPINEL_PROP_PROTOCOL_VERSION) { unpacked = spinel_datatype_unpack(data, len, (SPINEL_DATATYPE_UINT_PACKED_S SPINEL_DATATYPE_UINT_PACKED_S), &mSpinelVersionMajor, &mSpinelVersionMinor); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); } else if (key == SPINEL_PROP_NCP_VERSION) { unpacked = spinel_datatype_unpack_in_place(data, len, SPINEL_DATATYPE_UTF8_S, mVersion, sizeof(mVersion)); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); } else if (key == SPINEL_PROP_CAPS) { @@ -385,16 +383,16 @@ void SpinelDriver::HandleInitialFrame(const uint8_t *aFrame, uint16_t aLength, u unpacked = spinel_datatype_unpack_in_place(data, len, SPINEL_DATATYPE_DATA_S, capsBuffer, &capsLength); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); while (capsLength > 0) { unsigned int capability; unpacked = spinel_datatype_unpack(capsData, capsLength, SPINEL_DATATYPE_UINT_PACKED_S, &capability); - VerifyOrExit(unpacked > 0, error = OT_ERROR_PARSE); + EXPECT(unpacked > 0, error = OT_ERROR_PARSE); - SuccessOrExit(error = mCoprocessorCaps.PushBack(capability)); + EXPECT_NO_ERROR(error = mCoprocessorCaps.PushBack(capability)); capsData += unpacked; capsLength -= static_cast(unpacked); @@ -413,11 +411,11 @@ otError SpinelDriver::CheckSpinelVersion(void) { otError error = OT_ERROR_NONE; - SuccessOrExit(error = SendCommand(SPINEL_CMD_PROP_VALUE_GET, SPINEL_PROP_PROTOCOL_VERSION, sTid)); + EXPECT_NO_ERROR(error = SendCommand(SPINEL_CMD_PROP_VALUE_GET, SPINEL_PROP_PROTOCOL_VERSION, sTid)); mIsWaitingForResponse = true; mWaitingKey = SPINEL_PROP_PROTOCOL_VERSION; - SuccessOrExit(error = WaitResponse()); + EXPECT_NO_ERROR(error = WaitResponse()); if ((mSpinelVersionMajor != SPINEL_PROTOCOL_VERSION_THREAD_MAJOR) || (mSpinelVersionMinor != SPINEL_PROTOCOL_VERSION_THREAD_MINOR)) @@ -435,11 +433,11 @@ otError SpinelDriver::GetCoprocessorVersion(void) { otError error = OT_ERROR_NONE; - SuccessOrExit(error = SendCommand(SPINEL_CMD_PROP_VALUE_GET, SPINEL_PROP_NCP_VERSION, sTid)); + EXPECT_NO_ERROR(error = SendCommand(SPINEL_CMD_PROP_VALUE_GET, SPINEL_PROP_NCP_VERSION, sTid)); mIsWaitingForResponse = true; mWaitingKey = SPINEL_PROP_NCP_VERSION; - SuccessOrExit(error = WaitResponse()); + EXPECT_NO_ERROR(error = WaitResponse()); exit: return error; } @@ -448,11 +446,11 @@ otError SpinelDriver::GetCoprocessorCaps(void) { otError error = OT_ERROR_NONE; - SuccessOrExit(error = SendCommand(SPINEL_CMD_PROP_VALUE_GET, SPINEL_PROP_CAPS, sTid)); + EXPECT_NO_ERROR(error = SendCommand(SPINEL_CMD_PROP_VALUE_GET, SPINEL_PROP_CAPS, sTid)); mIsWaitingForResponse = true; mWaitingKey = SPINEL_PROP_CAPS; - SuccessOrExit(error = WaitResponse()); + EXPECT_NO_ERROR(error = WaitResponse()); exit: return error; } diff --git a/src/lib/spinel/spinel_encoder.cpp b/src/lib/spinel/spinel_encoder.cpp index 6cd390486..de1d937d7 100644 --- a/src/lib/spinel/spinel_encoder.cpp +++ b/src/lib/spinel/spinel_encoder.cpp @@ -34,7 +34,7 @@ #include -#include "common/code_utils.hpp" +#include "lib/utils/utils.hpp" namespace ot { namespace Spinel { @@ -54,15 +54,15 @@ otError Encoder::BeginFrame(uint8_t aHeader, unsigned int aCommand) if (SPINEL_HEADER_GET_TID(aHeader) != 0) { - SuccessOrExit(error = BeginFrame(Spinel::Buffer::kPriorityHigh)); + EXPECT_NO_ERROR(error = BeginFrame(Spinel::Buffer::kPriorityHigh)); } else { - SuccessOrExit(error = BeginFrame(Spinel::Buffer::kPriorityLow)); + EXPECT_NO_ERROR(error = BeginFrame(Spinel::Buffer::kPriorityLow)); } - SuccessOrExit(error = WriteUint8(aHeader)); - SuccessOrExit(error = WriteUintPacked(aCommand)); + EXPECT_NO_ERROR(error = WriteUint8(aHeader)); + EXPECT_NO_ERROR(error = WriteUintPacked(aCommand)); exit: return error; @@ -72,7 +72,7 @@ otError Encoder::BeginFrame(uint8_t aHeader, unsigned int aCommand, spinel_prop_ { otError error = OT_ERROR_NONE; - SuccessOrExit(error = BeginFrame(aHeader, aCommand)); + EXPECT_NO_ERROR(error = BeginFrame(aHeader, aCommand)); // The write position is saved before writing the property key, // so that if fetching the property fails and we need to @@ -80,8 +80,8 @@ otError Encoder::BeginFrame(uint8_t aHeader, unsigned int aCommand, spinel_prop_ // this saved write position and update the property key. // (Also see `OverwriteWithLastStatusError()`). - SuccessOrExit(error = SavePosition()); - SuccessOrExit(error = WriteUintPacked(aKey)); + EXPECT_NO_ERROR(error = SavePosition()); + EXPECT_NO_ERROR(error = WriteUintPacked(aKey)); exit: return error; @@ -91,9 +91,9 @@ otError Encoder::OverwriteWithLastStatusError(spinel_status_t aStatus) { otError error = OT_ERROR_NONE; - SuccessOrExit(error = ResetToSaved()); - SuccessOrExit(error = WriteUintPacked(SPINEL_PROP_LAST_STATUS)); - SuccessOrExit(error = WriteUintPacked(aStatus)); + EXPECT_NO_ERROR(error = ResetToSaved()); + EXPECT_NO_ERROR(error = WriteUintPacked(SPINEL_PROP_LAST_STATUS)); + EXPECT_NO_ERROR(error = WriteUintPacked(aStatus)); exit: return error; @@ -105,7 +105,7 @@ otError Encoder::EndFrame(void) while (mNumOpenStructs > 0) { - SuccessOrExit(error = CloseStruct()); + EXPECT_NO_ERROR(error = CloseStruct()); } error = mNcpBuffer.InFrameEnd(); @@ -118,8 +118,8 @@ otError Encoder::WriteUint16(uint16_t aUint16) { otError error = OT_ERROR_NONE; - SuccessOrExit(error = mNcpBuffer.InFrameFeedByte((aUint16 >> 0) & 0xff)); - SuccessOrExit(error = mNcpBuffer.InFrameFeedByte((aUint16 >> 8) & 0xff)); + EXPECT_NO_ERROR(error = mNcpBuffer.InFrameFeedByte((aUint16 >> 0) & 0xff)); + EXPECT_NO_ERROR(error = mNcpBuffer.InFrameFeedByte((aUint16 >> 8) & 0xff)); exit: return error; @@ -129,10 +129,10 @@ otError Encoder::WriteUint32(uint32_t aUint32) { otError error = OT_ERROR_NONE; - SuccessOrExit(error = mNcpBuffer.InFrameFeedByte((aUint32 >> 0) & 0xff)); - SuccessOrExit(error = mNcpBuffer.InFrameFeedByte((aUint32 >> 8) & 0xff)); - SuccessOrExit(error = mNcpBuffer.InFrameFeedByte((aUint32 >> 16) & 0xff)); - SuccessOrExit(error = mNcpBuffer.InFrameFeedByte((aUint32 >> 24) & 0xff)); + EXPECT_NO_ERROR(error = mNcpBuffer.InFrameFeedByte((aUint32 >> 0) & 0xff)); + EXPECT_NO_ERROR(error = mNcpBuffer.InFrameFeedByte((aUint32 >> 8) & 0xff)); + EXPECT_NO_ERROR(error = mNcpBuffer.InFrameFeedByte((aUint32 >> 16) & 0xff)); + EXPECT_NO_ERROR(error = mNcpBuffer.InFrameFeedByte((aUint32 >> 24) & 0xff)); exit: return error; @@ -142,14 +142,14 @@ otError Encoder::WriteUint64(uint64_t aUint64) { otError error = OT_ERROR_NONE; - SuccessOrExit(error = mNcpBuffer.InFrameFeedByte((aUint64 >> 0) & 0xff)); - SuccessOrExit(error = mNcpBuffer.InFrameFeedByte((aUint64 >> 8) & 0xff)); - SuccessOrExit(error = mNcpBuffer.InFrameFeedByte((aUint64 >> 16) & 0xff)); - SuccessOrExit(error = mNcpBuffer.InFrameFeedByte((aUint64 >> 24) & 0xff)); - SuccessOrExit(error = mNcpBuffer.InFrameFeedByte((aUint64 >> 32) & 0xff)); - SuccessOrExit(error = mNcpBuffer.InFrameFeedByte((aUint64 >> 40) & 0xff)); - SuccessOrExit(error = mNcpBuffer.InFrameFeedByte((aUint64 >> 48) & 0xff)); - SuccessOrExit(error = mNcpBuffer.InFrameFeedByte((aUint64 >> 56) & 0xff)); + EXPECT_NO_ERROR(error = mNcpBuffer.InFrameFeedByte((aUint64 >> 0) & 0xff)); + EXPECT_NO_ERROR(error = mNcpBuffer.InFrameFeedByte((aUint64 >> 8) & 0xff)); + EXPECT_NO_ERROR(error = mNcpBuffer.InFrameFeedByte((aUint64 >> 16) & 0xff)); + EXPECT_NO_ERROR(error = mNcpBuffer.InFrameFeedByte((aUint64 >> 24) & 0xff)); + EXPECT_NO_ERROR(error = mNcpBuffer.InFrameFeedByte((aUint64 >> 32) & 0xff)); + EXPECT_NO_ERROR(error = mNcpBuffer.InFrameFeedByte((aUint64 >> 40) & 0xff)); + EXPECT_NO_ERROR(error = mNcpBuffer.InFrameFeedByte((aUint64 >> 48) & 0xff)); + EXPECT_NO_ERROR(error = mNcpBuffer.InFrameFeedByte((aUint64 >> 56) & 0xff)); exit: return error; @@ -169,8 +169,8 @@ otError Encoder::WriteDataWithLen(const uint8_t *aData, uint16_t aDataLen) { otError error = OT_ERROR_NONE; - SuccessOrExit(error = WriteUint16(aDataLen)); - SuccessOrExit(error = WriteData(aData, aDataLen)); + EXPECT_NO_ERROR(error = WriteUint16(aDataLen)); + EXPECT_NO_ERROR(error = WriteData(aData, aDataLen)); exit: return error; @@ -186,8 +186,8 @@ otError Encoder::WriteUtf8(const char *aUtf8) len = 0xffff; } - SuccessOrExit(error = WriteData(reinterpret_cast(aUtf8), static_cast(len))); - SuccessOrExit(error = mNcpBuffer.InFrameFeedByte(0)); + EXPECT_NO_ERROR(error = WriteData(reinterpret_cast(aUtf8), static_cast(len))); + EXPECT_NO_ERROR(error = mNcpBuffer.InFrameFeedByte(0)); exit: return error; @@ -197,12 +197,12 @@ otError Encoder::OpenStruct(void) { otError error = OT_ERROR_NONE; - VerifyOrExit(mNumOpenStructs < kMaxNestedStructs, error = OT_ERROR_INVALID_STATE); - SuccessOrExit(error = mNcpBuffer.InFrameGetPosition(mStructPosition[mNumOpenStructs])); + EXPECT(mNumOpenStructs < kMaxNestedStructs, error = OT_ERROR_INVALID_STATE); + EXPECT_NO_ERROR(error = mNcpBuffer.InFrameGetPosition(mStructPosition[mNumOpenStructs])); // Reserve bytes for the length to be filled when the struct gets closed. - SuccessOrExit(error = mNcpBuffer.InFrameFeedByte(0)); - SuccessOrExit(error = mNcpBuffer.InFrameFeedByte(0)); + EXPECT_NO_ERROR(error = mNcpBuffer.InFrameFeedByte(0)); + EXPECT_NO_ERROR(error = mNcpBuffer.InFrameFeedByte(0)); mNumOpenStructs++; @@ -216,19 +216,19 @@ otError Encoder::CloseStruct(void) uint16_t len; uint8_t buffer[sizeof(uint16_t)]; - VerifyOrExit(mNumOpenStructs > 0, error = OT_ERROR_INVALID_STATE); + EXPECT(mNumOpenStructs > 0, error = OT_ERROR_INVALID_STATE); mNumOpenStructs--; len = mNcpBuffer.InFrameGetDistance(mStructPosition[mNumOpenStructs]); - VerifyOrExit(len >= sizeof(uint16_t), error = OT_ERROR_INVALID_STATE); + EXPECT(len >= sizeof(uint16_t), error = OT_ERROR_INVALID_STATE); len -= sizeof(uint16_t); buffer[0] = (len >> 0 & 0xff); buffer[1] = (len >> 8 & 0xff); - SuccessOrExit(error = mNcpBuffer.InFrameOverwrite(mStructPosition[mNumOpenStructs], buffer, sizeof(buffer))); + EXPECT_NO_ERROR(error = mNcpBuffer.InFrameOverwrite(mStructPosition[mNumOpenStructs], buffer, sizeof(buffer))); exit: return error; @@ -238,7 +238,7 @@ otError Encoder::SavePosition(void) { otError error = OT_ERROR_NONE; - SuccessOrExit(error = mNcpBuffer.InFrameGetPosition(mSavedPosition)); + EXPECT_NO_ERROR(error = mNcpBuffer.InFrameGetPosition(mSavedPosition)); mSavedNumOpenStructs = mNumOpenStructs; exit: @@ -249,7 +249,7 @@ otError Encoder::ResetToSaved(void) { otError error = OT_ERROR_NONE; - SuccessOrExit(error = mNcpBuffer.InFrameReset(mSavedPosition)); + EXPECT_NO_ERROR(error = mNcpBuffer.InFrameReset(mSavedPosition)); mNumOpenStructs = mSavedNumOpenStructs; exit: @@ -266,7 +266,7 @@ otError Encoder::WritePacked(const char *aPackFormat, ...) va_start(args, aPackFormat); packedLen = spinel_datatype_vpack(buf, sizeof(buf), aPackFormat, args); - VerifyOrExit((packedLen > 0) && (packedLen <= static_cast(sizeof(buf))), error = OT_ERROR_NO_BUFS); + EXPECT((packedLen > 0) && (packedLen <= static_cast(sizeof(buf))), error = OT_ERROR_NO_BUFS); error = mNcpBuffer.InFrameFeedData(buf, static_cast(packedLen)); @@ -283,7 +283,7 @@ otError Encoder::WriteVPacked(const char *aPackFormat, va_list aArgs) spinel_ssize_t packedLen; packedLen = spinel_datatype_vpack(buf, sizeof(buf), aPackFormat, aArgs); - VerifyOrExit((packedLen > 0) && (packedLen <= static_cast(sizeof(buf))), error = OT_ERROR_NO_BUFS); + EXPECT((packedLen > 0) && (packedLen <= static_cast(sizeof(buf))), error = OT_ERROR_NO_BUFS); error = mNcpBuffer.InFrameFeedData(buf, static_cast(packedLen)); diff --git a/src/lib/spinel/spinel_interface.hpp b/src/lib/spinel/spinel_interface.hpp index 10d0c9637..c2dfae349 100644 --- a/src/lib/spinel/spinel_interface.hpp +++ b/src/lib/spinel/spinel_interface.hpp @@ -35,6 +35,8 @@ #ifndef SPINEL_SPINEL_INTERFACE_HPP_ #define SPINEL_SPINEL_INTERFACE_HPP_ +#include "spinel-config.h" + #include "lib/spinel/multi_frame_buffer.hpp" #include "lib/spinel/radio_spinel_metrics.h" #include "lib/spinel/spinel.h" @@ -47,7 +49,7 @@ class SpinelInterface public: enum { - kMaxFrameSize = OPENTHREAD_CONFIG_PLATFORM_RADIO_SPINEL_RX_FRAME_BUFFER_SIZE, ///< Maximum buffer size. + kMaxFrameSize = OPENTHREAD_LIB_SPINEL_RX_FRAME_BUFFER_SIZE, ///< Maximum buffer size. }; /** @@ -182,22 +184,32 @@ protected: { #ifndef OPENTHREAD_CONFIG_MULTIPAN_RCP_ENABLE // Validate the iid. - VerifyOrExit(((aFrame[0] & SPINEL_HEADER_IID_MASK) == SPINEL_HEADER_IID_0)); + if (!((aFrame[0] & SPINEL_HEADER_IID_MASK) == SPINEL_HEADER_IID_0)) + { + goto exit; + } #endif // Validate the header flag by masking out the iid bits as it is validated above. - VerifyOrExit(((aFrame[0] & ~SPINEL_HEADER_IID_MASK) == SPINEL_HEADER_FLAG)); + if (!((aFrame[0] & ~SPINEL_HEADER_IID_MASK) == SPINEL_HEADER_FLAG)) + { + goto exit; + } // Validate the reset command. - VerifyOrExit(aFrame[1] == SPINEL_CMD_RESET); + if (!(aFrame[1] == SPINEL_CMD_RESET)) + { + goto exit; + } - ExitNow(resetCmd = true); + resetCmd = true; } exit: return resetCmd; } }; + } // namespace Spinel } // namespace ot diff --git a/src/lib/url/url.cpp b/src/lib/url/url.cpp index 040f6cdba..f06c84d86 100644 --- a/src/lib/url/url.cpp +++ b/src/lib/url/url.cpp @@ -32,7 +32,7 @@ #include #include -#include "core/common/code_utils.hpp" +#include "lib/utils/utils.hpp" namespace ot { namespace Url { @@ -54,7 +54,7 @@ otError Url::Init(char *aUrl) mProtocol = aUrl; url = strstr(aUrl, "://"); - VerifyOrExit(url != nullptr, error = OT_ERROR_PARSE); + EXPECT(url != nullptr, error = OT_ERROR_PARSE); *url = '\0'; url += sizeof("://") - 1; mPath = url; @@ -91,7 +91,7 @@ const char *Url::GetValue(const char *aName, const char *aLastValue) const } else { - VerifyOrExit(aLastValue > mQuery && aLastValue < mEnd); + EXPECT(aLastValue > mQuery && aLastValue < mEnd, NO_ACTION); start = aLastValue + strlen(aLastValue) + 1; } @@ -103,11 +103,11 @@ const char *Url::GetValue(const char *aName, const char *aLastValue) const { if (start[len] == '=') { - ExitNow(rval = &start[len + 1]); + EXIT_NOW(rval = &start[len + 1]); } else if (start[len] == '\0') { - ExitNow(rval = &start[len]); + EXIT_NOW(rval = &start[len]); } } last = start; @@ -124,10 +124,10 @@ otError Url::ParseUint32(const char *aName, uint32_t &aValue) const const char *str; long long value; - VerifyOrExit((str = GetValue(aName)) != nullptr, error = OT_ERROR_NOT_FOUND); + EXPECT((str = GetValue(aName)) != nullptr, error = OT_ERROR_NOT_FOUND); value = strtoll(str, nullptr, 0); - VerifyOrExit(0 <= value && value <= UINT32_MAX, error = OT_ERROR_INVALID_ARGS); + EXPECT(0 <= value && value <= UINT32_MAX, error = OT_ERROR_INVALID_ARGS); aValue = static_cast(value); exit: @@ -139,8 +139,8 @@ otError Url::ParseUint16(const char *aName, uint16_t &aValue) const otError error = OT_ERROR_NONE; uint32_t value; - SuccessOrExit(error = ParseUint32(aName, value)); - VerifyOrExit(value <= UINT16_MAX, error = OT_ERROR_INVALID_ARGS); + EXPECT_NO_ERROR(error = ParseUint32(aName, value)); + EXPECT(value <= UINT16_MAX, error = OT_ERROR_INVALID_ARGS); aValue = static_cast(value); exit: @@ -152,8 +152,8 @@ otError Url::ParseUint8(const char *aName, uint8_t &aValue) const otError error = OT_ERROR_NONE; uint32_t value; - SuccessOrExit(error = ParseUint32(aName, value)); - VerifyOrExit(value <= UINT8_MAX, error = OT_ERROR_INVALID_ARGS); + EXPECT_NO_ERROR(error = ParseUint32(aName, value)); + EXPECT(value <= UINT8_MAX, error = OT_ERROR_INVALID_ARGS); aValue = static_cast(value); exit: @@ -166,10 +166,10 @@ otError Url::ParseInt32(const char *aName, int32_t &aValue) const const char *str; long long value; - VerifyOrExit((str = GetValue(aName)) != nullptr, error = OT_ERROR_NOT_FOUND); + EXPECT((str = GetValue(aName)) != nullptr, error = OT_ERROR_NOT_FOUND); value = strtoll(str, nullptr, 0); - VerifyOrExit(INT32_MIN <= value && value <= INT32_MAX, error = OT_ERROR_INVALID_ARGS); + EXPECT(INT32_MIN <= value && value <= INT32_MAX, error = OT_ERROR_INVALID_ARGS); aValue = static_cast(value); exit: @@ -181,8 +181,8 @@ otError Url::ParseInt16(const char *aName, int16_t &aValue) const otError error = OT_ERROR_NONE; int32_t value; - SuccessOrExit(error = ParseInt32(aName, value)); - VerifyOrExit(INT16_MIN <= value && value <= INT16_MAX, error = OT_ERROR_INVALID_ARGS); + EXPECT_NO_ERROR(error = ParseInt32(aName, value)); + EXPECT(INT16_MIN <= value && value <= INT16_MAX, error = OT_ERROR_INVALID_ARGS); aValue = static_cast(value); exit: @@ -194,8 +194,8 @@ otError Url::ParseInt8(const char *aName, int8_t &aValue) const otError error = OT_ERROR_NONE; int32_t value; - SuccessOrExit(error = ParseInt32(aName, value)); - VerifyOrExit(INT8_MIN <= value && value <= INT8_MAX, error = OT_ERROR_INVALID_ARGS); + EXPECT_NO_ERROR(error = ParseInt32(aName, value)); + EXPECT(INT8_MIN <= value && value <= INT8_MAX, error = OT_ERROR_INVALID_ARGS); aValue = static_cast(value); exit: diff --git a/src/lib/utils/math.hpp b/src/lib/utils/math.hpp new file mode 100644 index 000000000..2b018ed29 --- /dev/null +++ b/src/lib/utils/math.hpp @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2024, The OpenThread Authors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @file + * This file includes definitions for generic number utility functions (min, max). + */ + +#ifndef LIB_UTILS_MATH_HPP_ +#define LIB_UTILS_MATH_HPP_ + +namespace ot { +namespace Lib { +namespace Utils { + +/** + * This template function returns the minimum of two given values. + * + * Uses `operator<` to compare the values. + * + * @tparam Type The value type. + * + * @param[in] aFirst The first value. + * @param[in] aSecond The second value. + * + * @returns The minimum of @p aFirst and @p aSecond. + * + */ +template Type Min(Type aFirst, Type aSecond) { return (aFirst < aSecond) ? aFirst : aSecond; } + +/** + * This template function returns the maximum of two given values. + * + * Uses `operator<` to compare the values. + * + * @tparam Type The value type. + * + * @param[in] aFirst The first value. + * @param[in] aSecond The second value. + * + * @returns The maximum of @p aFirst and @p aSecond. + * + */ +template Type Max(Type aFirst, Type aSecond) { return (aFirst < aSecond) ? aSecond : aFirst; } + +/** + * Casts a given `uint32_t` to `unsigned long`. + * + * @param[in] aUint32 A `uint32_t` value. + * + * @returns The @p aUint32 value as `unsigned long`. + * + */ +inline unsigned long ToUlong(uint32_t aUint32) { return static_cast(aUint32); } + +} // namespace Utils +} // namespace Lib +} // namespace ot + +#endif // LIB_UTILS_MATH_HPP_ diff --git a/src/lib/utils/utils.hpp b/src/lib/utils/utils.hpp new file mode 100644 index 000000000..5ee46d192 --- /dev/null +++ b/src/lib/utils/utils.hpp @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2024, The OpenThread Authors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @file + * This file includes macros for validating runtime conditions. + * + * The macros in this file should be exclusively used by code under 'lib'. It's RECOMMENDED that only + * include this file in sources under 'lib' and not include this file in headers under 'lib'. Because + * headers under 'lib' may be included externally and the common macros may cause redefinition. + * + */ + +#ifndef LIB_UTILS_CODE_UTILS_HPP_ +#define LIB_UTILS_CODE_UTILS_HPP_ + +#include +#include + +/** + * Checks for the specified status, which is expected to commonly be successful, and branches to the local + * label 'exit' if the status is unsuccessful. + * + * @param[in] aStatus A scalar status to be evaluated against zero (0). + * + */ +#define EXPECT_NO_ERROR(aStatus) \ + do \ + { \ + if ((aStatus) != 0) \ + { \ + goto exit; \ + } \ + } while (false) + +/** + * Does nothing. This is passed to EXPECT when there is no action to do. + * + */ +#define NO_ACTION + +/** + * Checks for the specified condition, which is expected to commonly be true, and both executes @a ... and + * branches to the local label 'exit' if the condition is false. + * + * @param[in] aCondition A Boolean expression to be evaluated. + * @param[in] aAction An optional expression or block to execute when the assertion fails. + * + */ +#define EXPECT(aCondition, aAction) \ + do \ + { \ + if (!(aCondition)) \ + { \ + aAction; \ + goto exit; \ + } \ + } while (false) + +/** + * Unconditionally executes @a ... and branches to the local label 'exit'. + * + * @note The use of this interface implies neither success nor failure for the overall exit status of the enclosing + * function body. + * + * @param[in] ... An optional expression or block to execute when the assertion fails. + * + */ +#define EXIT_NOW(...) \ + do \ + { \ + __VA_ARGS__; \ + goto exit; \ + } while (false) + +/** + * Executes the `statement` and ignores the return value. + * + * This is primarily used to indicate the intention of developer that the return value of a function/method can be + * safely ignored. + * + * @param[in] aStatement The function/method to execute. + * + */ +#define IGNORE_RETURN(aStatement) \ + do \ + { \ + if (aStatement) \ + { \ + } \ + } while (false) + +/** + * Overload the new operator to new an object at a specific address. + * + * @param[in] p The pointer of the address. + * + */ +inline void *operator new(size_t, void *p) throw() { return p; } + +#endif // LIB_UTILS_CODE_UTILS_HPP_ diff --git a/src/posix/platform/spi_interface.cpp b/src/posix/platform/spi_interface.cpp index 9d7860b34..f3078b46c 100644 --- a/src/posix/platform/spi_interface.cpp +++ b/src/posix/platform/spi_interface.cpp @@ -54,6 +54,8 @@ #include #include +#include "common/code_utils.hpp" + #if OPENTHREAD_POSIX_CONFIG_SPINEL_SPI_INTERFACE_ENABLE #include #include diff --git a/src/posix/platform/spinel_manager.hpp b/src/posix/platform/spinel_manager.hpp index 1922c1e6b..4ea9f87e4 100644 --- a/src/posix/platform/spinel_manager.hpp +++ b/src/posix/platform/spinel_manager.hpp @@ -29,6 +29,8 @@ #ifndef POSIX_PLATFORM_SPINEL_MANAGER_HPP_ #define POSIX_PLATFORM_SPINEL_MANAGER_HPP_ +#include + #include "common/code_utils.hpp" #include "lib/spinel/spinel_driver.hpp" #include "posix/platform/hdlc_interface.hpp" @@ -92,7 +94,7 @@ public: */ Spinel::SpinelInterface &GetSpinelInterface(void) { - OT_ASSERT(mSpinelInterface != nullptr); + assert(mSpinelInterface != nullptr); return *mSpinelInterface; } diff --git a/src/posix/platform/vendor_interface_example.cpp b/src/posix/platform/vendor_interface_example.cpp index da026b590..a4f6c0f34 100644 --- a/src/posix/platform/vendor_interface_example.cpp +++ b/src/posix/platform/vendor_interface_example.cpp @@ -36,6 +36,7 @@ #if OPENTHREAD_POSIX_CONFIG_SPINEL_VENDOR_INTERFACE_ENABLE #include "vendor_interface.hpp" +#include "common/code_utils.hpp" #include "common/new.hpp" namespace ot {