[log] add compile-time check for printf style arg check to log functions (#8339)

This commit adds compile-time check of format string to all log
functions and macros. It also updates different core modules to make
arg string formats consistent under different platforms. In particular
we use `'%lu` for `uint32_t` arguments and they are explicitly cast
to `unsigned long` using `ToUlong()`.
This commit is contained in:
Abtin Keshavarzian
2022-11-01 22:45:16 -07:00
committed by GitHub
parent f5acfb2dac
commit ac11f66419
28 changed files with 106 additions and 103 deletions
+4 -3
View File
@@ -92,8 +92,8 @@ void Leader::LogBackboneRouterPrimary(State aState, const BackboneRouterConfig &
if (aState != kStateRemoved && aState != kStateNone)
{
LogInfo("Rloc16: 0x%4X, seqno: %d, delay: %d, timeout %d", aConfig.mServer16, aConfig.mSequenceNumber,
aConfig.mReregistrationDelay, aConfig.mMlrTimeout);
LogInfo("Rloc16:0x%4x, seqno:%u, delay:%u, timeout:%lu", aConfig.mServer16, aConfig.mSequenceNumber,
aConfig.mReregistrationDelay, ToUlong(aConfig.mMlrTimeout));
}
}
@@ -205,7 +205,8 @@ void Leader::UpdateBackboneRouterPrimary(void)
if (config.mMlrTimeout != origMlrTimeout)
{
LogNote("Leader MLR Timeout is normalized from %u to %u", origMlrTimeout, config.mMlrTimeout);
LogNote("Leader MLR Timeout is normalized from %lu to %lu", ToUlong(origMlrTimeout),
ToUlong(config.mMlrTimeout));
}
}
+2 -2
View File
@@ -454,8 +454,8 @@ void Local::LogDomainPrefix(const char *aAction, Error aError)
void Local::LogBackboneRouterService(const char *aAction, Error aError)
{
LogInfo("%s BBR Service: seqno (%d), delay (%ds), timeout (%ds), %s", aAction, mSequenceNumber,
mReregistrationDelay, mMlrTimeout, ErrorToString(aError));
LogInfo("%s BBR Service: seqno (%u), delay (%us), timeout (%lus), %s", aAction, mSequenceNumber,
mReregistrationDelay, ToUlong(mMlrTimeout), ErrorToString(aError));
}
#endif
+5 -5
View File
@@ -213,7 +213,7 @@ void Manager::HandleMulticastListenerRegistration(const Coap::Message &aMessage,
if (timeout != origTimeout)
{
LogNote("MLR.req: MLR timeout is normalized from %u to %u", origTimeout, timeout);
LogNote("MLR.req: MLR timeout is normalized from %lu to %lu", ToUlong(origTimeout), ToUlong(timeout));
}
}
}
@@ -728,8 +728,8 @@ void Manager::HandleExtendedBackboneAnswer(const Ip6::Address & aDua,
dest.SetToRoutingLocator(Get<Mle::MleRouter>().GetMeshLocalPrefix(), aSrcRloc16);
Get<AddressResolver>().SendAddressQueryResponse(aDua, aMeshLocalIid, &aTimeSinceLastTransaction, dest);
LogInfo("HandleExtendedBackboneAnswer: target=%s, mliid=%s, LTT=%lds, rloc16=%04x", aDua.ToString().AsCString(),
aMeshLocalIid.ToString().AsCString(), aTimeSinceLastTransaction, aSrcRloc16);
LogInfo("HandleExtendedBackboneAnswer: target=%s, mliid=%s, LTT=%lus, rloc16=%04x", aDua.ToString().AsCString(),
aMeshLocalIid.ToString().AsCString(), ToUlong(aTimeSinceLastTransaction), aSrcRloc16);
}
void Manager::HandleProactiveBackboneNotification(const Ip6::Address & aDua,
@@ -765,8 +765,8 @@ void Manager::HandleProactiveBackboneNotification(const Ip6::Address &
}
exit:
LogInfo("HandleProactiveBackboneNotification: %s, target=%s, mliid=%s, LTT=%lds", ErrorToString(error),
aDua.ToString().AsCString(), aMeshLocalIid.ToString().AsCString(), aTimeSinceLastTransaction);
LogInfo("HandleProactiveBackboneNotification: %s, target=%s, mliid=%s, LTT=%lus", ErrorToString(error),
aDua.ToString().AsCString(), aMeshLocalIid.ToString().AsCString(), ToUlong(aTimeSinceLastTransaction));
}
#endif // OPENTHREAD_CONFIG_BACKBONE_ROUTER_DUA_NDPROXYING_ENABLE
@@ -157,7 +157,7 @@ void MulticastListenersTable::LogMulticastListenersTable(const char * aAc
OT_UNUSED_VARIABLE(aExpireTime);
OT_UNUSED_VARIABLE(aError);
LogDebg("%s %s expire %u: %s", aAction, aAddress.ToString().AsCString(), aExpireTime.GetValue(),
LogDebg("%s %s expire %lu: %s", aAction, aAddress.ToString().AsCString(), ToUlong(aExpireTime.GetValue()),
ErrorToString(aError));
}
+2 -2
View File
@@ -188,8 +188,8 @@ Error NdProxyTable::Register(const Ip6::InterfaceIdentifier &aAddressIid,
mIsAnyDadInProcess = true;
exit:
LogInfo("NdProxyTable::Register %s MLIID %s RLOC16 %04x LTT %u => %s", aAddressIid.ToString().AsCString(),
aMeshLocalIid.ToString().AsCString(), aRloc16, timeSinceLastTransaction, ErrorToString(error));
LogInfo("NdProxyTable::Register %s MLIID %s RLOC16 %04x LTT %lu => %s", aAddressIid.ToString().AsCString(),
aMeshLocalIid.ToString().AsCString(), aRloc16, ToUlong(timeSinceLastTransaction), ErrorToString(error));
return error;
}
+15 -15
View File
@@ -598,7 +598,7 @@ void RoutingManager::ScheduleRoutingPolicyEvaluation(ScheduleMode aMode)
// Ensure we wait a min delay after last RA tx
evaluateTime = Max(now + delay, mRaInfo.mLastTxTime + kMinDelayBetweenRtrAdvs);
LogInfo("Start evaluating routing policy, scheduled in %u milliseconds", evaluateTime - now);
LogInfo("Start evaluating routing policy, scheduled in %lu milliseconds", ToUlong(evaluateTime - now));
mRoutingPolicyTimer.FireAtIfEarlier(evaluateTime);
}
@@ -739,8 +739,8 @@ void RoutingManager::SendRouterAdvertisement(RouterAdvTxMode aRaTxMode)
for (const OnMeshPrefix &prefix : mAdvertisedPrefixes)
{
SuccessOrAssert(raMsg.AppendRouteInfoOption(prefix, kDefaultOmrPrefixLifetime, mRouteInfoOptionPreference));
LogInfo("RouterAdvert: Added RIO for %s (lifetime=%u)", prefix.ToString().AsCString(),
kDefaultOmrPrefixLifetime);
LogInfo("RouterAdvert: Added RIO for %s (lifetime=%lu)", prefix.ToString().AsCString(),
ToUlong(kDefaultOmrPrefixLifetime));
}
}
@@ -1145,7 +1145,7 @@ void RoutingManager::ResetDiscoveredPrefixStaleTimer(void)
else
{
mDiscoveredPrefixStaleTimer.FireAt(nextStaleTime);
LogDebg("Prefix stale timer scheduled in %lu ms", nextStaleTime - now);
LogDebg("Prefix stale timer scheduled in %lu ms", ToUlong(nextStaleTime - now));
}
}
@@ -1264,7 +1264,7 @@ void RoutingManager::DiscoveredPrefixTable::ProcessPrefixInfoOption(const Ip6::N
VerifyOrExit(Get<RoutingManager>().ShouldProcessPrefixInfoOption(aPio, prefix));
LogInfo("Processing PIO (%s, %u seconds)", prefix.ToString().AsCString(), aPio.GetValidLifetime());
LogInfo("Processing PIO (%s, %lu seconds)", prefix.ToString().AsCString(), ToUlong(aPio.GetValidLifetime()));
entry = aRouter.mEntries.FindMatching(Entry::Matcher(prefix, Entry::kTypeOnLink));
@@ -1311,7 +1311,7 @@ void RoutingManager::DiscoveredPrefixTable::ProcessRouteInfoOption(const Ip6::Nd
VerifyOrExit(Get<RoutingManager>().ShouldProcessRouteInfoOption(aRio, prefix));
LogInfo("Processing RIO (%s, %u seconds)", prefix.ToString().AsCString(), aRio.GetRouteLifetime());
LogInfo("Processing RIO (%s, %lu seconds)", prefix.ToString().AsCString(), ToUlong(aRio.GetRouteLifetime()));
entry = aRouter.mEntries.FindMatching(Entry::Matcher(prefix, Entry::kTypeRoute));
@@ -1761,7 +1761,7 @@ void RoutingManager::DiscoveredPrefixTable::SendNeighborSolicitToRouter(const Ro
IgnoreError(Get<RoutingManager>().mInfraIf.Send(packet, aRouter.mAddress));
LogInfo("Sent Neighbor Solicitation to %s - attempt:%d/%d", aRouter.mAddress.ToString().AsCString(),
LogInfo("Sent Neighbor Solicitation to %s - attempt:%u/%u", aRouter.mAddress.ToString().AsCString(),
aRouter.mNsProbeCount, Router::kMaxNsProbes);
exit:
@@ -2403,8 +2403,8 @@ void RoutingManager::OnLinkPrefixManager::AppendCurPrefix(Ip6::Nd::RouterAdvertM
SuccessOrAssert(aRaMessage.AppendPrefixInfoOption(mLocalPrefix, validLifetime, preferredLifetime));
LogInfo("RouterAdvert: Added PIO for %s (valid=%u, preferred=%u)", mLocalPrefix.ToString().AsCString(),
validLifetime, preferredLifetime);
LogInfo("RouterAdvert: Added PIO for %s (valid=%lu, preferred=%lu)", mLocalPrefix.ToString().AsCString(),
ToUlong(validLifetime), ToUlong(preferredLifetime));
exit:
return;
@@ -2425,8 +2425,8 @@ void RoutingManager::OnLinkPrefixManager::AppendOldPrefixes(Ip6::Nd::RouterAdver
validLifetime = TimeMilli::MsecToSec(oldPrefix.mExpireTime - now);
SuccessOrAssert(aRaMessage.AppendPrefixInfoOption(oldPrefix.mPrefix, validLifetime, 0));
LogInfo("RouterAdvert: Added PIO for %s (valid=%u, preferred=0)", oldPrefix.mPrefix.ToString().AsCString(),
validLifetime);
LogInfo("RouterAdvert: Added PIO for %s (valid=%lu, preferred=0)", oldPrefix.mPrefix.ToString().AsCString(),
ToUlong(validLifetime));
}
}
@@ -2801,7 +2801,7 @@ void RoutingManager::Nat64PrefixManager::HandleTimer(void)
Discover();
mTimer.Start(TimeMilli::SecToMsec(kDefaultNat64PrefixLifetime));
LogInfo("NAT64 prefix timer scheduled in %u seconds", kDefaultNat64PrefixLifetime);
LogInfo("NAT64 prefix timer scheduled in %lu seconds", ToUlong(kDefaultNat64PrefixLifetime));
}
void RoutingManager::Nat64PrefixManager::Discover(void)
@@ -2862,7 +2862,7 @@ void RoutingManager::RsSender::Start(void)
VerifyOrExit(!IsInProgress());
delay = Random::NonCrypto::GetUint32InRange(0, kMaxStartDelay);
LogInfo("Scheduled Router Solicitation in %u milliseconds", delay);
LogInfo("Scheduled Router Solicitation in %lu milliseconds", ToUlong(delay));
mTxCount = 0;
mStartTime = TimerMilli::GetNow();
@@ -2905,12 +2905,12 @@ void RoutingManager::RsSender::HandleTimer(void)
if (error == kErrorNone)
{
mTxCount++;
LogInfo("Successfully sent RS %d/%d", mTxCount, kMaxTxCount);
LogInfo("Successfully sent RS %u/%u", mTxCount, kMaxTxCount);
delay = (mTxCount == kMaxTxCount) ? kWaitOnLastAttempt : kTxInterval;
}
else
{
LogCrit("Failed to send RS %d, error:%s", mTxCount + 1, ErrorToString(error));
LogCrit("Failed to send RS %u, error:%s", mTxCount + 1, ErrorToString(error));
// Note that `mTxCount` is intentionally not incremented
// if the tx fails.
+10 -12
View File
@@ -107,7 +107,7 @@ constexpr uint8_t kMaxLogModuleNameLength = 14; ///< Maximum module name length
* @param[in] ... Arguments for the format specification.
*
*/
#define LogCrit(...) Logger::Log<kLogLevelCrit, kLogModuleName>(__VA_ARGS__)
#define LogCrit(...) Logger::LogAtLevel<kLogLevelCrit>(kLogModuleName, __VA_ARGS__)
#else
#define LogCrit(...)
#endif
@@ -119,7 +119,7 @@ constexpr uint8_t kMaxLogModuleNameLength = 14; ///< Maximum module name length
* @param[in] ... Arguments for the format specification.
*
*/
#define LogWarn(...) Logger::Log<kLogLevelWarn, kLogModuleName>(__VA_ARGS__)
#define LogWarn(...) Logger::LogAtLevel<kLogLevelWarn>(kLogModuleName, __VA_ARGS__)
#else
#define LogWarn(...)
#endif
@@ -131,7 +131,7 @@ constexpr uint8_t kMaxLogModuleNameLength = 14; ///< Maximum module name length
* @param[in] ... Arguments for the format specification.
*
*/
#define LogNote(...) Logger::Log<kLogLevelNote, kLogModuleName>(__VA_ARGS__)
#define LogNote(...) Logger::LogAtLevel<kLogLevelNote>(kLogModuleName, __VA_ARGS__)
#else
#define LogNote(...)
#endif
@@ -143,7 +143,7 @@ constexpr uint8_t kMaxLogModuleNameLength = 14; ///< Maximum module name length
* @param[in] ... Arguments for the format specification.
*
*/
#define LogInfo(...) Logger::Log<kLogLevelInfo, kLogModuleName>(__VA_ARGS__)
#define LogInfo(...) Logger::LogAtLevel<kLogLevelInfo>(kLogModuleName, __VA_ARGS__)
#else
#define LogInfo(...)
#endif
@@ -155,7 +155,7 @@ constexpr uint8_t kMaxLogModuleNameLength = 14; ///< Maximum module name length
* @param[in] ... Arguments for the format specification.
*
*/
#define LogDebg(...) Logger::Log<kLogLevelDebg, kLogModuleName>(__VA_ARGS__)
#define LogDebg(...) Logger::LogAtLevel<kLogLevelDebg>(kLogModuleName, __VA_ARGS__)
#else
#define LogDebg(...)
#endif
@@ -305,15 +305,13 @@ class Logger
// and instead the logging macros should be used.
public:
template <LogLevel kLogLevel, const char *kModuleName, typename... Args>
static void Log(const char *aFormat, Args... aArgs)
{
LogAtLevel<kLogLevel>(kModuleName, aFormat, aArgs...);
}
static void LogInModule(const char *aModuleName, LogLevel aLogLevel, const char *aFormat, ...)
OT_TOOL_PRINTF_STYLE_FORMAT_ARG_CHECK(3, 4);
static void LogInModule(const char *aModuleName, LogLevel aLogLevel, const char *aFormat, ...);
template <LogLevel kLogLevel>
static void LogAtLevel(const char *aModuleName, const char *aFormat, ...)
OT_TOOL_PRINTF_STYLE_FORMAT_ARG_CHECK(2, 3);
template <LogLevel kLogLevel> static void LogAtLevel(const char *aModuleName, const char *aFormat, ...);
static void LogVarArgs(const char *aModuleName, LogLevel aLogLevel, const char *aFormat, va_list aArgs);
#if OPENTHREAD_CONFIG_LOG_PKT_DUMP
+2 -2
View File
@@ -228,7 +228,7 @@ void Notifier::LogEvents(Events aEvents) const
{
if (string.GetLength() >= kFlagsStringLineLimit)
{
LogInfo("StateChanged (0x%08x) %s%s ...", aEvents.GetAsFlags(), didLog ? "... " : "[",
LogInfo("StateChanged (0x%08lx) %s%s ...", ToUlong(aEvents.GetAsFlags()), didLog ? "... " : "[",
string.AsCString());
string.Clear();
didLog = true;
@@ -243,7 +243,7 @@ void Notifier::LogEvents(Events aEvents) const
}
exit:
LogInfo("StateChanged (0x%08x) %s%s]", aEvents.GetAsFlags(), didLog ? "... " : "[", string.AsCString());
LogInfo("StateChanged (0x%08lx) %s%s]", ToUlong(aEvents.GetAsFlags()), didLog ? "... " : "[", string.AsCString());
}
const char *Notifier::EventToString(Event aEvent) const
+7 -7
View File
@@ -53,26 +53,26 @@ RegisterLogModule("Settings");
void SettingsBase::NetworkInfo::Log(Action aAction) const
{
LogInfo("%s NetworkInfo {rloc:0x%04x, extaddr:%s, role:%s, mode:0x%02x, version:%hu, keyseq:0x%x, ...",
LogInfo("%s NetworkInfo {rloc:0x%04x, extaddr:%s, role:%s, mode:0x%02x, version:%u, keyseq:0x%lx, ...",
ActionToString(aAction), GetRloc16(), GetExtAddress().ToString().AsCString(),
Mle::RoleToString(static_cast<Mle::DeviceRole>(GetRole())), GetDeviceMode(), GetVersion(),
GetKeySequence());
ToUlong(GetKeySequence()));
LogInfo("... pid:0x%x, mlecntr:0x%x, maccntr:0x%x, mliid:%s}", GetPreviousPartitionId(), GetMleFrameCounter(),
GetMacFrameCounter(), GetMeshLocalIid().ToString().AsCString());
LogInfo("... pid:0x%lx, mlecntr:0x%lx, maccntr:0x%lx, mliid:%s}", ToUlong(GetPreviousPartitionId()),
ToUlong(GetMleFrameCounter()), ToUlong(GetMacFrameCounter()), GetMeshLocalIid().ToString().AsCString());
}
void SettingsBase::ParentInfo::Log(Action aAction) const
{
LogInfo("%s ParentInfo {extaddr:%s, version:%hu}", ActionToString(aAction), GetExtAddress().ToString().AsCString(),
LogInfo("%s ParentInfo {extaddr:%s, version:%u}", ActionToString(aAction), GetExtAddress().ToString().AsCString(),
GetVersion());
}
#if OPENTHREAD_FTD
void SettingsBase::ChildInfo::Log(Action aAction) const
{
LogInfo("%s ChildInfo {rloc:0x%04x, extaddr:%s, timeout:%u, mode:0x%02x, version:%hu}", ActionToString(aAction),
GetRloc16(), GetExtAddress().ToString().AsCString(), GetTimeout(), GetMode(), GetVersion());
LogInfo("%s ChildInfo {rloc:0x%04x, extaddr:%s, timeout:%lu, mode:0x%02x, version:%u}", ActionToString(aAction),
GetRloc16(), GetExtAddress().ToString().AsCString(), ToUlong(GetTimeout()), GetMode(), GetVersion());
}
#endif
+7 -7
View File
@@ -571,7 +571,7 @@ void Mac::UpdateIdleMode(void)
else
{
mLinks.Receive(mRadioChannel);
LogDebg("Idle mode: Radio receiving on channel %d", mRadioChannel);
LogDebg("Idle mode: Radio receiving on channel %u", mRadioChannel);
}
exit:
@@ -1506,7 +1506,7 @@ Error Mac::ProcessReceiveSecurity(RxFrame &aFrame, const Address &aSrcAddr, Neig
VerifyOrExit(securityLevel == Frame::kSecEncMic32);
IgnoreError(aFrame.GetFrameCounter(frameCounter));
LogDebg("Rx security - frame counter %u", frameCounter);
LogDebg("Rx security - frame counter %lu", ToUlong(frameCounter));
IgnoreError(aFrame.GetKeyIdMode(keyIdMode));
@@ -1652,7 +1652,7 @@ Error Mac::ProcessEnhAckSecurity(TxFrame &aTxFrame, RxFrame &aAckFrame)
VerifyOrExit(txKeyId == ackKeyId);
IgnoreError(aAckFrame.GetFrameCounter(frameCounter));
LogDebg("Rx security - Ack frame counter %u", frameCounter);
LogDebg("Rx security - Ack frame counter %lu", ToUlong(frameCounter));
IgnoreError(aAckFrame.GetSrcAddr(srcAddr));
@@ -2209,7 +2209,7 @@ void Mac::LogFrameTxFailure(const TxFrame &aFrame, Error aError, uint8_t aRetryC
uint8_t maxAttempts = aFrame.GetMaxFrameRetries() + 1;
uint8_t curAttempt = aWillRetx ? (aRetryCount + 1) : maxAttempts;
LogInfo("Frame tx attempt %d/%d failed, error:%s, %s", curAttempt, maxAttempts, ErrorToString(aError),
LogInfo("Frame tx attempt %u/%u failed, error:%s, %s", curAttempt, maxAttempts, ErrorToString(aError),
aFrame.ToInfoString().AsCString());
}
else
@@ -2327,9 +2327,9 @@ void Mac::ProcessCsl(const RxFrame &aFrame, const Address &aSrcAddr)
child->SetCslSynchronized(true);
child->SetCslLastHeard(TimerMilli::GetNow());
child->SetLastRxTimestamp(aFrame.GetTimestamp());
LogDebg("Timestamp=%u Sequence=%u CslPeriod=%hu CslPhase=%hu TransmitPhase=%hu",
static_cast<uint32_t>(aFrame.GetTimestamp()), aFrame.GetSequence(), csl->GetPeriod(), csl->GetPhase(),
child->GetCslPhase());
LogDebg("Timestamp=%lu Sequence=%u CslPeriod=%u CslPhase=%u TransmitPhase=%u",
ToUlong(static_cast<uint32_t>(aFrame.GetTimestamp())), aFrame.GetSequence(), csl->GetPeriod(),
csl->GetPhase(), child->GetCslPhase());
Get<CslTxScheduler>().Update();
+4 -3
View File
@@ -485,7 +485,7 @@ void SubMac::StartTimerForBackoff(uint8_t aBackoffExponent)
#if OPENTHREAD_CONFIG_MAC_ADD_DELAY_ON_NO_ACK_ERROR_BEFORE_RETRY
if (mState == kStateDelayBeforeRetx)
{
LogDebg("Delaying retx for %u usec (be=%d)", backoff, aBackoffExponent);
LogDebg("Delaying retx for %lu usec (be=%u)", ToUlong(backoff), aBackoffExponent);
}
#endif
}
@@ -1103,7 +1103,7 @@ void SubMac::HandleCslTimer(void)
#if !OPENTHREAD_CONFIG_MAC_CSL_DEBUG_ENABLE
IgnoreError(Get<Radio>().Sleep()); // Don't actually sleep for debugging
#endif
LogDebg("CSL sleep %u", mCslTimer.GetNow().GetValue());
LogDebg("CSL sleep %lu", ToUlong(mCslTimer.GetNow().GetValue()));
}
}
else
@@ -1131,7 +1131,8 @@ void SubMac::HandleCslTimer(void)
else if (mState == kStateCslSample)
{
IgnoreError(Get<Radio>().Receive(mCslChannel));
LogDebg("CSL sample %u, duration %u", mCslTimer.GetNow().GetValue(), timeAhead + timeAfter);
LogDebg("CSL sample %lu, duration %lu", ToUlong(mCslTimer.GetNow().GetValue()),
ToUlong(timeAhead + timeAfter));
}
}
}
+1 -1
View File
@@ -211,7 +211,7 @@ exit:
{
FreeMessage(message);
LogWarn("Commissioner request[%hu] failed: %s", aForwardContext.GetMessageId(), ErrorToString(error));
LogWarn("Commissioner request[%u] failed: %s", aForwardContext.GetMessageId(), ErrorToString(error));
SendErrorMessage(aForwardContext, error);
}
+1 -1
View File
@@ -783,7 +783,7 @@ void PendingDatasetManager::StartDelayTimer(void)
}
mDelayTimer.StartAt(dataset.GetUpdateTime(), delay);
LogInfo("delay timer started %d", delay);
LogInfo("delay timer started %lu", ToUlong(delay));
}
}
+4 -4
View File
@@ -977,20 +977,20 @@ void Dtls::HandleMbedtlsDebug(int aLevel, const char *aFile, int aLine, const ch
switch (aLevel)
{
case 1:
LogCrit("[%hu] %s", mSocket.GetSockName().mPort, aStr);
LogCrit("[%u] %s", mSocket.GetSockName().mPort, aStr);
break;
case 2:
LogWarn("[%hu] %s", mSocket.GetSockName().mPort, aStr);
LogWarn("[%u] %s", mSocket.GetSockName().mPort, aStr);
break;
case 3:
LogInfo("[%hu] %s", mSocket.GetSockName().mPort, aStr);
LogInfo("[%u] %s", mSocket.GetSockName().mPort, aStr);
break;
case 4:
default:
LogDebg("[%hu] %s", mSocket.GetSockName().mPort, aStr);
LogDebg("[%u] %s", mSocket.GetSockName().mPort, aStr);
break;
}
}
+3 -3
View File
@@ -777,7 +777,7 @@ void Client::SendUpdate(void)
if (length >= Ip6::kMaxDatagramLength)
{
LogInfo("Msg len %u is larger than MTU, enabling single service mode", length);
LogInfo("Msg len %lu is larger than MTU, enabling single service mode", ToUlong(length));
mSingleServiceMode = true;
IgnoreError(message->SetLength(0));
SuccessOrExit(error = PrepareUpdateMessage(*message));
@@ -833,7 +833,7 @@ exit:
interval = Random::NonCrypto::AddJitter(kTxFailureRetryInterval, kTxFailureRetryJitter);
mTimer.Start(interval);
LogInfo("Quick retry %d in %u msec", mTxFailureRetryCount, interval);
LogInfo("Quick retry %u in %lu msec", mTxFailureRetryCount, ToUlong(interval));
// Do not report message preparation errors to user
// until `kMaxTxFailureRetries` are exhausted.
@@ -2220,7 +2220,7 @@ void Client::LogRetryWaitInterval(void) const
uint32_t interval = GetRetryWaitInterval();
LogInfo("Retry interval %u %s", (interval < kLogInMsecLimit) ? interval : Time::MsecToSec(interval),
LogInfo("Retry interval %lu %s", ToUlong((interval < kLogInMsecLimit) ? interval : Time::MsecToSec(interval)),
(interval < kLogInMsecLimit) ? "ms" : "sec");
}
+12 -10
View File
@@ -346,7 +346,7 @@ void Server::RemoveHost(Host *aHost, RetainName aRetainName, NotifyMode aNotifyS
{
uint32_t updateId = AllocateId();
LogInfo("SRP update handler is notified (updatedId = %u)", updateId);
LogInfo("SRP update handler is notified (updatedId = %lu)", ToUlong(updateId));
mServiceUpdateHandler(updateId, aHost, kDefaultEventsHandlerTimeout, mServiceUpdateHandlerContext);
// We don't wait for the reply from the service update handler,
// but always remove the host (and its services) regardless of
@@ -406,13 +406,14 @@ void Server::HandleServiceUpdateResult(ServiceUpdateId aId, Error aError)
}
else
{
LogInfo("Delayed SRP host update result, the SRP update has been committed (updateId = %u)", aId);
LogInfo("Delayed SRP host update result, the SRP update has been committed (updateId = %lu)", ToUlong(aId));
}
}
void Server::HandleServiceUpdateResult(UpdateMetadata *aUpdate, Error aError)
{
LogInfo("Handler result of SRP update (id = %u) is received: %s", aUpdate->GetId(), ErrorToString(aError));
LogInfo("Handler result of SRP update (id = %lu) is received: %s", ToUlong(aUpdate->GetId()),
ErrorToString(aError));
IgnoreError(mOutstandingUpdates.Remove(*aUpdate));
CommitSrpUpdate(aError, *aUpdate);
@@ -734,7 +735,7 @@ void Server::ProcessDnsUpdate(Message &aMessage, MessageMetadata &aMetadata)
if (FindOutstandingUpdate(aMetadata) != nullptr)
{
LogInfo("Drop duplicated SRP update request: MessageId=%hu", aMetadata.mDnsHeader.GetMessageId());
LogInfo("Drop duplicated SRP update request: MessageId=%u", aMetadata.mDnsHeader.GetMessageId());
// Silently drop duplicate requests.
// This could rarely happen, because the outstanding SRP update timer should
@@ -1337,7 +1338,8 @@ void Server::InformUpdateHandlerOrCommit(Error aError, Host &aHost, const Messag
LogInfo("Processed DNS update info");
LogInfo(" Host:%s", aHost.GetFullName());
LogInfo(" Lease:%u, key-lease:%u, ttl:%u", aHost.GetLease(), aHost.GetKeyLease(), aHost.GetTtl());
LogInfo(" Lease:%lu, key-lease:%lu, ttl:%lu", ToUlong(aHost.GetLease()), ToUlong(aHost.GetKeyLease()),
ToUlong(aHost.GetTtl()));
addrs = aHost.GetAddresses(numAddrs);
@@ -1380,7 +1382,7 @@ void Server::InformUpdateHandlerOrCommit(Error aError, Host &aHost, const Messag
mOutstandingUpdates.Push(*update);
mOutstandingUpdatesTimer.FireAtIfEarlier(update->GetExpireTime());
LogInfo("SRP update handler is notified (updatedId = %u)", update->GetId());
LogInfo("SRP update handler is notified (updatedId = %lu)", ToUlong(update->GetId()));
mServiceUpdateHandler(update->GetId(), &aHost, kDefaultEventsHandlerTimeout, mServiceUpdateHandlerContext);
ExitNow();
}
@@ -1469,7 +1471,7 @@ void Server::SendResponse(const Dns::UpdateHeader &aHeader,
SuccessOrExit(error = GetSocket().SendTo(*response, aMessageInfo));
LogInfo("Send success response with granted lease: %u and key lease: %u", aLease, aKeyLease);
LogInfo("Send success response with granted lease: %lu and key lease: %lu", ToUlong(aLease), ToUlong(aKeyLease));
UpdateResponseCounters(Dns::UpdateHeader::kResponseSuccess);
@@ -1631,7 +1633,7 @@ void Server::HandleLeaseTimer(void)
OT_ASSERT(earliestExpireTime >= now);
if (!mLeaseTimer.IsRunning() || earliestExpireTime <= mLeaseTimer.GetFireTime())
{
LogInfo("Lease timer is scheduled for %u seconds", Time::MsecToSec(earliestExpireTime - now));
LogInfo("Lease timer is scheduled for %lu seconds", ToUlong(Time::MsecToSec(earliestExpireTime - now)));
mLeaseTimer.StartAt(earliestExpireTime, 0);
}
}
@@ -1646,7 +1648,7 @@ void Server::HandleOutstandingUpdatesTimer(void)
{
while (!mOutstandingUpdates.IsEmpty() && mOutstandingUpdates.GetTail()->GetExpireTime() <= TimerMilli::GetNow())
{
LogInfo("Outstanding service update timeout (updateId = %u)", mOutstandingUpdates.GetTail()->GetId());
LogInfo("Outstanding service update timeout (updateId = %lu)", ToUlong(mOutstandingUpdates.GetTail()->GetId()));
HandleServiceUpdateResult(mOutstandingUpdates.GetTail(), kErrorResponseTimeout);
}
}
@@ -2078,7 +2080,7 @@ void Server::Host::RemoveService(Service *aService, RetainName aRetainName, Noti
{
uint32_t updateId = server.AllocateId();
LogInfo("SRP update handler is notified (updatedId = %u)", updateId);
LogInfo("SRP update handler is notified (updatedId = %lu)", ToUlong(updateId));
server.mServiceUpdateHandler(updateId, this, kDefaultEventsHandlerTimeout, server.mServiceUpdateHandlerContext);
// We don't wait for the reply from the service update handler,
// but always remove the service regardless of service update result.
+1 -1
View File
@@ -1116,7 +1116,7 @@ void tcplp_sys_log(const char *aFormat, ...)
vsnprintf(buffer, sizeof(buffer), aFormat, args);
va_end(args);
LogDebg(buffer);
LogDebg("%s", buffer);
}
void tcplp_sys_panic(const char *aFormat, ...)
+1 -1
View File
@@ -170,7 +170,7 @@ void TcpCircularSendBuffer::HandleForwardProgress(size_t aInSendBuffer)
size_t bytesUntilWrap;
OT_ASSERT(aInSendBuffer <= mCapacityUsed);
LogDebg("Forward progress: %u bytes in send buffer\n", aInSendBuffer);
LogDebg("Forward progress: %u bytes in send buffer\n", static_cast<unsigned>(aInSendBuffer));
bytesRemoved = mCapacityUsed - aInSendBuffer;
bytesUntilWrap = mCapacity - mStartIndex;
+1 -1
View File
@@ -259,7 +259,7 @@ void AnnounceSender::HandleActiveDatasetChanged(void)
SetChannelMask(channelMask);
SetPeriod(kTxInterval / channelMask.GetNumberOfChannels());
LogInfo("ChannelMask:%s, period:%u", GetChannelMask().ToString().AsCString(), GetPeriod());
LogInfo("ChannelMask:%s, period:%lu", GetChannelMask().ToString().AsCString(), ToUlong(GetPeriod()));
// When channel mask is changed, we also check and update the PAN
// channel. This handles the case where `ThreadChannelChanged` event
+4 -4
View File
@@ -464,25 +464,25 @@ void LinkMetrics::HandleReport(const Message & aMessage,
case TypeId::kPdu:
values.mMetrics.mPduCount = true;
values.mPduCountValue = reportTlv.GetMetricsValue32();
LogDebg(" - PDU Counter: %d (Count/Summation)", values.mPduCountValue);
LogDebg(" - PDU Counter: %lu (Count/Summation)", ToUlong(values.mPduCountValue));
break;
case TypeId::kLqi:
values.mMetrics.mLqi = true;
values.mLqiValue = reportTlv.GetMetricsValue8();
LogDebg(" - LQI: %d (Exponential Moving Average)", values.mLqiValue);
LogDebg(" - LQI: %u (Exponential Moving Average)", values.mLqiValue);
break;
case TypeId::kLinkMargin:
values.mMetrics.mLinkMargin = true;
values.mLinkMarginValue = ScaleRawValueToLinkMargin(reportTlv.GetMetricsValue8());
LogDebg(" - Margin: %d (dB) (Exponential Moving Average)", values.mLinkMarginValue);
LogDebg(" - Margin: %u (dB) (Exponential Moving Average)", values.mLinkMarginValue);
break;
case TypeId::kRssi:
values.mMetrics.mRssi = true;
values.mRssiValue = ScaleRawValueToRssi(reportTlv.GetMetricsValue8());
LogDebg(" - RSSI: %d (dBm) (Exponential Moving Average)", values.mRssiValue);
LogDebg(" - RSSI: %u (dBm) (Exponential Moving Average)", values.mRssiValue);
break;
}
+1 -1
View File
@@ -1244,7 +1244,7 @@ void MeshForwarder::HandleSentFrame(Mac::TxFrame &aFrame, Error aError)
if (mDelayNextTx && (aError == kErrorNone))
{
mTxDelayTimer.Start(kTxDelayInterval);
LogDebg("Start tx delay timer for %u msec", kTxDelayInterval);
LogDebg("Start tx delay timer for %lu msec", ToUlong(kTxDelayInterval));
}
else
{
+2 -2
View File
@@ -656,8 +656,8 @@ uint32_t Mle::GetAttachStartDelay(void) const
delay += jitter;
}
LogNote("Attach attempt %d unsuccessful, will try again in %u.%03u seconds", mAttachCounter, delay / 1000,
delay % 1000);
LogNote("Attach attempt %u unsuccessful, will try again in %lu.%03u seconds", mAttachCounter, ToUlong(delay / 1000),
static_cast<uint16_t>(delay % 1000));
exit:
return delay;
+9 -8
View File
@@ -439,7 +439,7 @@ void MleRouter::SetStateLeader(uint16_t aRloc16, LeaderStartMode aStartMode)
Get<Mac::Mac>().UpdateCsl();
#endif
LogNote("Leader partition id 0x%x", mLeaderData.GetPartitionId());
LogNote("Leader partition id 0x%lx", ToUlong(mLeaderData.GetPartitionId()));
}
void MleRouter::HandleAdvertiseTrickleTimer(TrickleTimer &aTimer)
@@ -1246,7 +1246,8 @@ Error MleRouter::HandleAdvertisement(RxInfo &aRxInfo)
if (partitionId != mLeaderData.GetPartitionId())
{
LogNote("Different partition (peer:%u, local:%u)", partitionId, mLeaderData.GetPartitionId());
LogNote("Different partition (peer:%lu, local:%lu)", ToUlong(partitionId),
ToUlong(mLeaderData.GetPartitionId()));
VerifyOrExit(linkMargin >= OPENTHREAD_CONFIG_MLE_PARTITION_MERGE_MARGIN_MIN, error = kErrorLinkMarginLow);
@@ -1873,7 +1874,7 @@ void MleRouter::HandleTimeTick(void)
case kRoleRouter:
// verify path to leader
LogDebg("network id timeout = %d", mRouterTable.GetLeaderAge());
LogDebg("network id timeout = %lu", ToUlong(mRouterTable.GetLeaderAge()));
if ((mRouterTable.GetActiveRouterCount() > 0) && (mRouterTable.GetLeaderAge() >= mNetworkIdTimeout))
{
@@ -2175,7 +2176,7 @@ Error MleRouter::UpdateChildAddresses(const Message &aMessage, uint16_t aOffset,
{
if (Get<NetworkData::Leader>().GetContext(entry.GetContextId(), context) != kErrorNone)
{
LogWarn("Failed to get context %d for compressed address from child 0x%04x", entry.GetContextId(),
LogWarn("Failed to get context %u for compressed address from child 0x%04x", entry.GetContextId(),
aChild.GetRloc16());
continue;
}
@@ -2225,7 +2226,7 @@ Error MleRouter::UpdateChildAddresses(const Message &aMessage, uint16_t aOffset,
}
#endif
LogInfo("Child 0x%04x IPv6 address[%d]=%s", aChild.GetRloc16(), storedCount,
LogInfo("Child 0x%04x IPv6 address[%u]=%s", aChild.GetRloc16(), storedCount,
address.ToString().AsCString());
}
else
@@ -2288,7 +2289,7 @@ Error MleRouter::UpdateChildAddresses(const Message &aMessage, uint16_t aOffset,
}
else
{
LogInfo("Child 0x%04x has %d registered IPv6 address%s, %d address%s stored", aChild.GetRloc16(),
LogInfo("Child 0x%04x has %u registered IPv6 address%s, %u address%s stored", aChild.GetRloc16(),
registeredCount, (registeredCount == 1) ? "" : "es", storedCount, (storedCount == 1) ? "" : "es");
}
@@ -3936,7 +3937,7 @@ template <> void MleRouter::HandleTmf<kUriAddressSolicit>(Coap::Message &aMessag
(Get<NetworkData::Leader>().CountBorderRouters(NetworkData::kRouterRoleOnly) >=
kRouterUpgradeBorderRouterRequestThreshold))
{
LogInfo("Rejecting BR %s router role req - have %d BR routers", extAddress.ToString().AsCString(),
LogInfo("Rejecting BR %s router role req - have %u BR routers", extAddress.ToString().AsCString(),
kRouterUpgradeBorderRouterRequestThreshold);
ExitNow();
}
@@ -3953,7 +3954,7 @@ template <> void MleRouter::HandleTmf<kUriAddressSolicit>(Coap::Message &aMessag
if (router != nullptr)
{
LogInfo("Router id %d requested and provided!", RouterIdFromRloc16(rloc16));
LogInfo("Router id %u requested and provided!", RouterIdFromRloc16(rloc16));
}
}
+1 -1
View File
@@ -672,7 +672,7 @@ void MlrManager::UpdateReregistrationDelay(bool aRereg)
UpdateTimeTickerRegistration();
LogDebg("MlrManager::UpdateReregistrationDelay: rereg=%d, needSendMlr=%d, ReregDelay=%lu", aRereg, needSendMlr,
mReregistrationDelay);
ToUlong(mReregistrationDelay));
}
void MlrManager::LogMulticastAddresses(void)
+1 -1
View File
@@ -472,7 +472,7 @@ exit:
void Publisher::Entry::LogUpdateTime(void) const
{
LogInfo("%s - update in %u msec", ToString().AsCString(), mUpdateTime - TimerMilli::GetNow());
LogInfo("%s - update in %lu msec", ToString().AsCString(), ToUlong(mUpdateTime - TimerMilli::GetNow()));
}
const char *Publisher::Entry::StateToString(State aState)
+2 -2
View File
@@ -237,8 +237,8 @@ void TimeSync::CheckAndHandleChanges(bool aTimeUpdated)
{
// The device hasnt received time sync for more than two periods time.
networkTimeStatus = OT_NETWORK_TIME_RESYNC_NEEDED;
LogInfo("Time sync status RESYNC_NEEDED as timeSyncLastSyncMs:%u > resyncNeededThresholdMs:%u",
timeSyncLastSyncMs, resyncNeededThresholdMs);
LogInfo("Time sync status RESYNC_NEEDED as timeSyncLastSyncMs:%lu > resyncNeededThresholdMs:%lu",
ToUlong(timeSyncLastSyncMs), ToUlong(resyncNeededThresholdMs));
}
else
{
+2 -2
View File
@@ -186,8 +186,8 @@ Error ChannelManager::FindBetterChannel(uint8_t &aNewChannel, uint16_t &aOccupan
if (Get<ChannelMonitor>().GetSampleCount() <= kMinChannelMonitorSampleCount)
{
LogInfo("Too few samples (%d <= %d) to select channel", Get<ChannelMonitor>().GetSampleCount(),
kMinChannelMonitorSampleCount);
LogInfo("Too few samples (%lu <= %lu) to select channel", ToUlong(Get<ChannelMonitor>().GetSampleCount()),
ToUlong(kMinChannelMonitorSampleCount));
ExitNow(error = kErrorInvalidState);
}
+1 -1
View File
@@ -195,7 +195,7 @@ void ChannelMonitor::LogResults(void)
logString.Append("%02x ", channel >> 8);
}
LogInfo("%u [%s]", mSampleCount, logString.AsCString());
LogInfo("%lu [%s]", ToUlong(mSampleCount), logString.AsCString());
#endif
}