Matter SDK Coverage Report
Current view: top level - lib/core - TLVReader.cpp (source / functions) Coverage Total Hit
Test: SHA:6c8f029dd2432dc900f1c9245c324e69bd79e40a Lines: 95.5 % 532 508
Test Date: 2026-08-08 07:40:09 Functions: 100.0 % 56 56

            Line data    Source code
       1              : /*
       2              :  *
       3              :  *    Copyright (c) 2020-2023 Project CHIP Authors
       4              :  *    Copyright (c) 2013-2017 Nest Labs, Inc.
       5              :  *
       6              :  *    Licensed under the Apache License, Version 2.0 (the "License");
       7              :  *    you may not use this file except in compliance with the License.
       8              :  *    You may obtain a copy of the License at
       9              :  *
      10              :  *        http://www.apache.org/licenses/LICENSE-2.0
      11              :  *
      12              :  *    Unless required by applicable law or agreed to in writing, software
      13              :  *    distributed under the License is distributed on an "AS IS" BASIS,
      14              :  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      15              :  *    See the License for the specific language governing permissions and
      16              :  *    limitations under the License.
      17              :  */
      18              : #include <lib/core/TLVReader.h>
      19              : 
      20              : #include <stdint.h>
      21              : #include <string.h>
      22              : 
      23              : #include <lib/core/CHIPConfig.h>
      24              : #include <lib/core/CHIPEncoding.h>
      25              : #include <lib/core/CHIPError.h>
      26              : #include <lib/core/CHIPSafeCasts.h>
      27              : #include <lib/core/DataModelTypes.h>
      28              : #include <lib/core/Optional.h>
      29              : #include <lib/core/TLVBackingStore.h>
      30              : #include <lib/core/TLVCommon.h>
      31              : #include <lib/core/TLVTags.h>
      32              : #include <lib/core/TLVTypes.h>
      33              : #include <lib/support/BufferWriter.h>
      34              : #include <lib/support/BytesToHex.h>
      35              : #include <lib/support/CHIPMem.h>
      36              : #include <lib/support/CodeUtils.h>
      37              : #include <lib/support/SafeInt.h>
      38              : #include <lib/support/Span.h>
      39              : #include <lib/support/logging/TextOnlyLogging.h>
      40              : #include <lib/support/utf8.h>
      41              : 
      42              : namespace chip {
      43              : namespace TLV {
      44              : 
      45              : using namespace chip::Encoding;
      46              : 
      47              : static const uint8_t sTagSizes[] = { 0, 1, 2, 4, 2, 4, 6, 8 };
      48              : 
      49      2868991 : TLVReader::TLVReader() :
      50      2868991 :     ImplicitProfileId(kProfileIdNotSpecified), AppData(nullptr), mElemLenOrVal(0), mBackingStore(nullptr), mReadPoint(nullptr),
      51      2868991 :     mBufEnd(nullptr), mLenRead(0), mMaxLen(0), mContainerType(kTLVType_NotSpecified), mControlByte(kTLVControlByte_NotSpecified),
      52      2868991 :     mContainerOpen(false)
      53      2868991 : {}
      54              : 
      55      2016154 : void TLVReader::Init(const uint8_t * data, size_t dataLen)
      56              : {
      57              :     // TODO: Maybe we can just make mMaxLen and mLenRead size_t instead?
      58      2016154 :     uint32_t actualDataLen = dataLen > UINT32_MAX ? UINT32_MAX : static_cast<uint32_t>(dataLen);
      59      2016154 :     mBackingStore          = nullptr;
      60      2016154 :     mReadPoint             = data;
      61      2016154 :     mBufEnd                = data + actualDataLen;
      62      2016154 :     mLenRead               = 0;
      63      2016154 :     mMaxLen                = actualDataLen;
      64      2016154 :     ClearElementState();
      65      2016154 :     mContainerType = kTLVType_NotSpecified;
      66      2016154 :     SetContainerOpen(false);
      67              : 
      68      2016154 :     ImplicitProfileId = kProfileIdNotSpecified;
      69      2016154 : }
      70              : 
      71         4152 : CHIP_ERROR TLVReader::Init(TLVBackingStore & backingStore, uint32_t maxLen)
      72              : {
      73         4152 :     mBackingStore   = &backingStore;
      74         4152 :     mReadPoint      = nullptr;
      75         4152 :     uint32_t bufLen = 0;
      76         4152 :     CHIP_ERROR err  = mBackingStore->OnInit(*this, mReadPoint, bufLen);
      77         8304 :     if (err != CHIP_NO_ERROR)
      78            0 :         return err;
      79              : 
      80         4152 :     mBufEnd  = mReadPoint + bufLen;
      81         4152 :     mLenRead = 0;
      82         4152 :     mMaxLen  = maxLen;
      83         4152 :     ClearElementState();
      84         4152 :     mContainerType = kTLVType_NotSpecified;
      85         4152 :     SetContainerOpen(false);
      86              : 
      87         4152 :     ImplicitProfileId = kProfileIdNotSpecified;
      88         4152 :     AppData           = nullptr;
      89         4152 :     return CHIP_NO_ERROR;
      90              : }
      91              : 
      92       802655 : void TLVReader::Init(const TLVReader & aReader)
      93              : {
      94              :     // Initialize private data members
      95              : 
      96       802655 :     mElemTag       = aReader.mElemTag;
      97       802655 :     mElemLenOrVal  = aReader.mElemLenOrVal;
      98       802655 :     mBackingStore  = aReader.mBackingStore;
      99       802655 :     mReadPoint     = aReader.mReadPoint;
     100       802655 :     mBufEnd        = aReader.mBufEnd;
     101       802655 :     mLenRead       = aReader.mLenRead;
     102       802655 :     mMaxLen        = aReader.mMaxLen;
     103       802655 :     mControlByte   = aReader.mControlByte;
     104       802655 :     mContainerType = aReader.mContainerType;
     105       802655 :     SetContainerOpen(aReader.IsContainerOpen());
     106              : 
     107              :     // Initialize public data members
     108              : 
     109       802655 :     ImplicitProfileId = aReader.ImplicitProfileId;
     110       802655 :     AppData           = aReader.AppData;
     111       802655 : }
     112              : 
     113     10857218 : TLVType TLVReader::GetType() const
     114              : {
     115     10857218 :     TLVElementType elemType = ElementType();
     116     10857218 :     if (elemType == TLVElementType::EndOfContainer)
     117            4 :         return kTLVType_NotSpecified;
     118     10857214 :     if (elemType == TLVElementType::FloatingPointNumber32 || elemType == TLVElementType::FloatingPointNumber64)
     119        12178 :         return kTLVType_FloatingPointNumber;
     120     10845036 :     if (elemType == TLVElementType::NotSpecified || elemType >= TLVElementType::Null)
     121      4378976 :         return static_cast<TLVType>(elemType);
     122      6466060 :     return static_cast<TLVType>(static_cast<uint8_t>(elemType) & ~kTLVTypeSizeMask);
     123              : }
     124              : 
     125       172439 : uint32_t TLVReader::GetLength() const
     126              : {
     127       172439 :     if (TLVTypeHasLength(ElementType()))
     128       159366 :         return static_cast<uint32_t>(mElemLenOrVal);
     129        13073 :     return 0;
     130              : }
     131              : 
     132      3607013 : CHIP_ERROR TLVReader::Get(bool & v) const
     133              : {
     134      3607013 :     TLVElementType elemType = ElementType();
     135      3607013 :     if (elemType == TLVElementType::BooleanFalse)
     136      1795846 :         v = false;
     137      1811167 :     else if (elemType == TLVElementType::BooleanTrue)
     138      1811166 :         v = true;
     139              :     else
     140            1 :         return CHIP_ERROR_WRONG_TLV_TYPE;
     141      3607012 :     return CHIP_NO_ERROR;
     142              : }
     143              : 
     144      1758057 : CHIP_ERROR TLVReader::Get(int8_t & v) const
     145              : {
     146      1758057 :     int64_t v64    = 0;
     147      1758057 :     CHIP_ERROR err = Get(v64);
     148      1758057 :     if (!CanCastTo<int8_t>(v64))
     149              :     {
     150           40 :         return CHIP_ERROR_INVALID_INTEGER_VALUE;
     151              :     }
     152      1758017 :     v = static_cast<int8_t>(v64);
     153      1758017 :     return err;
     154              : }
     155              : 
     156      1753226 : CHIP_ERROR TLVReader::Get(int16_t & v) const
     157              : {
     158      1753226 :     int64_t v64    = 0;
     159      1753226 :     CHIP_ERROR err = Get(v64);
     160      1753226 :     if (!CanCastTo<int16_t>(v64))
     161              :     {
     162            4 :         return CHIP_ERROR_INVALID_INTEGER_VALUE;
     163              :     }
     164      1753222 :     v = static_cast<int16_t>(v64);
     165      1753222 :     return err;
     166              : }
     167              : 
     168      1753562 : CHIP_ERROR TLVReader::Get(int32_t & v) const
     169              : {
     170      1753562 :     int64_t v64    = 0;
     171      1753562 :     CHIP_ERROR err = Get(v64);
     172      1753562 :     if (!CanCastTo<int32_t>(v64))
     173              :     {
     174            2 :         return CHIP_ERROR_INVALID_INTEGER_VALUE;
     175              :     }
     176      1753560 :     v = static_cast<int32_t>(v64);
     177      1753560 :     return err;
     178              : }
     179              : 
     180      7019195 : CHIP_ERROR TLVReader::Get(int64_t & v) const
     181              : {
     182              :     // Internal callers of this method depend on it not modifying "v" on failure.
     183      7019195 :     switch (ElementType())
     184              :     {
     185      7017649 :     case TLVElementType::Int8:
     186      7017649 :         v = CastToSigned(static_cast<uint8_t>(mElemLenOrVal));
     187      7017649 :         break;
     188          233 :     case TLVElementType::Int16:
     189          233 :         v = CastToSigned(static_cast<uint16_t>(mElemLenOrVal));
     190          233 :         break;
     191          847 :     case TLVElementType::Int32:
     192          847 :         v = CastToSigned(static_cast<uint32_t>(mElemLenOrVal));
     193          847 :         break;
     194           65 :     case TLVElementType::Int64:
     195           65 :         v = CastToSigned(mElemLenOrVal);
     196           65 :         break;
     197          401 :     default:
     198          401 :         return CHIP_ERROR_WRONG_TLV_TYPE;
     199              :     }
     200              : 
     201      7018794 :     return CHIP_NO_ERROR;
     202              : }
     203              : 
     204      1833362 : CHIP_ERROR TLVReader::Get(uint8_t & v) const
     205              : {
     206      1833362 :     uint64_t v64   = 0;
     207      1833362 :     CHIP_ERROR err = Get(v64);
     208      1833362 :     if (!CanCastTo<uint8_t>(v64))
     209              :     {
     210            3 :         return CHIP_ERROR_INVALID_INTEGER_VALUE;
     211              :     }
     212      1833359 :     v = static_cast<uint8_t>(v64);
     213      1833359 :     return err;
     214              : }
     215              : 
     216       375206 : CHIP_ERROR TLVReader::Get(uint16_t & v) const
     217              : {
     218       375206 :     uint64_t v64   = 0;
     219       375206 :     CHIP_ERROR err = Get(v64);
     220       375206 :     if (!CanCastTo<uint16_t>(v64))
     221              :     {
     222            6 :         return CHIP_ERROR_INVALID_INTEGER_VALUE;
     223              :     }
     224       375200 :     v = static_cast<uint16_t>(v64);
     225       375200 :     return err;
     226              : }
     227              : 
     228       123495 : CHIP_ERROR TLVReader::Get(uint32_t & v) const
     229              : {
     230       123495 :     uint64_t v64   = 0;
     231       123495 :     CHIP_ERROR err = Get(v64);
     232       123495 :     if (!CanCastTo<uint32_t>(v64))
     233              :     {
     234            1 :         return CHIP_ERROR_INVALID_INTEGER_VALUE;
     235              :     }
     236       123494 :     v = static_cast<uint32_t>(v64);
     237       123494 :     return err;
     238              : }
     239              : 
     240      2393029 : CHIP_ERROR TLVReader::Get(uint64_t & v) const
     241              : {
     242              :     // Internal callers of this method depend on it not modifying "v" on failure.
     243      2393029 :     switch (ElementType())
     244              :     {
     245       638720 :     case TLVElementType::UInt8:
     246              :     case TLVElementType::UInt16:
     247              :     case TLVElementType::UInt32:
     248              :     case TLVElementType::UInt64:
     249       638720 :         v = mElemLenOrVal;
     250       638720 :         break;
     251      1754309 :     default:
     252      1754309 :         return CHIP_ERROR_WRONG_TLV_TYPE;
     253              :     }
     254       638720 :     return CHIP_NO_ERROR;
     255              : }
     256              : 
     257              : namespace {
     258         2567 : float BitCastToFloat(const uint64_t elemLenOrVal)
     259              : {
     260              :     float f;
     261         2567 :     auto unsigned32 = static_cast<uint32_t>(elemLenOrVal);
     262         2567 :     memcpy(&f, &unsigned32, sizeof(f));
     263         2567 :     return f;
     264              : }
     265              : } // namespace
     266              : 
     267              : // Note: Unlike the integer Get functions, this code avoids doing conversions
     268              : // between float and double wherever possible, because these conversions are
     269              : // relatively expensive on platforms that use soft-float instruction sets.
     270              : 
     271          529 : CHIP_ERROR TLVReader::Get(float & v) const
     272              : {
     273          529 :     switch (ElementType())
     274              :     {
     275          527 :     case TLVElementType::FloatingPointNumber32: {
     276          527 :         v = BitCastToFloat(mElemLenOrVal);
     277          527 :         break;
     278              :     }
     279            2 :     default:
     280            2 :         return CHIP_ERROR_WRONG_TLV_TYPE;
     281              :     }
     282          527 :     return CHIP_NO_ERROR;
     283              : }
     284              : 
     285         4228 : CHIP_ERROR TLVReader::Get(double & v) const
     286              : {
     287         4228 :     switch (ElementType())
     288              :     {
     289         2040 :     case TLVElementType::FloatingPointNumber32: {
     290         2040 :         v = BitCastToFloat(mElemLenOrVal);
     291         2040 :         break;
     292              :     }
     293         2187 :     case TLVElementType::FloatingPointNumber64: {
     294              :         double d;
     295         2187 :         memcpy(&d, &mElemLenOrVal, sizeof(d));
     296         2187 :         v = d;
     297         2187 :         break;
     298              :     }
     299            1 :     default:
     300            1 :         return CHIP_ERROR_WRONG_TLV_TYPE;
     301              :     }
     302         4227 :     return CHIP_NO_ERROR;
     303              : }
     304              : 
     305        15482 : CHIP_ERROR TLVReader::Get(ByteSpan & v) const
     306              : {
     307              :     const uint8_t * val;
     308        15482 :     ReturnErrorOnFailure(GetDataPtr(val));
     309        15478 :     v = ByteSpan(val, GetLength());
     310              : 
     311        15478 :     return CHIP_NO_ERROR;
     312              : }
     313              : 
     314              : namespace {
     315              : constexpr int kUnicodeInformationSeparator1       = 0x1F;
     316              : constexpr size_t kMaxLocalizedStringIdentifierLen = 2 * sizeof(LocalizedStringIdentifier);
     317              : 
     318              : // Shared conformance predicate for TLV UTF-8 character strings (Matter spec §A.11.2 /
     319              : // §7.19.2.40): the bytes must be valid UTF-8 and must not contain ANY 0x00. The spec
     320              : // only forbids a *terminating* NUL, but we additionally reject interior NULs because
     321              : // Matter has no field for which an embedded 0x00 is meaningful and a C/C++ string
     322              : // handler downstream would mis-terminate. Both read-path Get overloads in this TU
     323              : // route through this single predicate so they agree byte-for-byte on what is
     324              : // conformant; tests reach it via the CHIP_CONFIG_TEST-gated ValidateCharStringForTest
     325              : // shim. File-scope (anonymous-namespace) internal linkage — not part of the public API.
     326           19 : CHIP_ERROR ValidateCharString(const CharSpan & str)
     327              : {
     328           19 :     VerifyOrReturnError(Utf8::IsValid(str), CHIP_ERROR_INVALID_UTF8);
     329           11 :     if (!str.empty())
     330              :     {
     331           10 :         VerifyOrReturnError(memchr(str.data(), 0, str.size()) == nullptr, CHIP_ERROR_INVALID_TLV_CHAR_STRING);
     332              :     }
     333            4 :     return CHIP_NO_ERROR;
     334              : }
     335              : } // namespace
     336              : 
     337         1217 : CHIP_ERROR TLVReader::Get(CharSpan & v) const
     338              : {
     339         1217 :     if (!TLVTypeIsUTF8String(ElementType()))
     340              :     {
     341            2 :         return CHIP_ERROR_WRONG_TLV_TYPE;
     342              :     }
     343              : 
     344              :     const uint8_t * bytes;
     345         1215 :     ReturnErrorOnFailure(GetDataPtr(bytes)); // Does length sanity checks
     346         1213 :     if (bytes == nullptr)
     347              :     {
     348              :         // Calling memchr further down with bytes == nullptr would have undefined behaviour, exiting early.
     349          149 :         v = {}; // empty data
     350          149 :         return CHIP_NO_ERROR;
     351              :     }
     352              : 
     353         1064 :     uint32_t len = GetLength();
     354              : 
     355              :     // If Unicode Information Separator 1 (0x1f) is present in the string then method returns
     356              :     // string ending at first appearance of the Information Separator 1.
     357         1064 :     const uint8_t * infoSeparator = reinterpret_cast<const uint8_t *>(memchr(bytes, kUnicodeInformationSeparator1, len));
     358         1064 :     if (infoSeparator != nullptr)
     359              :     {
     360           12 :         len = static_cast<uint32_t>(infoSeparator - bytes);
     361              :     }
     362              : 
     363         1064 :     v = CharSpan(Uint8::to_const_char(bytes), len);
     364              : 
     365              : #if CHIP_CONFIG_TLV_VALIDATE_CHAR_STRING_ON_READ
     366              :     // Read-side strict validation is opt-in (default off in core.gni). The default keeps
     367              :     // the historical lenient decode because some deployed accessories ship char strings
     368              :     // that fail strict UTF-8 / no-NUL validation (e.g. raw FreeRTOS buffers in place of
     369              :     // UTF-8 text); flipping this on by default would cause controllers to start rejecting
     370              :     // payloads they previously accepted. Integrators who want strict enforcement set the
     371              :     // GN flag explicitly.
     372              :     //
     373              :     // When enabled, validation runs on the FULL on-wire span (pre- and post-IS1 alike) per
     374              :     // Matter spec §A.11.2 — strings MUST be UTF-8 and may contain an IS1 separator — even
     375              :     // though `v` is truncated at IS1 for caller convenience, so this overload's verdict
     376              :     // matches Get(LSID&)'s on the same bytes.
     377              :     CharSpan full(Uint8::to_const_char(bytes), GetLength());
     378              :     ReturnErrorOnFailure(ValidateCharString(full));
     379              : #endif // CHIP_CONFIG_TLV_VALIDATE_CHAR_STRING_ON_READ
     380              : 
     381         1064 :     return CHIP_NO_ERROR;
     382              : }
     383              : 
     384           18 : CHIP_ERROR TLVReader::Get(Optional<LocalizedStringIdentifier> & lsid)
     385              : {
     386              : #if CHIP_CONFIG_TLV_VALIDATE_CHAR_STRING_ON_READ
     387              :     constexpr bool validateCharString = true;
     388              : #else
     389           18 :     constexpr bool validateCharString = false;
     390              : #endif // CHIP_CONFIG_TLV_VALIDATE_CHAR_STRING_ON_READ
     391           18 :     return GetLocalizedStringIdentifierImpl(lsid, validateCharString);
     392              : }
     393              : 
     394           24 : CHIP_ERROR TLVReader::GetLocalizedStringIdentifierImpl(Optional<LocalizedStringIdentifier> & lsid, bool validateCharString)
     395              : {
     396           24 :     lsid.ClearValue();
     397           24 :     VerifyOrReturnError(TLVTypeIsUTF8String(ElementType()), CHIP_ERROR_WRONG_TLV_TYPE);
     398              : 
     399              :     const uint8_t * bytes;
     400           23 :     ReturnErrorOnFailure(GetDataPtr(bytes)); // Does length sanity checks
     401           23 :     if (bytes == nullptr)
     402              :     {
     403              :         // Treat null/empty LSID as a NullOptional (cleared above).
     404            0 :         return CHIP_NO_ERROR;
     405              :     }
     406              : 
     407           23 :     uint32_t len = GetLength();
     408              : 
     409           23 :     const uint8_t * infoSeparator1 = static_cast<const uint8_t *>(memchr(bytes, kUnicodeInformationSeparator1, len));
     410           23 :     if (infoSeparator1 == nullptr)
     411              :     {
     412              :         // No IS1: by contract this overload reports only the LSID suffix and does not
     413              :         // UTF-8-validate the whole string (callers wanting that use Get(CharSpan&)).
     414            1 :         return CHIP_NO_ERROR;
     415              :     }
     416              : 
     417              :     // When requested, validate the entire on-wire char string so this overload's verdict
     418              :     // matches Get(CharSpan&)'s on the same bytes.
     419           22 :     if (validateCharString)
     420              :     {
     421            4 :         CharSpan full(Uint8::to_const_char(bytes), len);
     422            4 :         ReturnErrorOnFailure(ValidateCharString(full));
     423              :     }
     424              : 
     425           19 :     const uint8_t * lsidPtr = infoSeparator1 + 1;
     426           19 :     len -= static_cast<uint32_t>(lsidPtr - bytes);
     427              : 
     428           19 :     const uint8_t * infoSeparator2 = static_cast<const uint8_t *>(memchr(lsidPtr, kUnicodeInformationSeparator1, len));
     429           19 :     if (infoSeparator2 != nullptr)
     430              :     {
     431            3 :         len = static_cast<uint32_t>(infoSeparator2 - lsidPtr);
     432              :     }
     433           19 :     if (len == 0)
     434              :     {
     435              :         // This treats null/empty LSID as a NullOptional (we clear the value at the start)
     436            1 :         return CHIP_NO_ERROR;
     437              :     }
     438           18 :     VerifyOrReturnError(len <= kMaxLocalizedStringIdentifierLen, CHIP_ERROR_INVALID_TLV_ELEMENT);
     439              :     // Leading zeroes are not allowed.
     440           17 :     VerifyOrReturnError(static_cast<char>(lsidPtr[0]) != '0', CHIP_ERROR_INVALID_TLV_ELEMENT);
     441              : 
     442           15 :     char idStr[kMaxLocalizedStringIdentifierLen] = { '0', '0', '0', '0' };
     443           15 :     memcpy(&idStr[kMaxLocalizedStringIdentifierLen - len], lsidPtr, len);
     444              : 
     445              :     LocalizedStringIdentifier id;
     446           15 :     VerifyOrReturnError(Encoding::UppercaseHexToUint16(idStr, sizeof(idStr), id) == sizeof(LocalizedStringIdentifier),
     447              :                         CHIP_ERROR_INVALID_TLV_ELEMENT);
     448              : 
     449           14 :     lsid.SetValue(id);
     450           14 :     return CHIP_NO_ERROR;
     451              : }
     452              : 
     453              : #if CHIP_CONFIG_TEST
     454           15 : CHIP_ERROR ValidateCharStringForTest(const CharSpan & str)
     455              : {
     456           15 :     return ValidateCharString(str);
     457              : }
     458              : 
     459            6 : CHIP_ERROR GetLocalizedStringIdentifierForTest(TLVReader & reader, Optional<LocalizedStringIdentifier> & lsid,
     460              :                                                bool validateCharString)
     461              : {
     462            6 :     return reader.GetLocalizedStringIdentifierImpl(lsid, validateCharString);
     463              : }
     464              : #endif // CHIP_CONFIG_TEST
     465              : 
     466        26467 : CHIP_ERROR TLVReader::GetBytes(uint8_t * buf, size_t bufSize)
     467              : {
     468        26467 :     if (!TLVTypeIsString(ElementType()))
     469            1 :         return CHIP_ERROR_WRONG_TLV_TYPE;
     470              : 
     471        26466 :     if (mElemLenOrVal > bufSize)
     472            0 :         return CHIP_ERROR_BUFFER_TOO_SMALL;
     473              : 
     474        26466 :     CHIP_ERROR err = ReadData(buf, static_cast<uint32_t>(mElemLenOrVal));
     475        52932 :     if (err != CHIP_NO_ERROR)
     476            0 :         return err;
     477              : 
     478        26466 :     mElemLenOrVal = 0;
     479              : 
     480        26466 :     return CHIP_NO_ERROR;
     481              : }
     482              : 
     483        12594 : CHIP_ERROR TLVReader::GetString(char * buf, size_t bufSize)
     484              : {
     485        12594 :     if (!TLVTypeIsString(ElementType()))
     486            1 :         return CHIP_ERROR_WRONG_TLV_TYPE;
     487              : 
     488        12593 :     if (mElemLenOrVal >= bufSize)
     489            3 :         return CHIP_ERROR_BUFFER_TOO_SMALL;
     490              : 
     491        12590 :     buf[mElemLenOrVal] = 0;
     492              : 
     493        12590 :     return GetBytes(reinterpret_cast<uint8_t *>(buf), static_cast<uint32_t>(mElemLenOrVal));
     494              : }
     495              : 
     496            1 : CHIP_ERROR TLVReader::DupBytes(uint8_t *& buf, uint32_t & dataLen)
     497              : {
     498            1 :     if (!TLVTypeIsString(ElementType()))
     499            0 :         return CHIP_ERROR_WRONG_TLV_TYPE;
     500              : 
     501            1 :     buf = static_cast<uint8_t *>(chip::Platform::MemoryAlloc(static_cast<uint32_t>(mElemLenOrVal)));
     502            1 :     if (buf == nullptr)
     503            0 :         return CHIP_ERROR_NO_MEMORY;
     504              : 
     505            1 :     CHIP_ERROR err = ReadData(buf, static_cast<uint32_t>(mElemLenOrVal));
     506            2 :     if (err != CHIP_NO_ERROR)
     507              :     {
     508            0 :         chip::Platform::MemoryFree(buf);
     509            0 :         buf = nullptr;
     510            0 :         return err;
     511              :     }
     512              : 
     513            1 :     dataLen       = static_cast<uint32_t>(mElemLenOrVal);
     514            1 :     mElemLenOrVal = 0;
     515              : 
     516            1 :     return CHIP_NO_ERROR;
     517              : }
     518              : 
     519            2 : CHIP_ERROR TLVReader::DupString(char *& buf)
     520              : {
     521            2 :     if (!TLVTypeIsString(ElementType()))
     522            1 :         return CHIP_ERROR_WRONG_TLV_TYPE;
     523              : 
     524            1 :     if (mElemLenOrVal > UINT32_MAX - 1)
     525            0 :         return CHIP_ERROR_NO_MEMORY;
     526              : 
     527            1 :     buf = static_cast<char *>(chip::Platform::MemoryAlloc(static_cast<uint32_t>(mElemLenOrVal + 1)));
     528            1 :     if (buf == nullptr)
     529            0 :         return CHIP_ERROR_NO_MEMORY;
     530              : 
     531            1 :     CHIP_ERROR err = ReadData(reinterpret_cast<uint8_t *>(buf), static_cast<uint32_t>(mElemLenOrVal));
     532            2 :     if (err != CHIP_NO_ERROR)
     533              :     {
     534            0 :         chip::Platform::MemoryFree(buf);
     535            0 :         buf = nullptr;
     536            0 :         return err;
     537              :     }
     538              : 
     539            1 :     buf[mElemLenOrVal] = 0;
     540            1 :     mElemLenOrVal      = 0;
     541              : 
     542            1 :     return err;
     543              : }
     544              : 
     545        31835 : CHIP_ERROR TLVReader::GetDataPtr(const uint8_t *& data) const
     546              : {
     547        31835 :     VerifyOrReturnError(TLVTypeIsString(ElementType()), CHIP_ERROR_WRONG_TLV_TYPE);
     548              : 
     549        31832 :     if (GetLength() == 0)
     550              :     {
     551         4795 :         data = nullptr;
     552         4795 :         return CHIP_NO_ERROR;
     553              :     }
     554              : 
     555        27037 :     uint32_t remainingLen = static_cast<decltype(mMaxLen)>(mBufEnd - mReadPoint);
     556              : 
     557              :     // Verify that the entirety of the data is available in the buffer.
     558              :     // Note that this may not be possible if the reader is reading from a chain of buffers.
     559        27037 :     VerifyOrReturnError(remainingLen >= static_cast<uint32_t>(mElemLenOrVal), CHIP_ERROR_TLV_UNDERRUN);
     560        27033 :     data = mReadPoint;
     561        27033 :     return CHIP_NO_ERROR;
     562              : }
     563              : 
     564         1873 : CHIP_ERROR TLVReader::OpenContainer(TLVReader & containerReader)
     565              : {
     566         1873 :     TLVElementType elemType = ElementType();
     567         1873 :     if (!TLVTypeIsContainer(elemType))
     568            1 :         return CHIP_ERROR_INCORRECT_STATE;
     569              : 
     570         1872 :     containerReader.mBackingStore = mBackingStore;
     571         1872 :     containerReader.mReadPoint    = mReadPoint;
     572         1872 :     containerReader.mBufEnd       = mBufEnd;
     573         1872 :     containerReader.mLenRead      = mLenRead;
     574         1872 :     containerReader.mMaxLen       = mMaxLen;
     575         1872 :     containerReader.ClearElementState();
     576         1872 :     containerReader.mContainerType = static_cast<TLVType>(elemType);
     577         1872 :     containerReader.SetContainerOpen(false);
     578         1872 :     containerReader.ImplicitProfileId = ImplicitProfileId;
     579         1872 :     containerReader.AppData           = AppData;
     580              : 
     581         1872 :     SetContainerOpen(true);
     582              : 
     583         1872 :     return CHIP_NO_ERROR;
     584              : }
     585              : 
     586         1566 : CHIP_ERROR TLVReader::CloseContainer(TLVReader & containerReader)
     587              : {
     588              :     CHIP_ERROR err;
     589              : 
     590         1566 :     if (!IsContainerOpen())
     591            1 :         return CHIP_ERROR_INCORRECT_STATE;
     592              : 
     593         1565 :     if (static_cast<TLVElementType>(containerReader.mContainerType) != ElementType())
     594            0 :         return CHIP_ERROR_INCORRECT_STATE;
     595              : 
     596         1565 :     err = containerReader.SkipToEndOfContainer();
     597         3130 :     if (err != CHIP_NO_ERROR)
     598            0 :         return err;
     599              : 
     600         1565 :     mBackingStore = containerReader.mBackingStore;
     601         1565 :     mReadPoint    = containerReader.mReadPoint;
     602         1565 :     mBufEnd       = containerReader.mBufEnd;
     603         1565 :     mLenRead      = containerReader.mLenRead;
     604         1565 :     mMaxLen       = containerReader.mMaxLen;
     605         1565 :     ClearElementState();
     606              : 
     607         1565 :     return CHIP_NO_ERROR;
     608              : }
     609              : 
     610      4223666 : CHIP_ERROR TLVReader::EnterContainer(TLVType & outerContainerType)
     611              : {
     612      4223666 :     TLVElementType elemType = ElementType();
     613      4223666 :     if (!TLVTypeIsContainer(elemType))
     614            1 :         return CHIP_ERROR_INCORRECT_STATE;
     615              : 
     616      4223665 :     outerContainerType = mContainerType;
     617      4223665 :     mContainerType     = static_cast<TLVType>(elemType);
     618              : 
     619      4223665 :     ClearElementState();
     620      4223665 :     SetContainerOpen(false);
     621              : 
     622      4223665 :     return CHIP_NO_ERROR;
     623              : }
     624              : 
     625       643061 : CHIP_ERROR TLVReader::ExitContainer(TLVType outerContainerType)
     626              : {
     627              :     CHIP_ERROR err;
     628              : 
     629       643061 :     err = SkipToEndOfContainer();
     630      1286122 :     if (err != CHIP_NO_ERROR)
     631           43 :         return err;
     632              : 
     633       643018 :     mContainerType = outerContainerType;
     634       643018 :     ClearElementState();
     635              : 
     636       643018 :     return CHIP_NO_ERROR;
     637              : }
     638              : 
     639         8520 : CHIP_ERROR TLVReader::VerifyEndOfContainer()
     640              : {
     641         8520 :     CHIP_ERROR err = Next();
     642        17040 :     if (err == CHIP_END_OF_TLV)
     643         8517 :         return CHIP_NO_ERROR;
     644            6 :     if (err == CHIP_NO_ERROR)
     645            2 :         return CHIP_ERROR_UNEXPECTED_TLV_ELEMENT;
     646            1 :     return err;
     647              : }
     648              : 
     649     10935624 : CHIP_ERROR TLVReader::Next()
     650              : {
     651     10935624 :     ReturnErrorOnFailure(Skip());
     652     10931891 :     ReturnErrorOnFailure(ReadElement());
     653              : 
     654     10901745 :     TLVElementType elemType = ElementType();
     655              : 
     656     10901745 :     VerifyOrReturnError(elemType != TLVElementType::EndOfContainer, CHIP_END_OF_TLV);
     657              : 
     658              :     // Ensure that GetDataPtr calls can be called immediately after Next, so
     659              :     // that `Get(ByteSpan&)` does not need to advance buffers and just works
     660     10631111 :     if (TLVTypeIsString(elemType) && (GetLength() != 0))
     661              :     {
     662        49599 :         ReturnErrorOnFailure(EnsureData(CHIP_ERROR_TLV_UNDERRUN));
     663              :     }
     664              : 
     665     10631111 :     return CHIP_NO_ERROR;
     666              : }
     667              : 
     668       531731 : CHIP_ERROR TLVReader::Expect(Tag expectedTag)
     669              : {
     670       531731 :     VerifyOrReturnError(GetType() != kTLVType_NotSpecified, CHIP_ERROR_WRONG_TLV_TYPE);
     671       531727 :     VerifyOrReturnError(GetTag() == expectedTag, CHIP_ERROR_UNEXPECTED_TLV_ELEMENT);
     672       531678 :     return CHIP_NO_ERROR;
     673              : }
     674              : 
     675       530940 : CHIP_ERROR TLVReader::Next(Tag expectedTag)
     676              : {
     677       530940 :     ReturnErrorOnFailure(Next());
     678       527989 :     ReturnErrorOnFailure(Expect(expectedTag));
     679       527943 :     return CHIP_NO_ERROR;
     680              : }
     681              : 
     682      9052370 : CHIP_ERROR TLVReader::Expect(TLVType expectedType, Tag expectedTag)
     683              : {
     684      9052370 :     VerifyOrReturnError(GetType() == expectedType, CHIP_ERROR_WRONG_TLV_TYPE);
     685      9042099 :     VerifyOrReturnError(GetTag() == expectedTag, CHIP_ERROR_UNEXPECTED_TLV_ELEMENT);
     686      8968383 :     return CHIP_NO_ERROR;
     687              : }
     688              : 
     689      9045353 : CHIP_ERROR TLVReader::Next(TLVType expectedType, Tag expectedTag)
     690              : {
     691      9045353 :     ReturnErrorOnFailure(Next());
     692      9030565 :     ReturnErrorOnFailure(Expect(expectedType, expectedTag));
     693      8947567 :     return CHIP_NO_ERROR;
     694              : }
     695              : 
     696     10964909 : CHIP_ERROR TLVReader::Skip()
     697              : {
     698     10964909 :     const TLVElementType elemType = ElementType();
     699     10964909 :     VerifyOrReturnError(elemType != TLVElementType::EndOfContainer, CHIP_END_OF_TLV);
     700              : 
     701     10961179 :     if (TLVTypeIsContainer(elemType))
     702              :     {
     703              :         TLVType outerContainerType;
     704       278837 :         ReturnErrorOnFailure(EnterContainer(outerContainerType));
     705       278837 :         return ExitContainer(outerContainerType);
     706              :     }
     707              : 
     708     10682342 :     ReturnErrorOnFailure(SkipData());
     709     10682342 :     ClearElementState();
     710              : 
     711     10682342 :     return CHIP_NO_ERROR;
     712              : }
     713              : 
     714              : /**
     715              :  * Clear the state of the TLVReader.
     716              :  * This method is used to position the reader before the first TLV,
     717              :  * between TLVs or after the last TLV.
     718              :  */
     719     17572768 : void TLVReader::ClearElementState()
     720              : {
     721     17572768 :     mElemTag      = AnonymousTag();
     722     17572768 :     mControlByte  = kTLVControlByte_NotSpecified;
     723     17572768 :     mElemLenOrVal = 0;
     724     17572768 : }
     725              : 
     726              : /**
     727              :  * Skip any data contained in the current TLV by reading over it without
     728              :  * a destination buffer.
     729              :  *
     730              :  * @retval #CHIP_NO_ERROR              If the reader was successfully positioned at the end of the
     731              :  *                                      data.
     732              :  * @retval other                        Other CHIP or platform error codes returned by the configured
     733              :  *                                      TLVBackingStore.
     734              :  */
     735     14552847 : CHIP_ERROR TLVReader::SkipData()
     736              : {
     737     14552847 :     CHIP_ERROR err          = CHIP_NO_ERROR;
     738     14552847 :     TLVElementType elemType = ElementType();
     739              : 
     740     14552847 :     if (TLVTypeHasLength(elemType))
     741              :     {
     742       327571 :         err = ReadData(nullptr, static_cast<uint32_t>(mElemLenOrVal));
     743              :     }
     744              : 
     745     14552847 :     return err;
     746              : }
     747              : 
     748       644626 : CHIP_ERROR TLVReader::SkipToEndOfContainer()
     749              : {
     750              :     CHIP_ERROR err;
     751       644626 :     TLVType outerContainerType = mContainerType;
     752       644626 :     uint32_t nestLevel         = 0;
     753              : 
     754              :     // If the user calls Next() after having called OpenContainer() but before calling
     755              :     // CloseContainer() they're effectively doing a close container by skipping over
     756              :     // the container element.  So reset the 'container open' flag here to prevent them
     757              :     // from calling CloseContainer() with the now orphaned container reader.
     758       644626 :     SetContainerOpen(false);
     759              : 
     760              :     while (true)
     761              :     {
     762      4515088 :         TLVElementType elemType = ElementType();
     763              : 
     764      4515088 :         if (elemType == TLVElementType::EndOfContainer)
     765              :         {
     766      1341614 :             if (nestLevel == 0)
     767       644583 :                 return CHIP_NO_ERROR;
     768              : 
     769       697031 :             nestLevel--;
     770       697031 :             mContainerType = (nestLevel == 0) ? outerContainerType : kTLVType_UnknownContainer;
     771              :         }
     772              : 
     773      3173474 :         else if (TLVTypeIsContainer(elemType))
     774              :         {
     775       697033 :             nestLevel++;
     776       697033 :             mContainerType = static_cast<TLVType>(elemType);
     777              :         }
     778              : 
     779      3870505 :         err = SkipData();
     780      7741010 :         if (err != CHIP_NO_ERROR)
     781            0 :             return err;
     782              : 
     783      3870505 :         err = ReadElement();
     784      7741010 :         if (err != CHIP_NO_ERROR)
     785           43 :             return err;
     786      3870462 :     }
     787              : }
     788              : 
     789     14802396 : CHIP_ERROR TLVReader::ReadElement()
     790              : {
     791              :     // Make sure we have input data. Return CHIP_END_OF_TLV if no more data is available.
     792     14802396 :     ReturnErrorOnFailure(EnsureData(CHIP_END_OF_TLV));
     793     14786410 :     VerifyOrReturnError(mReadPoint != nullptr, CHIP_ERROR_INVALID_TLV_ELEMENT);
     794              : 
     795              :     // Get the element's control byte.
     796     14786410 :     mControlByte = *mReadPoint;
     797              : 
     798              :     // Extract the element type from the control byte. Fail if it's invalid.
     799     14786410 :     TLVElementType elemType = ElementType();
     800     14786410 :     VerifyOrReturnError(IsValidTLVType(elemType), CHIP_ERROR_INVALID_TLV_ELEMENT);
     801              : 
     802              :     // Extract the tag control from the control byte.
     803     14780975 :     TLVTagControl tagControl = static_cast<TLVTagControl>(mControlByte & kTLVTagControlMask);
     804              : 
     805              :     // Determine the number of bytes in the element's tag, if any.
     806     14780975 :     uint8_t tagBytes = sTagSizes[tagControl >> kTLVTagControlShift];
     807              : 
     808              :     // Extract the size of length/value field from the control byte.
     809     14780975 :     TLVFieldSize lenOrValFieldSize = GetTLVFieldSize(elemType);
     810              : 
     811              :     // Determine the number of bytes in the length/value field.
     812     14780975 :     const uint8_t valOrLenBytes = TLVFieldSizeToBytes(lenOrValFieldSize);
     813              : 
     814              :     // Determine the number of bytes in the element's 'head'. This includes: the control byte, the tag bytes (if present), the
     815              :     // length bytes (if present), and for elements that don't have a length (e.g. integers), the value bytes.
     816     14780975 :     const uint8_t elemHeadBytes = static_cast<uint8_t>(1 + tagBytes + valOrLenBytes);
     817              : 
     818              :     // 17 = 1 control byte + 8 tag bytes + 8 length/value bytes
     819              :     uint8_t stagingBuf[17];
     820              : 
     821              :     // Odd workaround: clang-tidy claims garbage value otherwise as it does not
     822              :     // understand that ReadData initializes stagingBuf
     823     14780975 :     stagingBuf[1] = 0;
     824              : 
     825              :     // If the head of the element goes past the end of the current input buffer,
     826              :     // we need to read it into the staging buffer to parse it.  Just do that unconditionally,
     827              :     // even if the head does not go past end of current buffer, to save codesize.
     828     14780975 :     ReturnErrorOnFailure(ReadData(stagingBuf, elemHeadBytes));
     829              : 
     830              :     // +1 to skip over the control byte
     831     14780971 :     const uint8_t * p = stagingBuf + 1;
     832              : 
     833              :     // Read the tag field, if present.
     834     14780971 :     mElemTag      = ReadTag(tagControl, p);
     835     14780971 :     mElemLenOrVal = 0;
     836              : 
     837              :     // Read the length/value field, if present.
     838              :     // NOTE: this is works because even though we only memcpy a subset of values and leave
     839              :     //       the rest 0. Value looks like "<le-byte> <le-byte> ... <le-byte> 0 0 ... 0"
     840              :     //       which is the TLV format. HostSwap ensures this becomes a real host value
     841              :     //       (should be a NOOP on LE machines, will full-swap on big-endian machines)
     842     14780971 :     memcpy(&mElemLenOrVal, p, valOrLenBytes);
     843     14780971 :     LittleEndian::HostSwap(mElemLenOrVal);
     844              : 
     845     14780971 :     VerifyOrReturnError(!TLVTypeHasLength(elemType) || (mElemLenOrVal <= UINT32_MAX), CHIP_ERROR_NOT_IMPLEMENTED);
     846              : 
     847     14779411 :     return VerifyElement();
     848              : }
     849              : 
     850     14779411 : CHIP_ERROR TLVReader::VerifyElement()
     851              : {
     852     14779411 :     if (ElementType() == TLVElementType::EndOfContainer)
     853              :     {
     854      1406200 :         if (mContainerType == kTLVType_NotSpecified)
     855          159 :             return CHIP_ERROR_INVALID_TLV_ELEMENT;
     856      1406041 :         if (mElemTag != AnonymousTag())
     857          534 :             return CHIP_ERROR_INVALID_TLV_TAG;
     858              :     }
     859              :     else
     860              :     {
     861     13373211 :         if (mElemTag == UnknownImplicitTag())
     862            0 :             return CHIP_ERROR_UNKNOWN_IMPLICIT_TLV_TAG;
     863     13373211 :         switch (mContainerType)
     864              :         {
     865      2028179 :         case kTLVType_NotSpecified:
     866      2028179 :             if (IsContextTag(mElemTag))
     867          409 :                 return CHIP_ERROR_INVALID_TLV_TAG;
     868      2027770 :             break;
     869      7604306 :         case kTLVType_Structure:
     870      7604306 :             if (mElemTag == AnonymousTag())
     871         1247 :                 return CHIP_ERROR_INVALID_TLV_TAG;
     872      7603059 :             break;
     873      2192982 :         case kTLVType_Array:
     874      2192982 :             if (mElemTag != AnonymousTag())
     875         2990 :                 return CHIP_ERROR_INVALID_TLV_TAG;
     876      2189992 :             break;
     877      1547744 :         case kTLVType_UnknownContainer:
     878              :         case kTLVType_List:
     879      1547744 :             break;
     880            0 :         default:
     881            0 :             return CHIP_ERROR_INCORRECT_STATE;
     882              :         }
     883              :     }
     884              : 
     885              :     // If the current element encodes a specific length (e.g. a UTF8 string or a byte string), verify
     886              :     // that the purported length fits within the remaining bytes of the encoding (as delineated by mMaxLen).
     887              :     //
     888              :     // Note that this check is not strictly necessary to prevent runtime errors, as any attempt to access
     889              :     // the data of an element with an invalid length will result in an error.  However checking the length
     890              :     // here catches the error earlier, and ensures that the application will never see the erroneous length
     891              :     // value.
     892              :     //
     893     14774072 :     if (TLVTypeHasLength(ElementType()))
     894              :     {
     895       334561 :         uint32_t overallLenRemaining = mMaxLen - mLenRead;
     896       334561 :         if (overallLenRemaining < static_cast<uint32_t>(mElemLenOrVal))
     897         1865 :             return CHIP_ERROR_TLV_UNDERRUN;
     898              :     }
     899              : 
     900     14772207 :     return CHIP_NO_ERROR;
     901              : }
     902              : 
     903     14780971 : Tag TLVReader::ReadTag(TLVTagControl tagControl, const uint8_t *& p) const
     904              : {
     905              :     uint16_t vendorId;
     906              :     uint16_t profileNum;
     907              : 
     908     14780971 :     switch (tagControl)
     909              :     {
     910      5501715 :     case TLVTagControl::ContextSpecific:
     911      5501715 :         return ContextTag(Read8(p));
     912         2408 :     case TLVTagControl::CommonProfile_2Bytes:
     913         2408 :         return CommonTag(LittleEndian::Read16(p));
     914         2664 :     case TLVTagControl::CommonProfile_4Bytes:
     915         2664 :         return CommonTag(LittleEndian::Read32(p));
     916      1784749 :     case TLVTagControl::ImplicitProfile_2Bytes:
     917      1784749 :         if (ImplicitProfileId == kProfileIdNotSpecified)
     918            0 :             return UnknownImplicitTag();
     919      1784749 :         return ProfileTag(ImplicitProfileId, LittleEndian::Read16(p));
     920         3643 :     case TLVTagControl::ImplicitProfile_4Bytes:
     921         3643 :         if (ImplicitProfileId == kProfileIdNotSpecified)
     922            0 :             return UnknownImplicitTag();
     923         3643 :         return ProfileTag(ImplicitProfileId, LittleEndian::Read32(p));
     924      3669579 :     case TLVTagControl::FullyQualified_6Bytes:
     925      3669579 :         vendorId   = LittleEndian::Read16(p);
     926      3669579 :         profileNum = LittleEndian::Read16(p);
     927      3669579 :         return ProfileTag(vendorId, profileNum, LittleEndian::Read16(p));
     928         2333 :     case TLVTagControl::FullyQualified_8Bytes:
     929         2333 :         vendorId   = LittleEndian::Read16(p);
     930         2333 :         profileNum = LittleEndian::Read16(p);
     931         2333 :         return ProfileTag(vendorId, profileNum, LittleEndian::Read32(p));
     932      3813880 :     case TLVTagControl::Anonymous:
     933              :     default:
     934      3813880 :         return AnonymousTag();
     935              :     }
     936              : }
     937              : 
     938     15157645 : CHIP_ERROR TLVReader::ReadData(uint8_t * buf, uint32_t len)
     939              : {
     940     30035918 :     while (len > 0)
     941              :     {
     942     14878277 :         ReturnErrorOnFailure(EnsureData(CHIP_ERROR_TLV_UNDERRUN));
     943              : 
     944     14878273 :         uint32_t remainingLen = static_cast<decltype(mMaxLen)>(mBufEnd - mReadPoint);
     945              : 
     946     14878273 :         uint32_t readLen = len;
     947     14878273 :         if (readLen > remainingLen)
     948          161 :             readLen = remainingLen;
     949              : 
     950     14878273 :         if (buf != nullptr)
     951              :         {
     952     14812303 :             memcpy(buf, mReadPoint, readLen);
     953     14812303 :             buf += readLen;
     954              :         }
     955     14878273 :         mReadPoint += readLen;
     956     14878273 :         mLenRead += readLen;
     957     14878273 :         len -= readLen;
     958              :     }
     959              : 
     960     15157641 :     return CHIP_NO_ERROR;
     961              : }
     962              : 
     963     29730272 : CHIP_ERROR TLVReader::EnsureData(CHIP_ERROR noDataErr)
     964              : {
     965     29730272 :     if (mReadPoint == mBufEnd)
     966              :     {
     967        16277 :         VerifyOrReturnError((mLenRead != mMaxLen) && (mBackingStore != nullptr), noDataErr);
     968              : 
     969              :         uint32_t bufLen;
     970          287 :         ReturnErrorOnFailure(mBackingStore->GetNextBuffer(*this, mReadPoint, bufLen));
     971          287 :         VerifyOrReturnError(bufLen > 0, noDataErr);
     972              : 
     973              :         // Cap mBufEnd so that we don't read beyond the user's specified maximum length, even
     974              :         // if the underlying buffer is larger.
     975          287 :         bufLen  = std::min(bufLen, mMaxLen - mLenRead);
     976          287 :         mBufEnd = mReadPoint + bufLen;
     977              :     }
     978              : 
     979     29714282 :     return CHIP_NO_ERROR;
     980              : }
     981              : 
     982              : /**
     983              :  * This is a private method used to compute the length of a TLV element head.
     984              :  */
     985            2 : CHIP_ERROR TLVReader::GetElementHeadLength(uint8_t & elemHeadBytes) const
     986              : {
     987              :     uint8_t tagBytes;
     988              :     uint8_t valOrLenBytes;
     989              :     TLVTagControl tagControl;
     990              :     TLVFieldSize lenOrValFieldSize;
     991            2 :     TLVElementType elemType = ElementType();
     992              : 
     993              :     // Verify element is of valid TLVType.
     994            2 :     VerifyOrReturnError(IsValidTLVType(elemType), CHIP_ERROR_INVALID_TLV_ELEMENT);
     995              : 
     996              :     // Extract the tag control from the control byte.
     997            2 :     tagControl = static_cast<TLVTagControl>(mControlByte & kTLVTagControlMask);
     998              : 
     999              :     // Determine the number of bytes in the element's tag, if any.
    1000            2 :     tagBytes = sTagSizes[tagControl >> kTLVTagControlShift];
    1001              : 
    1002              :     // Extract the size of length/value field from the control byte.
    1003            2 :     lenOrValFieldSize = GetTLVFieldSize(elemType);
    1004              : 
    1005              :     // Determine the number of bytes in the length/value field.
    1006            2 :     valOrLenBytes = TLVFieldSizeToBytes(lenOrValFieldSize);
    1007              : 
    1008              :     // Determine the number of bytes in the element's 'head'. This includes: the
    1009              :     // control byte, the tag bytes (if present), the length bytes (if present),
    1010              :     // and for elements that don't have a length (e.g. integers), the value
    1011              :     // bytes.
    1012            2 :     VerifyOrReturnError(CanCastTo<uint8_t>(1 + tagBytes + valOrLenBytes), CHIP_ERROR_INTERNAL);
    1013            2 :     elemHeadBytes = static_cast<uint8_t>(1 + tagBytes + valOrLenBytes);
    1014              : 
    1015            2 :     return CHIP_NO_ERROR;
    1016              : }
    1017              : 
    1018              : /**
    1019              :  * This is a private method that returns the TLVElementType from mControlByte
    1020              :  */
    1021    113655086 : TLVElementType TLVReader::ElementType() const
    1022              : {
    1023    113655086 :     if (mControlByte == static_cast<uint16_t>(kTLVControlByte_NotSpecified))
    1024     13170402 :         return TLVElementType::NotSpecified;
    1025    100484684 :     return static_cast<TLVElementType>(mControlByte & kTLVTypeMask);
    1026              : }
    1027              : 
    1028       217716 : CHIP_ERROR TLVReader::FindElementWithTag(Tag tag, TLVReader & destReader) const
    1029              : {
    1030       217716 :     CHIP_ERROR err = CHIP_NO_ERROR;
    1031              : 
    1032       217716 :     chip::TLV::TLVReader reader;
    1033       217716 :     reader.Init(*this);
    1034              : 
    1035      1008198 :     while (CHIP_NO_ERROR == (err = reader.Next()))
    1036              :     {
    1037       468806 :         VerifyOrExit(chip::TLV::kTLVType_NotSpecified != reader.GetType(), err = CHIP_ERROR_INVALID_TLV_ELEMENT);
    1038              : 
    1039       468806 :         if (tag == reader.GetTag())
    1040              :         {
    1041       182423 :             destReader.Init(reader);
    1042       182423 :             break;
    1043              :         }
    1044              :     }
    1045              : 
    1046        35293 : exit:
    1047       470725 :     ChipLogIfFalse((CHIP_NO_ERROR == err) || (CHIP_END_OF_TLV == err));
    1048              : 
    1049       217716 :     return err;
    1050              : }
    1051              : 
    1052         1660 : CHIP_ERROR TLVReader::CountRemainingInContainer(size_t * size) const
    1053              : {
    1054         1660 :     if (mContainerType == kTLVType_NotSpecified)
    1055              :     {
    1056            0 :         return CHIP_ERROR_INCORRECT_STATE;
    1057              :     }
    1058              : 
    1059         1660 :     TLVReader tempReader(*this);
    1060         1660 :     size_t count = 0;
    1061              :     CHIP_ERROR err;
    1062        14390 :     while ((err = tempReader.Next()) == CHIP_NO_ERROR)
    1063              :     {
    1064         5535 :         ++count;
    1065              :     };
    1066         3320 :     if (err == CHIP_END_OF_TLV)
    1067              :     {
    1068         1660 :         *size = count;
    1069         1660 :         return CHIP_NO_ERROR;
    1070              :     }
    1071            0 :     return err;
    1072              : }
    1073              : 
    1074           10 : CHIP_ERROR ContiguousBufferTLVReader::OpenContainer(ContiguousBufferTLVReader & containerReader)
    1075              : {
    1076              :     // We are going to initialize containerReader by calling our superclass
    1077              :     // OpenContainer method.  The superclass only knows how to initialize
    1078              :     // members the superclass knows about, so we assert that we don't have any
    1079              :     // extra members that need initializing.  If such members ever get added,
    1080              :     // they would need to be initialized in this method.
    1081              :     static_assert(sizeof(ContiguousBufferTLVReader) == sizeof(TLVReader), "We have state the superclass is not initializing?");
    1082           10 :     return TLVReader::OpenContainer(containerReader);
    1083              : }
    1084              : 
    1085           11 : CHIP_ERROR ContiguousBufferTLVReader::GetStringView(Span<const char> & data)
    1086              : {
    1087           11 :     return Get(data);
    1088              : }
    1089              : 
    1090          670 : CHIP_ERROR ContiguousBufferTLVReader::GetByteView(ByteSpan & data)
    1091              : {
    1092          670 :     if (!TLVTypeIsByteString(ElementType()))
    1093              :     {
    1094            2 :         return CHIP_ERROR_WRONG_TLV_TYPE;
    1095              :     }
    1096              : 
    1097          668 :     return Get(data);
    1098              : }
    1099              : 
    1100              : } // namespace TLV
    1101              : } // namespace chip
        

Generated by: LCOV version 2.0-1