Skip to content

Commit

Permalink
Use AsData and AsString more uniformly in Darwin code. (#26888)
Browse files Browse the repository at this point in the history
* Use AsData and AsString more uniformly in Darwin code.

Also adds error-checking for when AsString fails due to the string not actually
being valid UTF-8.

* Address review comment.
  • Loading branch information
bzbarsky-apple authored May 27, 2023
1 parent aa947c1 commit 5a6b771
Show file tree
Hide file tree
Showing 13 changed files with 1,058 additions and 521 deletions.
25 changes: 14 additions & 11 deletions src/darwin/Framework/CHIP/MTRBaseDevice.mm
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
#import "MTRFramework.h"
#import "MTRLogging_Internal.h"
#import "MTRSetupPayload_Internal.h"
#import "NSDataSpanConversion.h"
#import "NSStringSpanConversion.h"

#include "app/ConcreteAttributePath.h"
#include "app/ConcreteCommandPath.h"
Expand Down Expand Up @@ -522,26 +524,27 @@ id _Nullable MTRDecodeDataValueDictionaryFromCHIPTLV(chip::TLV::TLVReader * data
dictionaryWithObjectsAndKeys:MTRDoubleValueType, MTRTypeKey, [NSNumber numberWithDouble:val], MTRValueKey, nil];
}
case chip::TLV::kTLVType_UTF8String: {
uint32_t len = data->GetLength();
const uint8_t * ptr;
CHIP_ERROR err = data->GetDataPtr(ptr);
CharSpan stringValue;
CHIP_ERROR err = data->Get(stringValue);
if (err != CHIP_NO_ERROR) {
MTR_LOG_ERROR("Error(%s): TLV UTF8String decoding failed", chip::ErrorStr(err));
return nil;
}
return [NSDictionary dictionaryWithObjectsAndKeys:MTRUTF8StringValueType, MTRTypeKey,
[[NSString alloc] initWithBytes:ptr length:len encoding:NSUTF8StringEncoding], MTRValueKey, nil];
NSString * stringObj = AsString(stringValue);
if (stringObj == nil) {
MTR_LOG_ERROR("Error(%s): TLV UTF8String value is not actually UTF-8", err.AsString());
return nil;
}
return @ { MTRTypeKey : MTRUTF8StringValueType, MTRValueKey : stringObj };
}
case chip::TLV::kTLVType_ByteString: {
uint32_t len = data->GetLength();
const uint8_t * ptr;
CHIP_ERROR err = data->GetDataPtr(ptr);
ByteSpan bytesValue;
CHIP_ERROR err = data->Get(bytesValue);
if (err != CHIP_NO_ERROR) {
MTR_LOG_ERROR("Error(%s): TLV ByteString decoding failed", chip::ErrorStr(err));
return nil;
}
return [NSDictionary dictionaryWithObjectsAndKeys:MTROctetStringValueType, MTRTypeKey,
[NSData dataWithBytes:ptr length:len], MTRValueKey, nil];
return @ { MTRTypeKey : MTROctetStringValueType, MTRValueKey : AsData(bytesValue) };
}
case chip::TLV::kTLVType_Null: {
return [NSDictionary dictionaryWithObjectsAndKeys:MTRNullValueType, MTRTypeKey, nil];
Expand Down Expand Up @@ -653,7 +656,7 @@ static CHIP_ERROR MTREncodeTLVFromDataValueDictionary(id object, chip::TLV::TLVW
MTR_LOG_ERROR("Error: Object to encode has corrupt UTF8 string type: %@", [value class]);
return CHIP_ERROR_INVALID_ARGUMENT;
}
return writer.PutString(tag, [value cStringUsingEncoding:NSUTF8StringEncoding]);
return writer.PutString(tag, [value UTF8String]);
}
if ([typeName isEqualToString:MTROctetStringValueType]) {
if (![value isKindOfClass:[NSData class]]) {
Expand Down
2 changes: 1 addition & 1 deletion src/darwin/Framework/CHIP/MTRFabricInfo.mm
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ - (instancetype)initWithFabricTable:(const FabricTable &)fabricTable fabricInfo:
return nil;
}

_rootPublicKey = [NSData dataWithBytes:publicKey.ConstBytes() length:publicKey.Length()];
_rootPublicKey = AsData(ByteSpan(publicKey.ConstBytes(), publicKey.Length()));

_vendorID = @(fabricInfo.GetVendorId());
_fabricID = @(fabricInfo.GetFabricId());
Expand Down
55 changes: 29 additions & 26 deletions src/darwin/Framework/CHIP/MTROTAProviderDelegateBridge.mm
Original file line number Diff line number Diff line change
Expand Up @@ -232,8 +232,13 @@ CHIP_ERROR OnTransferSessionBegin(TransferSession::OutputEvent & event)
uint16_t fdl = 0;
auto fd = mTransfer.GetFileDesignator(fdl);
VerifyOrReturnError(fdl <= bdx::kMaxFileDesignatorLen, CHIP_ERROR_INVALID_ARGUMENT);
CharSpan fileDesignatorSpan(Uint8::to_const_char(fd), fdl);

auto fileDesignator = AsString(fileDesignatorSpan);
if (fileDesignator == nil) {
return CHIP_ERROR_INCORRECT_STATE;
}

auto fileDesignator = [[NSString alloc] initWithBytes:fd length:fdl encoding:NSUTF8StringEncoding];
auto offset = @(mTransfer.GetStartOffset());

auto * controller = [[MTRDeviceControllerFactory sharedInstance] runningControllerForFabricIndex:mFabricIndex.Value()];
Expand Down Expand Up @@ -565,8 +570,8 @@ bool GetPeerNodeInfo(CommandHandler * commandHandler, const ConcreteCommandPath
if (error != nil) {
auto * desc = [error description];
auto err = [MTRError errorToCHIPErrorCode:error];
ChipLogError(Controller, "%s: application returned error: '%s', sending error: '%s'", prefix,
[desc cStringUsingEncoding:NSUTF8StringEncoding], chip::ErrorStr(err));
ChipLogError(
Controller, "%s: application returned error: '%s', sending error: '%s'", prefix, desc.UTF8String, err.AsString());

handler->AddStatus(cachedCommandPath, StatusIB(err).mStatus);
handle.Release();
Expand Down Expand Up @@ -635,8 +640,7 @@ bool GetPeerNodeInfo(CommandHandler * commandHandler, const ConcreteCommandPath
CommandHandler * handler = EnsureValidState(handle, cachedCommandPath, "QueryImage", data, error);
VerifyOrReturn(handler != nullptr);

ChipLogDetail(Controller, "QueryImage: application responded with: %s",
[[data description] cStringUsingEncoding:NSUTF8StringEncoding]);
ChipLogDetail(Controller, "QueryImage: application responded with: %s", [[data description] UTF8String]);

auto hasUpdate = [data.status isEqual:@(MTROtaSoftwareUpdateProviderOTAQueryStatusUpdateAvailable)];
auto isBDXProtocolSupported = [commandParams.protocolsSupported
Expand Down Expand Up @@ -753,27 +757,26 @@ bool GetPeerNodeInfo(CommandHandler * commandHandler, const ConcreteCommandPath
__block CommandHandler::Handle handle(commandObj);
__block ConcreteCommandPath cachedCommandPath(commandPath.mEndpointId, commandPath.mClusterId, commandPath.mCommandId);

auto completionHandler
= ^(MTROTASoftwareUpdateProviderClusterApplyUpdateResponseParams * _Nullable data, NSError * _Nullable error) {
[controller
asyncDispatchToMatterQueue:^() {
assertChipStackLockedByCurrentThread();

CommandHandler * handler = EnsureValidState(handle, cachedCommandPath, "ApplyUpdateRequest", data, error);
VerifyOrReturn(handler != nullptr);

ChipLogDetail(Controller, "ApplyUpdateRequest: application responded with: %s",
[[data description] cStringUsingEncoding:NSUTF8StringEncoding]);

Commands::ApplyUpdateResponse::Type response;
ConvertFromApplyUpdateRequestResponseParms(data, response);
handler->AddResponse(cachedCommandPath, response);
handle.Release();
}
errorHandler:^(NSError *) {
// Not much we can do here
}];
};
auto completionHandler = ^(
MTROTASoftwareUpdateProviderClusterApplyUpdateResponseParams * _Nullable data, NSError * _Nullable error) {
[controller
asyncDispatchToMatterQueue:^() {
assertChipStackLockedByCurrentThread();

CommandHandler * handler = EnsureValidState(handle, cachedCommandPath, "ApplyUpdateRequest", data, error);
VerifyOrReturn(handler != nullptr);

ChipLogDetail(Controller, "ApplyUpdateRequest: application responded with: %s", [[data description] UTF8String]);

Commands::ApplyUpdateResponse::Type response;
ConvertFromApplyUpdateRequestResponseParms(data, response);
handler->AddResponse(cachedCommandPath, response);
handle.Release();
}
errorHandler:^(NSError *) {
// Not much we can do here
}];
};

auto * commandParams = [[MTROTASoftwareUpdateProviderClusterApplyUpdateRequestParams alloc] init];
ConvertToApplyUpdateRequestParams(commandData, commandParams);
Expand Down
11 changes: 6 additions & 5 deletions src/darwin/Framework/CHIP/MTRThreadOperationalDataset.mm
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
*/

#import "MTRThreadOperationalDataset.h"
#import "NSDataSpanConversion.h"

#include "MTRLogging_Internal.h"
#include <lib/support/Span.h>
Expand Down Expand Up @@ -62,7 +63,7 @@ - (instancetype _Nullable)initWithNetworkName:(NSString *)networkName
- (BOOL)_populateCppOperationalDataset
{
_cppThreadOperationalDataset.Clear();
_cppThreadOperationalDataset.SetNetworkName([self.networkName cStringUsingEncoding:NSUTF8StringEncoding]);
_cppThreadOperationalDataset.SetNetworkName(self.networkName.UTF8String);

if (![self _checkDataLength:self.extendedPANID expectedLength:MTRSizeThreadExtendedPANID]) {
MTR_LOG_ERROR("Invalid ExtendedPANID");
Expand Down Expand Up @@ -137,17 +138,17 @@ - (instancetype _Nullable)initWithData:(NSData *)data
panID = CFSwapInt16BigToHost(panID);

return [self initWithNetworkName:[NSString stringWithUTF8String:networkName]
extendedPANID:[NSData dataWithBytes:extendedPANID length:MTRSizeThreadExtendedPANID]
masterKey:[NSData dataWithBytes:masterKey length:MTRSizeThreadMasterKey]
PSKc:[NSData dataWithBytes:pskc length:MTRSizeThreadPSKc]
extendedPANID:AsData(chip::ByteSpan(extendedPANID))
masterKey:AsData(chip::ByteSpan(masterKey))
PSKc:AsData(chip::ByteSpan(pskc))
channelNumber:@(channel)
panID:[NSData dataWithBytes:&panID length:sizeof(uint16_t)]];
}

- (NSData *)data
{
chip::ByteSpan span = _cppThreadOperationalDataset.AsByteSpan();
return [NSData dataWithBytes:span.data() length:span.size()];
return AsData(span);
}

@end
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
#import "MTRAttributeTLVValueDecoder_Internal.h"

#import "MTRStructsObjc.h"
#import "NSStringSpanConversion.h"
#import "NSDataSpanConversion.h"

#include <app/data-model/Decode.h>
#include <app/data-model/DecodableList.h>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
#import "MTRStructsObjc.h"
#import "MTRCommandPayloadsObjc.h"
#import "MTRCommandPayloads_Internal.h"
#import "NSStringSpanConversion.h"
#import "NSDataSpanConversion.h"

#include <lib/support/TypeTraits.h>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
#import "MTRBaseDevice_Internal.h"
#import "MTRError_Internal.h"
#import "MTRLogging_Internal.h"
#import "NSStringSpanConversion.h"
#import "NSDataSpanConversion.h"

#include <lib/core/TLV.h>
#include <app/data-model/Decode.h>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
#import "MTREventTLVValueDecoder_Internal.h"

#import "MTRStructsObjc.h"
#import "NSStringSpanConversion.h"
#import "NSDataSpanConversion.h"

#include <app/data-model/Decode.h>
#include <app/data-model/DecodableList.h>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,14 @@
{{#if_is_strongly_typed_bitmap type}}
{{target}} = [NSNumber numberWith{{asObjectiveCNumberType "" type false}}:{{source}}.Raw()];
{{else if (isOctetString type)}}
{{target}} = [NSData dataWithBytes:{{source}}.data() length:{{source}}.size()];
{{target}} = AsData({{source}});
{{else if (isCharString type)}}
{{target}} = [[NSString alloc] initWithBytes:{{source}}.data() length:{{source}}.size() encoding:NSUTF8StringEncoding];
{{target}} = AsString({{source}});
if ({{target}} == nil) {
{{! Invalid UTF-8. Just make up an error for now. }}
CHIP_ERROR err = CHIP_ERROR_INVALID_ARGUMENT;
{{errorCode}}
}
{{else}}
{{target}} = [NSNumber numberWith{{asObjectiveCNumberType "" type false}}:{{source}}];
{{/if_is_strongly_typed_bitmap}}
Expand Down
Loading

0 comments on commit 5a6b771

Please sign in to comment.