From 686eb30e9a0f069dcc24640cc816768c92ace798 Mon Sep 17 00:00:00 2001 From: Abtin Keshavarzian Date: Thu, 1 Feb 2024 11:58:47 -0800 Subject: [PATCH] [common] add `ClearAllBytes()` template function (#9818) This commit introduces the `ClearAllBytes()` template function to zero out all bytes within an object. This replaces `memset(0)` calls in OT core modules, simplifying code and improving safety by automatically using the correct object size. --- src/cli/cli.cpp | 10 +++++----- src/cli/cli_coap.cpp | 26 +++++++++++++------------- src/cli/cli_coap_secure.cpp | 10 +++++----- src/cli/cli_commissioner.cpp | 4 ++-- src/cli/cli_dataset.cpp | 10 +++++----- src/cli/cli_dns.cpp | 2 +- src/cli/cli_joiner.cpp | 2 +- src/cli/cli_link_metrics.cpp | 6 +++--- src/cli/cli_output.hpp | 16 ++++++++++++++++ src/cli/cli_ping.cpp | 2 +- src/cli/cli_tcp.cpp | 4 ++-- src/cli/cli_udp.cpp | 4 ++-- src/core/common/clearable.hpp | 19 ++++++++++++++++++- src/core/common/message.cpp | 2 +- src/core/common/settings.hpp | 4 ++-- src/core/diags/factory_diags.hpp | 5 ++--- src/core/mac/mac.cpp | 4 ++-- src/core/mac/mac.hpp | 3 ++- src/core/mac/mac_frame.cpp | 4 ++-- src/core/meshcop/commissioner.cpp | 4 ++-- src/core/meshcop/dataset.cpp | 2 +- src/core/meshcop/dataset_local.cpp | 2 +- src/core/meshcop/joiner.cpp | 2 +- src/core/meshcop/meshcop.cpp | 5 +++-- src/core/meshcop/secure_transport.cpp | 17 +++++++++-------- src/core/net/dhcp6_client.cpp | 2 +- src/core/net/dhcp6_server.cpp | 2 +- src/core/net/dns_client.cpp | 4 ++-- src/core/net/ip6.hpp | 2 +- src/core/net/ip6_mpl.cpp | 2 +- src/core/net/tcp6.cpp | 14 +++++++------- src/core/radio/trel_link.cpp | 6 +++--- src/core/thread/child.cpp | 4 ++-- src/core/thread/discover_scanner.cpp | 2 +- src/core/thread/mesh_forwarder.hpp | 2 +- src/core/thread/mle.cpp | 4 ++-- src/core/thread/mle_tlvs.cpp | 3 ++- src/core/thread/mle_types.hpp | 8 +------- src/core/thread/network_diagnostic.cpp | 2 +- src/core/thread/radio_selector.cpp | 2 +- src/core/thread/router.cpp | 4 ++-- src/core/thread/router_table.hpp | 3 +-- src/core/utils/channel_monitor.cpp | 4 ++-- src/core/utils/history_tracker.cpp | 2 +- src/core/utils/slaac_address.cpp | 2 +- 45 files changed, 136 insertions(+), 107 deletions(-) diff --git a/src/cli/cli.cpp b/src/cli/cli.cpp index 78c1ee807..454033409 100644 --- a/src/cli/cli.cpp +++ b/src/cli/cli.cpp @@ -163,7 +163,7 @@ Interpreter::Interpreter(Instance *aInstance, otCliOutputCallback aCallback, voi #if (OPENTHREAD_FTD || OPENTHREAD_MTD) && OPENTHREAD_CONFIG_CLI_REGISTER_IP6_RECV_CALLBACK otIp6SetReceiveCallback(GetInstancePtr(), &Interpreter::HandleIp6Receive, this); #endif - memset(&mUserCommands, 0, sizeof(mUserCommands)); + ClearAllBytes(mUserCommands); OutputPrompt(); } @@ -2668,7 +2668,7 @@ template <> otError Interpreter::Process(Arg aArgs[]) otCacheEntryIterator iterator; otCacheEntryInfo entry; - memset(&iterator, 0, sizeof(iterator)); + ClearAllBytes(iterator); while (true) { @@ -4078,7 +4078,7 @@ template <> otError Interpreter::Process(Arg aArgs[]) otError error = OT_ERROR_NONE; otLinkModeConfig linkMode; - memset(&linkMode, 0, sizeof(otLinkModeConfig)); + ClearAllBytes(linkMode); if (aArgs[0].IsEmpty()) { @@ -5662,7 +5662,7 @@ otError Interpreter::ParsePrefix(Arg aArgs[], otBorderRouterConfig &aConfig) { otError error = OT_ERROR_NONE; - memset(&aConfig, 0, sizeof(otBorderRouterConfig)); + ClearAllBytes(aConfig); SuccessOrExit(error = aArgs[0].ParseAsIp6Prefix(aConfig.mPrefix)); aArgs++; @@ -6089,7 +6089,7 @@ otError Interpreter::ParseRoute(Arg aArgs[], otExternalRouteConfig &aConfig) { otError error = OT_ERROR_NONE; - memset(&aConfig, 0, sizeof(otExternalRouteConfig)); + ClearAllBytes(aConfig); SuccessOrExit(error = aArgs[0].ParseAsIp6Prefix(aConfig.mPrefix)); aArgs++; diff --git a/src/cli/cli_coap.cpp b/src/cli/cli_coap.cpp index 7f7178151..f69800b8e 100644 --- a/src/cli/cli_coap.cpp +++ b/src/cli/cli_coap.cpp @@ -58,15 +58,15 @@ Coap::Coap(otInstance *aInstance, OutputImplementer &aOutputImplementer) , mBlockCount(1) #endif { - memset(&mResource, 0, sizeof(mResource)); + ClearAllBytes(mResource); #if OPENTHREAD_CONFIG_COAP_OBSERVE_API_ENABLE - memset(&mRequestAddr, 0, sizeof(mRequestAddr)); - memset(&mSubscriberSock, 0, sizeof(mSubscriberSock)); - memset(&mRequestToken, 0, sizeof(mRequestToken)); - memset(&mSubscriberToken, 0, sizeof(mSubscriberToken)); - memset(&mRequestUri, 0, sizeof(mRequestUri)); + ClearAllBytes(mRequestAddr); + ClearAllBytes(mSubscriberSock); + ClearAllBytes(mRequestToken); + ClearAllBytes(mSubscriberToken); + ClearAllBytes(mRequestUri); #endif - memset(&mUriPath, 0, sizeof(mUriPath)); + ClearAllBytes(mUriPath); strncpy(mResourceContent, "0", sizeof(mResourceContent)); mResourceContent[sizeof(mResourceContent) - 1] = '\0'; } @@ -78,7 +78,7 @@ otError Coap::CancelResourceSubscription(void) otMessage *message = nullptr; otMessageInfo messageInfo; - memset(&messageInfo, 0, sizeof(messageInfo)); + ClearAllBytes(messageInfo); messageInfo.mPeerAddr = mRequestAddr; messageInfo.mPeerPort = OT_DEFAULT_COAP_PORT; @@ -94,8 +94,8 @@ otError Coap::CancelResourceSubscription(void) SuccessOrExit(error = otCoapMessageAppendUriPathOptions(message, mRequestUri)); SuccessOrExit(error = otCoapSendRequest(GetInstancePtr(), message, &messageInfo, &Coap::HandleResponse, this)); - memset(&mRequestAddr, 0, sizeof(mRequestAddr)); - memset(&mRequestUri, 0, sizeof(mRequestUri)); + ClearAllBytes(mRequestAddr); + ClearAllBytes(mRequestUri); mRequestTokenLength = 0; exit: @@ -110,7 +110,7 @@ exit: void Coap::CancelSubscriber(void) { - memset(&mSubscriberSock, 0, sizeof(mSubscriberSock)); + ClearAllBytes(mSubscriberSock); mSubscriberTokenLength = 0; } #endif // OPENTHREAD_CONFIG_COAP_OBSERVE_API_ENABLE @@ -207,7 +207,7 @@ template <> otError Coap::Process(Arg aArgs[]) if (mSubscriberTokenLength > 0) { // Notify the subscriber - memset(&messageInfo, 0, sizeof(messageInfo)); + ClearAllBytes(messageInfo); messageInfo.mPeerAddr = mSubscriberSock.mAddress; messageInfo.mPeerPort = mSubscriberSock.mPort; @@ -494,7 +494,7 @@ otError Coap::ProcessRequest(Arg aArgs[], otCoapCode aCoapCode) SuccessOrExit(error = otMessageAppend(message, aArgs[3].GetCString(), payloadLength)); } - memset(&messageInfo, 0, sizeof(messageInfo)); + ClearAllBytes(messageInfo); messageInfo.mPeerAddr = coapDestinationIp; messageInfo.mPeerPort = OT_DEFAULT_COAP_PORT; diff --git a/src/cli/cli_coap_secure.cpp b/src/cli/cli_coap_secure.cpp index e22352ff2..d977443d1 100644 --- a/src/cli/cli_coap_secure.cpp +++ b/src/cli/cli_coap_secure.cpp @@ -56,10 +56,10 @@ CoapSecure::CoapSecure(otInstance *aInstance, OutputImplementer &aOutputImplemen , mBlockCount(1) #endif { - memset(&mResource, 0, sizeof(mResource)); - memset(&mPsk, 0, sizeof(mPsk)); - memset(&mPskId, 0, sizeof(mPskId)); - memset(&mUriPath, 0, sizeof(mUriPath)); + ClearAllBytes(mResource); + ClearAllBytes(mPsk); + ClearAllBytes(mPskId); + ClearAllBytes(mUriPath); strncpy(mResourceContent, "0", sizeof(mResourceContent)); mResourceContent[sizeof(mResourceContent) - 1] = '\0'; } @@ -398,7 +398,7 @@ template <> otError CoapSecure::Process(Arg aArgs[]) otError error; otSockAddr sockaddr; - memset(&sockaddr, 0, sizeof(sockaddr)); + ClearAllBytes(sockaddr); SuccessOrExit(error = aArgs[0].ParseAsIp6Address(sockaddr.mAddress)); sockaddr.mPort = OT_DEFAULT_COAP_SECURE_PORT; diff --git a/src/cli/cli_commissioner.cpp b/src/cli/cli_commissioner.cpp index b7c04d3b7..03aa8389a 100644 --- a/src/cli/cli_commissioner.cpp +++ b/src/cli/cli_commissioner.cpp @@ -186,7 +186,7 @@ template <> otError Commissioner::Process(Arg aArgs[]) VerifyOrExit(!aArgs[1].IsEmpty(), error = OT_ERROR_INVALID_ARGS); - memset(&discerner, 0, sizeof(discerner)); + ClearAllBytes(discerner); if (aArgs[1] == "*") { @@ -383,7 +383,7 @@ template <> otError Commissioner::Process(Arg aArgs[]) VerifyOrExit(!aArgs[0].IsEmpty(), error = OT_ERROR_INVALID_ARGS); - memset(&dataset, 0, sizeof(dataset)); + ClearAllBytes(dataset); for (; !aArgs->IsEmpty(); aArgs++) { diff --git a/src/cli/cli_dataset.cpp b/src/cli/cli_dataset.cpp index 32a4372ec..cfd47a18c 100644 --- a/src/cli/cli_dataset.cpp +++ b/src/cli/cli_dataset.cpp @@ -526,7 +526,7 @@ otError Dataset::ProcessCommand(const ComponentMapper &aMapper, Arg aArgs[]) } else { - memset(&dataset, 0, sizeof(dataset)); + ClearAllBytes(dataset); SuccessOrExit(error = (this->*aMapper.mParse)(aArgs, dataset)); dataset.mComponents.*aMapper.mIsPresentPtr = true; SuccessOrExit(error = otDatasetUpdateTlvs(&dataset, &sDatasetTlvs)); @@ -716,7 +716,7 @@ template <> otError Dataset::Process(Arg aArgs[]) { OT_UNUSED_VARIABLE(aArgs); - memset(&sDatasetTlvs, 0, sizeof(sDatasetTlvs)); + ClearAllBytes(sDatasetTlvs); return OT_ERROR_NONE; } @@ -765,7 +765,7 @@ template <> otError Dataset::Process(Arg aArgs[]) uint8_t tlvs[128]; uint8_t tlvsLength = 0; - memset(&dataset, 0, sizeof(dataset)); + ClearAllBytes(dataset); for (Arg *arg = &aArgs[1]; !arg->IsEmpty();) { @@ -853,7 +853,7 @@ template <> otError Dataset::Process(Arg aArgs[]) bool destAddrSpecified = false; otIp6Address address; - memset(&datasetComponents, 0, sizeof(datasetComponents)); + ClearAllBytes(datasetComponents); for (Arg *arg = &aArgs[1]; !arg->IsEmpty(); arg++) { @@ -1003,7 +1003,7 @@ otError Dataset::ParseSecurityPolicy(otSecurityPolicy &aSecurityPolicy, Arg *&aA otSecurityPolicy policy; uint8_t versionThreshold; - memset(&policy, 0, sizeof(policy)); + ClearAllBytes(policy); SuccessOrExit(error = aArgs->ParseAsUint16(policy.mRotationTime)); aArgs++; diff --git a/src/cli/cli_dns.cpp b/src/cli/cli_dns.cpp index c532a0f6f..7aef47976 100644 --- a/src/cli/cli_dns.cpp +++ b/src/cli/cli_dns.cpp @@ -418,7 +418,7 @@ otError Dns::GetDnsConfig(Arg aArgs[], otDnsQueryConfig *&aConfig) bool recursionDesired; bool nat64SynthesizedAddress; - memset(aConfig, 0, sizeof(otDnsQueryConfig)); + ClearAllBytes(*aConfig); VerifyOrExit(!aArgs[0].IsEmpty(), aConfig = nullptr); diff --git a/src/cli/cli_joiner.cpp b/src/cli/cli_joiner.cpp index cf84968ed..805087989 100644 --- a/src/cli/cli_joiner.cpp +++ b/src/cli/cli_joiner.cpp @@ -78,7 +78,7 @@ template <> otError Joiner::Process(Arg aArgs[]) { otJoinerDiscerner discerner; - memset(&discerner, 0, sizeof(discerner)); + ClearAllBytes(discerner); /** * @cli joiner discerner clear diff --git a/src/cli/cli_link_metrics.cpp b/src/cli/cli_link_metrics.cpp index b8c284611..93cc8c575 100644 --- a/src/cli/cli_link_metrics.cpp +++ b/src/cli/cli_link_metrics.cpp @@ -138,7 +138,7 @@ template <> otError LinkMetrics::Process(Arg aArgs[]) SuccessOrExit(error = aArgs[0].ParseAsIp6Address(address)); - memset(&seriesFlags, 0, sizeof(otLinkMetricsSeriesFlags)); + ClearAllBytes(seriesFlags); /** * @cli linkmetrics mgmt forward @@ -171,7 +171,7 @@ template <> otError LinkMetrics::Process(Arg aArgs[]) uint8_t seriesId; otLinkMetrics linkMetrics; - memset(&linkMetrics, 0, sizeof(otLinkMetrics)); + ClearAllBytes(linkMetrics); SuccessOrExit(error = aArgs[2].ParseAsUint8(seriesId)); VerifyOrExit(!aArgs[3].IsEmpty(), error = OT_ERROR_INVALID_ARGS); @@ -368,7 +368,7 @@ otError LinkMetrics::ParseLinkMetricsFlags(otLinkMetrics &aLinkMetrics, const Ar VerifyOrExit(!aFlags.IsEmpty(), error = OT_ERROR_INVALID_ARGS); - memset(&aLinkMetrics, 0, sizeof(aLinkMetrics)); + ClearAllBytes(aLinkMetrics); for (const char *arg = aFlags.GetCString(); *arg != '\0'; arg++) { diff --git a/src/cli/cli_output.hpp b/src/cli/cli_output.hpp index 8941f7e57..3029108cf 100644 --- a/src/cli/cli_output.hpp +++ b/src/cli/cli_output.hpp @@ -45,6 +45,7 @@ #include "common/binary_search.hpp" #include "common/num_utils.hpp" #include "common/string.hpp" +#include "common/type_traits.hpp" #include "utils/parse_cmdline.hpp" namespace ot { @@ -527,6 +528,21 @@ public: } } + /** + * Clears (sets to zero) all bytes of a given object. + * + * @tparam ObjectType The object type. + * + * @param[in] aObject A reference to the object of type `ObjectType` to clear all its bytes. + * + */ + template static void ClearAllBytes(ObjectType &aObject) + { + static_assert(!TypeTraits::IsPointer::kValue, "ObjectType must not be a pointer"); + + memset(reinterpret_cast(&aObject), 0, sizeof(ObjectType)); + } + protected: void OutputFormatV(const char *aFormat, va_list aArguments); diff --git a/src/cli/cli_ping.cpp b/src/cli/cli_ping.cpp index 80868c789..e8e762157 100644 --- a/src/cli/cli_ping.cpp +++ b/src/cli/cli_ping.cpp @@ -78,7 +78,7 @@ otError PingSender::Process(Arg aArgs[]) aArgs++; } - memset(&config, 0, sizeof(config)); + ClearAllBytes(config); if (aArgs[0] == "-I") { diff --git a/src/cli/cli_tcp.cpp b/src/cli/cli_tcp.cpp index 4f3a8d5c7..eadb27bb8 100644 --- a/src/cli/cli_tcp.cpp +++ b/src/cli/cli_tcp.cpp @@ -219,7 +219,7 @@ template <> otError TcpExample::Process(Arg aArgs[]) { otTcpEndpointInitializeArgs endpointArgs; - memset(&endpointArgs, 0x00, sizeof(endpointArgs)); + ClearAllBytes(endpointArgs); endpointArgs.mEstablishedCallback = HandleTcpEstablishedCallback; if (mUseCircularSendBuffer) { @@ -241,7 +241,7 @@ template <> otError TcpExample::Process(Arg aArgs[]) { otTcpListenerInitializeArgs listenerArgs; - memset(&listenerArgs, 0x00, sizeof(listenerArgs)); + ClearAllBytes(listenerArgs); listenerArgs.mAcceptReadyCallback = HandleTcpAcceptReadyCallback; listenerArgs.mAcceptDoneCallback = HandleTcpAcceptDoneCallback; listenerArgs.mContext = this; diff --git a/src/cli/cli_udp.cpp b/src/cli/cli_udp.cpp index 1651debb2..711456416 100644 --- a/src/cli/cli_udp.cpp +++ b/src/cli/cli_udp.cpp @@ -47,7 +47,7 @@ UdpExample::UdpExample(otInstance *aInstance, OutputImplementer &aOutputImplemen : Output(aInstance, aOutputImplementer) , mLinkSecurityEnabled(true) { - memset(&mSocket, 0, sizeof(mSocket)); + ClearAllBytes(mSocket); } /** @@ -258,7 +258,7 @@ template <> otError UdpExample::Process(Arg aArgs[]) otMessageInfo messageInfo; otMessageSettings messageSettings = {mLinkSecurityEnabled, OT_MESSAGE_PRIORITY_NORMAL}; - memset(&messageInfo, 0, sizeof(messageInfo)); + ClearAllBytes(messageInfo); // Possible argument formats: // diff --git a/src/core/common/clearable.hpp b/src/core/common/clearable.hpp index f91c15f41..bc1b1f637 100644 --- a/src/core/common/clearable.hpp +++ b/src/core/common/clearable.hpp @@ -38,8 +38,25 @@ #include +#include "common/type_traits.hpp" + namespace ot { +/** + * Clears (sets to zero) all bytes of a given object. + * + * @tparam ObjectType The object type. + * + * @param[in] aObject A reference to the object of type `ObjectType` to clear all its bytes. + * + */ +template void ClearAllBytes(ObjectType &aObject) +{ + static_assert(!TypeTraits::IsPointer::kValue, "ObjectType must not be a pointer"); + + memset(reinterpret_cast(&aObject), 0, sizeof(ObjectType)); +} + /** * Defines a `Clearable` object which provides `Clear()` method. * @@ -52,7 +69,7 @@ namespace ot { template class Clearable { public: - void Clear(void) { memset(reinterpret_cast(static_cast(this)), 0, sizeof(Type)); } + void Clear(void) { ClearAllBytes(*static_cast(this)); } }; } // namespace ot diff --git a/src/core/common/message.cpp b/src/core/common/message.cpp index 1c7028d0f..50e1fcc45 100644 --- a/src/core/common/message.cpp +++ b/src/core/common/message.cpp @@ -75,7 +75,7 @@ Message *MessagePool::Allocate(Message::Type aType, uint16_t aReserveHeader, con VerifyOrExit((message = static_cast(NewBuffer(aSettings.GetPriority()))) != nullptr); - memset(message, 0, sizeof(*message)); + ClearAllBytes(*message); message->SetMessagePool(this); message->SetType(aType); message->SetReserved(aReserveHeader); diff --git a/src/core/common/settings.hpp b/src/core/common/settings.hpp index 9716cb87a..1f5a33adb 100644 --- a/src/core/common/settings.hpp +++ b/src/core/common/settings.hpp @@ -417,7 +417,7 @@ public: */ void Init(void) { - memset(this, 0, sizeof(*this)); + ClearAllBytes(*this); SetVersion(kThreadVersion1p1); } @@ -784,7 +784,7 @@ public: * Initializes the `BorderAgentId` object. * */ - void Init(void) { memset(&mId, 0, sizeof(mId)); } + void Init(void) { ClearAllBytes(mId); } /** * Returns the Border Agent ID. diff --git a/src/core/diags/factory_diags.hpp b/src/core/diags/factory_diags.hpp index 5d015d278..1b72a1563 100644 --- a/src/core/diags/factory_diags.hpp +++ b/src/core/diags/factory_diags.hpp @@ -42,6 +42,7 @@ #include +#include "common/clearable.hpp" #include "common/error.hpp" #include "common/locator.hpp" #include "common/non_copyable.hpp" @@ -131,10 +132,8 @@ private: Error (Diags::*mCommand)(uint8_t aArgsLength, char *aArgs[], char *aOutput, size_t aOutputMaxLen); }; - struct Stats + struct Stats : public Clearable { - void Clear(void) { memset(this, 0, sizeof(*this)); } - uint32_t mReceivedPackets; uint32_t mSentPackets; int8_t mFirstRssi; diff --git a/src/core/mac/mac.cpp b/src/core/mac/mac.cpp index 15f560631..04e235cc5 100644 --- a/src/core/mac/mac.cpp +++ b/src/core/mac/mac.cpp @@ -234,7 +234,7 @@ Error Mac::ConvertBeaconToActiveScanResult(const RxFrame *aBeaconFrame, ActiveSc uint16_t payloadLength; #endif - memset(&aResult, 0, sizeof(ActiveScanResult)); + ClearAllBytes(aResult); VerifyOrExit(aBeaconFrame != nullptr, error = kErrorInvalidArgs); @@ -2153,7 +2153,7 @@ const uint32_t *Mac::GetIndirectRetrySuccessHistogram(uint8_t &aNumberOfEntries) } #endif -void Mac::ResetRetrySuccessHistogram() { memset(&mRetryHistogram, 0, sizeof(mRetryHistogram)); } +void Mac::ResetRetrySuccessHistogram() { ClearAllBytes(mRetryHistogram); } #endif // OPENTHREAD_CONFIG_MAC_RETRY_SUCCESS_HISTOGRAM_ENABLE uint8_t Mac::ComputeLinkMargin(int8_t aRss) const { return ot::ComputeLinkMargin(GetNoiseFloor(), aRss); } diff --git a/src/core/mac/mac.hpp b/src/core/mac/mac.hpp index 1b2ae6c67..6f95ab7d3 100644 --- a/src/core/mac/mac.hpp +++ b/src/core/mac/mac.hpp @@ -39,6 +39,7 @@ #include #include +#include "common/clearable.hpp" #include "common/locator.hpp" #include "common/log.hpp" #include "common/non_copyable.hpp" @@ -496,7 +497,7 @@ public: * Resets mac counters * */ - void ResetCounters(void) { memset(&mCounters, 0, sizeof(mCounters)); } + void ResetCounters(void) { ClearAllBytes(mCounters); } /** * Returns the MAC counter. diff --git a/src/core/mac/mac_frame.cpp b/src/core/mac/mac_frame.cpp index 47debefb3..3e84465be 100644 --- a/src/core/mac/mac_frame.cpp +++ b/src/core/mac/mac_frame.cpp @@ -1385,7 +1385,7 @@ void TxFrame::GenerateImmAck(const RxFrame &aFrame, bool aIsFramePending) uint16_t fcf = static_cast(kTypeAck) | aFrame.GetVersion(); mChannel = aFrame.mChannel; - memset(&mInfo.mTxInfo, 0, sizeof(mInfo.mTxInfo)); + ClearAllBytes(mInfo.mTxInfo); if (aIsFramePending) { @@ -1449,7 +1449,7 @@ Error TxFrame::GenerateEnhAck(const RxFrame &aRxFrame, bool aIsFramePending, con // Prepare the ack frame mChannel = aRxFrame.mChannel; - memset(&mInfo.mTxInfo, 0, sizeof(mInfo.mTxInfo)); + ClearAllBytes(mInfo.mTxInfo); InitMacHeader(kTypeAck, kVersion2015, addrs, panIds, static_cast(securityLevel), static_cast(keyIdMode)); diff --git a/src/core/meshcop/commissioner.cpp b/src/core/meshcop/commissioner.cpp index 3009a4742..92a52c12e 100644 --- a/src/core/meshcop/commissioner.cpp +++ b/src/core/meshcop/commissioner.cpp @@ -72,7 +72,7 @@ Commissioner::Commissioner(Instance &aInstance) , mPanIdQuery(aInstance) , mState(kStateDisabled) { - memset(reinterpret_cast(mJoiners), 0, sizeof(mJoiners)); + ClearAllBytes(mJoiners); mCommissionerAloc.InitAsThreadOriginMeshLocal(); mCommissionerAloc.mPreferred = true; @@ -476,7 +476,7 @@ exit: void Commissioner::Joiner::CopyToJoinerInfo(otJoinerInfo &aJoiner) const { - memset(&aJoiner, 0, sizeof(aJoiner)); + ClearAllBytes(aJoiner); switch (mType) { diff --git a/src/core/meshcop/dataset.cpp b/src/core/meshcop/dataset.cpp index b15a40720..15c547ba9 100644 --- a/src/core/meshcop/dataset.cpp +++ b/src/core/meshcop/dataset.cpp @@ -159,7 +159,7 @@ Dataset::Dataset(void) : mUpdateTime(0) , mLength(0) { - memset(mTlvs, 0, sizeof(mTlvs)); + ClearAllBytes(mTlvs); } void Dataset::Clear(void) { mLength = 0; } diff --git a/src/core/meshcop/dataset_local.cpp b/src/core/meshcop/dataset_local.cpp index 4c971c7bb..edb810871 100644 --- a/src/core/meshcop/dataset_local.cpp +++ b/src/core/meshcop/dataset_local.cpp @@ -152,7 +152,7 @@ Error DatasetLocal::Read(otOperationalDatasetTlvs &aDataset) const Dataset dataset; Error error; - memset(&aDataset, 0, sizeof(aDataset)); + ClearAllBytes(aDataset); SuccessOrExit(error = Read(dataset)); dataset.ConvertTo(aDataset); diff --git a/src/core/meshcop/joiner.cpp b/src/core/meshcop/joiner.cpp index 50b02e923..fb0f3e61c 100644 --- a/src/core/meshcop/joiner.cpp +++ b/src/core/meshcop/joiner.cpp @@ -68,7 +68,7 @@ Joiner::Joiner(Instance &aInstance) { SetIdFromIeeeEui64(); mDiscerner.Clear(); - memset(mJoinerRouters, 0, sizeof(mJoinerRouters)); + ClearAllBytes(mJoinerRouters); } void Joiner::SetIdFromIeeeEui64(void) diff --git a/src/core/meshcop/meshcop.cpp b/src/core/meshcop/meshcop.cpp index d2d14c321..b30fe274c 100644 --- a/src/core/meshcop/meshcop.cpp +++ b/src/core/meshcop/meshcop.cpp @@ -34,6 +34,7 @@ #include "meshcop.hpp" +#include "common/clearable.hpp" #include "common/crc16.hpp" #include "common/debug.hpp" #include "common/locator_getters.hpp" @@ -191,7 +192,7 @@ void SteeringData::Init(uint8_t aLength) { OT_ASSERT(aLength <= kMaxLength); mLength = aLength; - memset(m8, 0, sizeof(m8)); + ClearAllBytes(m8); } void SteeringData::SetToPermitAllJoiners(void) @@ -324,7 +325,7 @@ Error GeneratePskc(const char *aPassPhrase, (networkNameLen <= OT_NETWORK_NAME_MAX_SIZE), error = kErrorInvalidArgs); - memset(salt, 0, sizeof(salt)); + ClearAllBytes(salt); memcpy(salt, saltPrefix, sizeof(saltPrefix) - 1); saltLen += static_cast(sizeof(saltPrefix) - 1); diff --git a/src/core/meshcop/secure_transport.cpp b/src/core/meshcop/secure_transport.cpp index acb7b5d96..530ba5cea 100644 --- a/src/core/meshcop/secure_transport.cpp +++ b/src/core/meshcop/secure_transport.cpp @@ -41,6 +41,7 @@ #include #include "common/as_core_type.hpp" +#include "common/clearable.hpp" #include "common/code_utils.hpp" #include "common/debug.hpp" #include "common/encoding.hpp" @@ -105,19 +106,19 @@ SecureTransport::SecureTransport(Instance &aInstance, bool aLayerTwoSecurity, bo mOwnCertLength = 0; mPrivateKeySrc = nullptr; mPrivateKeyLength = 0; - memset(&mCaChain, 0, sizeof(mCaChain)); - memset(&mOwnCert, 0, sizeof(mOwnCert)); - memset(&mPrivateKey, 0, sizeof(mPrivateKey)); + ClearAllBytes(mCaChain); + ClearAllBytes(mOwnCert); + ClearAllBytes(mPrivateKey); #endif #endif - memset(mCipherSuites, 0, sizeof(mCipherSuites)); - memset(mPsk, 0, sizeof(mPsk)); - memset(&mSsl, 0, sizeof(mSsl)); - memset(&mConf, 0, sizeof(mConf)); + ClearAllBytes(mCipherSuites); + ClearAllBytes(mPsk); + ClearAllBytes(mSsl); + ClearAllBytes(mConf); #ifdef MBEDTLS_SSL_COOKIE_C - memset(&mCookieCtx, 0, sizeof(mCookieCtx)); + ClearAllBytes(mCookieCtx); #endif } diff --git a/src/core/net/dhcp6_client.cpp b/src/core/net/dhcp6_client.cpp index 680ea049e..e206ff664 100644 --- a/src/core/net/dhcp6_client.cpp +++ b/src/core/net/dhcp6_client.cpp @@ -57,7 +57,7 @@ Client::Client(Instance &aInstance) , mStartTime(0) , mIdentityAssociationCurrent(nullptr) { - memset(mIdentityAssociations, 0, sizeof(mIdentityAssociations)); + ClearAllBytes(mIdentityAssociations); } bool Client::MatchNetifAddressWithPrefix(const Ip6::Netif::UnicastAddress &aNetifAddress, const Ip6::Prefix &aIp6Prefix) diff --git a/src/core/net/dhcp6_server.cpp b/src/core/net/dhcp6_server.cpp index c268e1c6f..7fd072cf4 100644 --- a/src/core/net/dhcp6_server.cpp +++ b/src/core/net/dhcp6_server.cpp @@ -56,7 +56,7 @@ Server::Server(Instance &aInstance) , mPrefixAgentsCount(0) , mPrefixAgentsMask(0) { - memset(mPrefixAgents, 0, sizeof(mPrefixAgents)); + ClearAllBytes(mPrefixAgents); } Error Server::UpdateService(void) diff --git a/src/core/net/dns_client.cpp b/src/core/net/dns_client.cpp index 366a657a4..95a87b7bf 100644 --- a/src/core/net/dns_client.cpp +++ b/src/core/net/dns_client.cpp @@ -799,7 +799,7 @@ Error Client::InitTcpSocket(void) Error error; otTcpEndpointInitializeArgs endpointArgs; - memset(&endpointArgs, 0x00, sizeof(endpointArgs)); + ClearAllBytes(endpointArgs); endpointArgs.mSendDoneCallback = HandleTcpSendDoneCallback; endpointArgs.mEstablishedCallback = HandleTcpEstablishedCallback; endpointArgs.mReceiveAvailableCallback = HandleTcpReceiveAvailableCallback; @@ -1634,7 +1634,7 @@ void Client::ResolveHostAddressIfNeeded(Query &aQuery, const Message &aResponseM PopulateResponse(response, aQuery, aResponseMessage); - memset(&serviceInfo, 0, sizeof(serviceInfo)); + ClearAllBytes(serviceInfo); serviceInfo.mHostNameBuffer = hostName; serviceInfo.mHostNameBufferSize = sizeof(hostName); SuccessOrExit(response.ReadServiceInfo(Response::kAnswerSection, Name(aQuery, kNameOffsetInQuery), serviceInfo)); diff --git a/src/core/net/ip6.hpp b/src/core/net/ip6.hpp index 1c700b590..53330b359 100644 --- a/src/core/net/ip6.hpp +++ b/src/core/net/ip6.hpp @@ -350,7 +350,7 @@ public: * Resets the Border Routing counters. * */ - void ResetBorderRoutingCounters(void) { memset(&mBorderRoutingCounters, 0, sizeof(mBorderRoutingCounters)); } + void ResetBorderRoutingCounters(void) { ClearAllBytes(mBorderRoutingCounters); } #endif private: diff --git a/src/core/net/ip6_mpl.cpp b/src/core/net/ip6_mpl.cpp index 78922ef6f..61be9ea11 100644 --- a/src/core/net/ip6_mpl.cpp +++ b/src/core/net/ip6_mpl.cpp @@ -52,7 +52,7 @@ Mpl::Mpl(Instance &aInstance) , mRetransmissionTimer(aInstance) #endif { - memset(mSeedSet, 0, sizeof(mSeedSet)); + ClearAllBytes(mSeedSet); } void MplOption::Init(SeedIdLength aSeedIdLength) diff --git a/src/core/net/tcp6.cpp b/src/core/net/tcp6.cpp index d9712a3c6..470e92ac5 100644 --- a/src/core/net/tcp6.cpp +++ b/src/core/net/tcp6.cpp @@ -81,7 +81,7 @@ Error Tcp::Endpoint::Initialize(Instance &aInstance, const otTcpEndpointInitiali Error error; struct tcpcb &tp = GetTcb(); - memset(&tp, 0x00, sizeof(tp)); + ClearAllBytes(tp); SuccessOrExit(error = aInstance.Get().mEndpoints.Add(*this)); @@ -92,8 +92,8 @@ Error Tcp::Endpoint::Initialize(Instance &aInstance, const otTcpEndpointInitiali mReceiveAvailableCallback = aArgs.mReceiveAvailableCallback; mDisconnectedCallback = aArgs.mDisconnectedCallback; - memset(mTimers, 0x00, sizeof(mTimers)); - memset(&mSockAddr, 0x00, sizeof(mSockAddr)); + ClearAllBytes(mTimers); + ClearAllBytes(mSockAddr); mPendingCallbacks = 0; /* @@ -549,7 +549,7 @@ Error Tcp::Listener::Initialize(Instance &aInstance, const otTcpListenerInitiali mAcceptReadyCallback = aArgs.mAcceptReadyCallback; mAcceptDoneCallback = aArgs.mAcceptDoneCallback; - memset(tpl, 0x00, sizeof(struct tcpcb_listen)); + ClearAllBytes(*tpl); tpl->instance = &aInstance; exit: @@ -579,7 +579,7 @@ Error Tcp::Listener::StopListening(void) { struct tcpcb_listen *tpl = &GetTcbListen(); - memset(&tpl->laddr, 0x00, sizeof(tpl->laddr)); + ClearAllBytes(tpl->laddr); tpl->lport = 0; tpl->t_state = TCP6S_CLOSED; return kErrorNone; @@ -670,7 +670,7 @@ Error Tcp::HandleMessage(ot::Ip6::Header &aIp6Header, Message &aMessage, Message otLinkedBuffer *priorHead = lbuf_head(&tp->sendbuf); size_t priorBacklog = endpoint->GetSendBufferBytes() - endpoint->GetInFlightBytes(); - memset(&sig, 0x00, sizeof(sig)); + ClearAllBytes(sig); nextAction = tcp_input(ip6Header, tcpHeader, &aMessage, tp, nullptr, &sig); if (nextAction != RELOOKUP_REQUIRED) { @@ -685,7 +685,7 @@ Error Tcp::HandleMessage(ot::Ip6::Header &aIp6Header, Message &aMessage, Message { struct tcpcb_listen *tpl = &listener->GetTcbListen(); - memset(&sig, 0x00, sizeof(sig)); + ClearAllBytes(sig); nextAction = tcp_input(ip6Header, tcpHeader, &aMessage, nullptr, tpl, &sig); OT_ASSERT(nextAction != RELOOKUP_REQUIRED); if (sig.accepted_connection != nullptr) diff --git a/src/core/radio/trel_link.cpp b/src/core/radio/trel_link.cpp index b97676549..0b479874a 100644 --- a/src/core/radio/trel_link.cpp +++ b/src/core/radio/trel_link.cpp @@ -55,9 +55,9 @@ Link::Link(Instance &aInstance) , mTimer(aInstance) , mInterface(aInstance) { - memset(&mTxFrame, 0, sizeof(mTxFrame)); - memset(&mRxFrame, 0, sizeof(mRxFrame)); - memset(mAckFrameBuffer, 0, sizeof(mAckFrameBuffer)); + ClearAllBytes(mTxFrame); + ClearAllBytes(mRxFrame); + ClearAllBytes(mAckFrameBuffer); mTxFrame.mPsdu = &mTxPacketBuffer[kMaxHeaderSize]; mTxFrame.SetLength(0); diff --git a/src/core/thread/child.cpp b/src/core/thread/child.cpp index 008173b6d..92a0b0566 100644 --- a/src/core/thread/child.cpp +++ b/src/core/thread/child.cpp @@ -112,14 +112,14 @@ void Child::Clear(void) { Instance &instance = GetInstance(); - memset(reinterpret_cast(this), 0, sizeof(Child)); + ClearAllBytes(*this); Init(instance); } void Child::ClearIp6Addresses(void) { mMeshLocalIid.Clear(); - memset(mIp6Address, 0, sizeof(mIp6Address)); + ClearAllBytes(mIp6Address); #if OPENTHREAD_FTD && OPENTHREAD_CONFIG_TMF_PROXY_MLR_ENABLE mMlrToRegisterMask.Clear(); mMlrRegisteredMask.Clear(); diff --git a/src/core/thread/discover_scanner.cpp b/src/core/thread/discover_scanner.cpp index e3c337cd3..3a59651d8 100644 --- a/src/core/thread/discover_scanner.cpp +++ b/src/core/thread/discover_scanner.cpp @@ -325,7 +325,7 @@ void DiscoverScanner::HandleDiscoveryResponse(Mle::RxInfo &aRxInfo) const // Find MLE Discovery TLV SuccessOrExit(error = Tlv::FindTlvValueStartEndOffsets(aRxInfo.mMessage, Tlv::kDiscovery, offset, end)); - memset(&result, 0, sizeof(result)); + ClearAllBytes(result); result.mDiscover = true; result.mPanId = linkInfo->mPanId; result.mChannel = linkInfo->mChannel; diff --git a/src/core/thread/mesh_forwarder.hpp b/src/core/thread/mesh_forwarder.hpp index a640004f9..8c3a7907c 100644 --- a/src/core/thread/mesh_forwarder.hpp +++ b/src/core/thread/mesh_forwarder.hpp @@ -306,7 +306,7 @@ public: * Resets the IP level counters. * */ - void ResetCounters(void) { memset(&mIpCounters, 0, sizeof(mIpCounters)); } + void ResetCounters(void) { ClearAllBytes(mIpCounters); } #if OPENTHREAD_CONFIG_TX_QUEUE_STATISTICS_ENABLE /** diff --git a/src/core/thread/mle.cpp b/src/core/thread/mle.cpp index 8910c35d5..ef5fe7efb 100644 --- a/src/core/thread/mle.cpp +++ b/src/core/thread/mle.cpp @@ -265,7 +265,7 @@ exit: void Mle::ResetCounters(void) { - memset(&mCounters, 0, sizeof(mCounters)); + ClearAllBytes(mCounters); #if OPENTHREAD_CONFIG_UPTIME_ENABLE mLastUpdatedTimestamp = Get().GetUptime(); #endif @@ -5097,7 +5097,7 @@ void Mle::ParentCandidate::Clear(void) { Instance &instance = GetInstance(); - memset(reinterpret_cast(this), 0, sizeof(ParentCandidate)); + ClearAllBytes(*this); Init(instance); } diff --git a/src/core/thread/mle_tlvs.cpp b/src/core/thread/mle_tlvs.cpp index f2098f175..8c0ac134b 100644 --- a/src/core/thread/mle_tlvs.cpp +++ b/src/core/thread/mle_tlvs.cpp @@ -33,6 +33,7 @@ #include "mle_tlvs.hpp" +#include "common/clearable.hpp" #include "common/code_utils.hpp" #include "common/numeric_limits.hpp" #include "radio/radio.hpp" @@ -47,7 +48,7 @@ void RouteTlv::Init(void) SetType(kRoute); SetLength(sizeof(*this) - sizeof(Tlv)); mRouterIdMask.Clear(); - memset(mRouteData, 0, sizeof(mRouteData)); + ClearAllBytes(mRouteData); } bool RouteTlv::IsValid(void) const diff --git a/src/core/thread/mle_types.hpp b/src/core/thread/mle_types.hpp index ffc6a4287..fd08cdccd 100644 --- a/src/core/thread/mle_types.hpp +++ b/src/core/thread/mle_types.hpp @@ -434,15 +434,9 @@ public: }; OT_TOOL_PACKED_BEGIN -class RouterIdSet : public Equatable +class RouterIdSet : public Equatable, public Clearable { public: - /** - * Clears the Router Id Set. - * - */ - void Clear(void) { memset(mRouterIdSet, 0, sizeof(mRouterIdSet)); } - /** * Indicates whether or not a Router ID bit is set. * diff --git a/src/core/thread/network_diagnostic.cpp b/src/core/thread/network_diagnostic.cpp index 724b6a9cb..43c1ea736 100644 --- a/src/core/thread/network_diagnostic.cpp +++ b/src/core/thread/network_diagnostic.cpp @@ -212,7 +212,7 @@ Error Server::AppendMacCounters(Message &aMessage) MacCountersTlv tlv; const otMacCounters &counters = Get().GetCounters(); - memset(&tlv, 0, sizeof(tlv)); + ClearAllBytes(tlv); tlv.Init(); tlv.SetIfInUnknownProtos(counters.mRxOther); diff --git a/src/core/thread/radio_selector.cpp b/src/core/thread/radio_selector.cpp index ea7ea74de..4268bb092 100644 --- a/src/core/thread/radio_selector.cpp +++ b/src/core/thread/radio_selector.cpp @@ -63,7 +63,7 @@ RadioSelector::RadioSelector(Instance &aInstance) void RadioSelector::NeighborInfo::PopulateMultiRadioInfo(MultiRadioInfo &aInfo) { - memset(&aInfo, 0, sizeof(MultiRadioInfo)); + ClearAllBytes(aInfo); #if OPENTHREAD_CONFIG_RADIO_LINK_IEEE_802_15_4_ENABLE if (GetSupportedRadioTypes().Contains(Mac::kRadioTypeIeee802154)) diff --git a/src/core/thread/router.cpp b/src/core/thread/router.cpp index d16d635e5..e130b69ab 100644 --- a/src/core/thread/router.cpp +++ b/src/core/thread/router.cpp @@ -71,7 +71,7 @@ void Router::Clear(void) { Instance &instance = GetInstance(); - memset(reinterpret_cast(this), 0, sizeof(Router)); + ClearAllBytes(*this); Init(instance); } @@ -92,7 +92,7 @@ void Parent::Clear(void) { Instance &instance = GetInstance(); - memset(reinterpret_cast(this), 0, sizeof(Parent)); + ClearAllBytes(*this); Init(instance); } diff --git a/src/core/thread/router_table.hpp b/src/core/thread/router_table.hpp index bf11573a2..8f2b8f207 100644 --- a/src/core/thread/router_table.hpp +++ b/src/core/thread/router_table.hpp @@ -465,7 +465,7 @@ private: void HandleTableChanged(void); void LogRouteTable(void) const; - class RouterIdMap + class RouterIdMap : public Clearable { public: // The `RouterIdMap` tracks which Router IDs are allocated. @@ -474,7 +474,6 @@ private: // remaining reuse delay time (in seconds). RouterIdMap(void) { Clear(); } - void Clear(void) { memset(mIndexes, 0, sizeof(mIndexes)); } bool IsAllocated(uint8_t aRouterId) const { return (mIndexes[aRouterId] & kAllocatedFlag); } uint8_t GetIndex(uint8_t aRouterId) const { return (mIndexes[aRouterId] & kIndexMask); } void SetIndex(uint8_t aRouterId, uint8_t aIndex) { mIndexes[aRouterId] = kAllocatedFlag | aIndex; } diff --git a/src/core/utils/channel_monitor.cpp b/src/core/utils/channel_monitor.cpp index b707a79b6..f10dd93c2 100644 --- a/src/core/utils/channel_monitor.cpp +++ b/src/core/utils/channel_monitor.cpp @@ -66,7 +66,7 @@ ChannelMonitor::ChannelMonitor(Instance &aInstance) , mSampleCount(0) , mTimer(aInstance) { - memset(mChannelOccupancy, 0, sizeof(mChannelOccupancy)); + ClearAllBytes(mChannelOccupancy); } Error ChannelMonitor::Start(void) @@ -98,7 +98,7 @@ void ChannelMonitor::Clear(void) { mChannelMaskIndex = 0; mSampleCount = 0; - memset(mChannelOccupancy, 0, sizeof(mChannelOccupancy)); + ClearAllBytes(mChannelOccupancy); LogDebg("Clearing data"); } diff --git a/src/core/utils/history_tracker.cpp b/src/core/utils/history_tracker.cpp index 74d8cfb85..1b2a4fd27 100644 --- a/src/core/utils/history_tracker.cpp +++ b/src/core/utils/history_tracker.cpp @@ -61,7 +61,7 @@ HistoryTracker::HistoryTracker(Instance &aInstance) mTimer.Start(kAgeCheckPeriod); #if OPENTHREAD_FTD && (OPENTHREAD_CONFIG_HISTORY_TRACKER_ROUTER_LIST_SIZE > 0) - memset(mRouterEntries, 0, sizeof(mRouterEntries)); + ClearAllBytes(mRouterEntries); #endif } diff --git a/src/core/utils/slaac_address.cpp b/src/core/utils/slaac_address.cpp index 7420bdf1a..f7870ee9c 100644 --- a/src/core/utils/slaac_address.cpp +++ b/src/core/utils/slaac_address.cpp @@ -56,7 +56,7 @@ Slaac::Slaac(Instance &aInstance) , mEnabled(true) , mFilter(nullptr) { - memset(mAddresses, 0, sizeof(mAddresses)); + ClearAllBytes(mAddresses); } void Slaac::Enable(void)