From 8153a8a83c45c6d07c509a6875ef1bb0f9ff6217 Mon Sep 17 00:00:00 2001 From: Ben Date: Mon, 28 Oct 2024 17:47:03 +0000 Subject: [PATCH] pw_bluetooth_sapphire: Use PW_CHECK directly for most asserts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Use PW_ASSERT only for the few asserts in constexpr functions. Change-Id: I55896095e9e50ef6eaf9748479e409d3761d4f75 Reviewed-on: https://pigweed-review.googlesource.com/c/pigweed/pigweed/+/244533 Docs-Not-Needed: Ben Lawson Reviewed-by: Wyatt Hepler Commit-Queue: Ben Lawson Lint: Lint 🤖 --- .../fuchsia/bt_hci_virtual/controller.cc | 2 +- pw_bluetooth_sapphire/fuchsia/bt_host/host.cc | 6 +- pw_bluetooth_sapphire/fuchsia/bt_host/main.cc | 2 +- .../host/controllers/fidl_controller.cc | 4 +- .../host/fidl/bredr_connection_server.cc | 14 +- .../fuchsia/host/fidl/gatt2_client_server.cc | 20 +-- .../host/fidl/gatt2_remote_service_server.cc | 6 +- .../fidl/gatt2_remote_service_server_test.cc | 2 +- .../fuchsia/host/fidl/gatt2_server_server.cc | 10 +- .../host/fidl/gatt_remote_service_server.cc | 9 +- .../fidl/gatt_remote_service_server_test.cc | 2 +- .../fuchsia/host/fidl/gatt_server_server.cc | 12 +- .../fuchsia/host/fidl/helpers.cc | 10 +- .../fuchsia/host/fidl/host_server.cc | 40 ++--- .../fuchsia/host/fidl/host_server_test.cc | 4 +- .../fidl/host_server_watch_peers_fuzztest.cc | 36 ++--- .../fuchsia/host/fidl/iso_stream_server.cc | 2 +- .../host/fidl/low_energy_central_server.cc | 30 ++-- .../fidl/low_energy_central_server_test.cc | 2 +- .../host/fidl/low_energy_connection_server.cc | 6 +- .../fidl/low_energy_connection_server_test.cc | 6 +- .../host/fidl/low_energy_peripheral_server.cc | 33 ++-- .../fuchsia/host/fidl/profile_server.cc | 30 ++-- .../fuchsia/host/fidl/fake_gatt_fixture.h | 8 +- .../fuchsia/host/fidl/fake_vendor_server.h | 4 +- .../fuchsia/host/fidl/server_base.h | 6 +- .../host/socket/socket_channel_relay.h | 141 +++++++++--------- .../fuchsia/host/socket/socket_factory.h | 25 ++-- .../host/socket/socket_channel_relay_test.cc | 2 +- pw_bluetooth_sapphire/host/att/attribute.cc | 20 +-- pw_bluetooth_sapphire/host/att/bearer.cc | 73 +++++---- pw_bluetooth_sapphire/host/att/database.cc | 26 ++-- .../host/att/database_test.cc | 2 +- pw_bluetooth_sapphire/host/att/error.cc | 2 +- .../host/common/advertising_data.cc | 46 +++--- .../host/common/byte_buffer.cc | 88 +++++------ .../host/common/device_address.cc | 4 +- .../host/common/device_class.cc | 8 +- .../host/common/error_test.cc | 4 +- pw_bluetooth_sapphire/host/common/random.cc | 2 +- .../host/common/retire_log.cc | 8 +- .../host/common/supplement_data.cc | 10 +- pw_bluetooth_sapphire/host/common/uuid.cc | 8 +- .../host/common/uuid_string_util.cc | 4 +- .../host/common/weak_self_test.cc | 4 +- pw_bluetooth_sapphire/host/gap/adapter.cc | 40 ++--- .../host/gap/bredr_connection.cc | 10 +- .../host/gap/bredr_connection_manager.cc | 39 +++-- .../host/gap/bredr_discovery_manager.cc | 35 +++-- .../host/gap/bredr_interrogator.cc | 6 +- .../host/gap/discovery_filter.cc | 2 +- .../host/gap/generic_access_client.cc | 4 +- .../host/gap/legacy_pairing_state.cc | 62 ++++---- .../host/gap/low_energy_address_manager.cc | 10 +- .../gap/low_energy_advertising_manager.cc | 8 +- .../low_energy_advertising_manager_test.cc | 2 +- .../host/gap/low_energy_connection.cc | 73 +++++---- .../host/gap/low_energy_connection_handle.cc | 12 +- .../host/gap/low_energy_connection_manager.cc | 40 ++--- .../gap/low_energy_connection_manager_test.cc | 6 +- .../host/gap/low_energy_connector.cc | 78 +++++----- .../host/gap/low_energy_discovery_manager.cc | 30 ++-- .../gap/low_energy_discovery_manager_test.cc | 18 +-- .../host/gap/low_energy_interrogator.cc | 14 +- .../host/gap/pairing_state_manager.cc | 8 +- pw_bluetooth_sapphire/host/gap/peer.cc | 61 ++++---- pw_bluetooth_sapphire/host/gap/peer_cache.cc | 71 +++++---- pw_bluetooth_sapphire/host/gap/peer_test.cc | 16 +- .../host/gap/secure_simple_pairing_state.cc | 86 +++++------ pw_bluetooth_sapphire/host/gatt/client.cc | 56 +++---- pw_bluetooth_sapphire/host/gatt/connection.cc | 4 +- pw_bluetooth_sapphire/host/gatt/fake_layer.cc | 4 +- pw_bluetooth_sapphire/host/gatt/gatt.cc | 4 +- .../host/gatt/generic_attribute_service.cc | 10 +- .../gatt/generic_attribute_service_test.cc | 4 +- .../host/gatt/local_service_manager.cc | 54 +++---- .../host/gatt/local_service_manager_test.cc | 10 +- .../host/gatt/remote_characteristic.cc | 26 ++-- .../host/gatt/remote_service.cc | 52 +++---- .../host/gatt/remote_service_manager.cc | 32 ++-- .../host/gatt/remote_service_manager_test.cc | 8 +- pw_bluetooth_sapphire/host/gatt/server.cc | 74 ++++----- .../host/gatt/server_test.cc | 2 +- .../host/hci/acl_connection.cc | 2 +- .../host/hci/advertising_handle_map.cc | 6 +- .../android_extended_low_energy_advertiser.cc | 18 +-- .../host/hci/bredr_connection.cc | 12 +- .../host/hci/bredr_connection_request.cc | 6 +- pw_bluetooth_sapphire/host/hci/connection.cc | 8 +- .../hci/extended_low_energy_advertiser.cc | 18 +-- .../host/hci/extended_low_energy_scanner.cc | 16 +- .../host/hci/fake_bredr_connection.cc | 2 +- .../host/hci/fake_local_address_delegate.cc | 2 +- .../host/hci/fake_low_energy_connection.cc | 2 +- .../host/hci/legacy_low_energy_advertiser.cc | 2 +- .../host/hci/legacy_low_energy_scanner.cc | 20 +-- .../host/hci/low_energy_advertiser.cc | 2 +- .../host/hci/low_energy_connection.cc | 6 +- .../host/hci/low_energy_connector.cc | 16 +- .../host/hci/low_energy_scanner.cc | 20 +-- .../host/hci/sequential_command_runner.cc | 14 +- pw_bluetooth_sapphire/host/iso/iso_stream.cc | 12 +- .../host/iso/iso_stream_manager.cc | 15 +- .../host/l2cap/a2dp_offload_manager.cc | 4 +- .../host/l2cap/basic_mode_rx_engine.cc | 2 +- .../host/l2cap/basic_mode_tx_engine.cc | 4 +- .../host/l2cap/bredr_command_handler_test.cc | 2 +- .../host/l2cap/bredr_dynamic_channel.cc | 26 ++-- .../host/l2cap/bredr_signaling_channel.cc | 2 +- pw_bluetooth_sapphire/host/l2cap/channel.cc | 30 ++-- .../host/l2cap/channel_manager.cc | 14 +- .../host/l2cap/channel_manager_test.cc | 14 +- .../host/l2cap/command_handler.cc | 2 +- .../host/l2cap/command_handler_test.cc | 2 +- .../credit_based_flow_control_tx_engine.cc | 18 +-- .../host/l2cap/dynamic_channel.cc | 2 +- .../host/l2cap/dynamic_channel_registry.cc | 16 +- .../enhanced_retransmission_mode_tx_engine.cc | 72 ++++----- .../host/l2cap/fake_channel.cc | 12 +- .../host/l2cap/fake_l2cap.cc | 36 ++--- .../host/l2cap/fragmenter.cc | 28 ++-- .../host/l2cap/fragmenter_test.cc | 2 +- .../host/l2cap/l2cap_fuzztest.cc | 2 +- .../host/l2cap/le_dynamic_channel.cc | 10 +- .../host/l2cap/le_signaling_channel.cc | 2 +- .../host/l2cap/logical_link.cc | 66 ++++---- .../l2cap/low_energy_command_handler_test.cc | 2 +- pw_bluetooth_sapphire/host/l2cap/pdu.cc | 22 +-- pw_bluetooth_sapphire/host/l2cap/pdu_test.cc | 2 +- .../host/l2cap/recombiner.cc | 14 +- .../host/l2cap/recombiner_test.cc | 2 +- .../host/l2cap/signaling_channel.cc | 42 +++--- .../host/l2cap/signaling_channel_test.cc | 2 +- .../host/l2cap/test_packets.cc | 8 +- pw_bluetooth_sapphire/host/l2cap/types.cc | 2 +- .../host/sco/sco_connection.cc | 16 +- .../host/sco/sco_connection_manager.cc | 28 ++-- pw_bluetooth_sapphire/host/sdp/client.cc | 13 +- .../host/sdp/data_element.cc | 12 +- pw_bluetooth_sapphire/host/sdp/pdu.cc | 34 ++--- pw_bluetooth_sapphire/host/sdp/server.cc | 16 +- .../host/sdp/service_discoverer.cc | 9 +- .../host/sdp/service_record.cc | 6 +- pw_bluetooth_sapphire/host/sm/ecdh_key.cc | 32 ++-- pw_bluetooth_sapphire/host/sm/error.cc | 2 +- pw_bluetooth_sapphire/host/sm/packet.cc | 2 +- .../host/sm/pairing_channel.cc | 12 +- .../host/sm/pairing_phase.cc | 6 +- pw_bluetooth_sapphire/host/sm/phase_1.cc | 24 +-- .../host/sm/phase_2_legacy.cc | 46 +++--- .../host/sm/phase_2_legacy_test.cc | 6 +- .../host/sm/phase_2_secure_connections.cc | 50 +++---- .../sm/phase_2_secure_connections_test.cc | 37 +++-- pw_bluetooth_sapphire/host/sm/phase_3.cc | 29 ++-- pw_bluetooth_sapphire/host/sm/phase_3_test.cc | 6 +- ...c_stage_1_just_works_numeric_comparison.cc | 16 +- .../host/sm/sc_stage_1_passkey.cc | 32 ++-- .../host/sm/security_manager.cc | 64 ++++---- .../host/sm/security_manager_test.cc | 22 +-- .../host/sm/security_request_phase.cc | 2 +- .../host/sm/test_security_manager.cc | 2 +- pw_bluetooth_sapphire/host/sm/types.cc | 5 +- pw_bluetooth_sapphire/host/sm/util.cc | 22 +-- .../host/testing/fake_controller.cc | 46 +++--- .../host/testing/fake_gatt_server.cc | 6 +- .../host/testing/fake_l2cap.cc | 6 +- .../host/testing/fake_peer.cc | 36 +++-- .../host/testing/fake_sdp_server.cc | 2 +- .../host/testing/fake_signaling_server.cc | 10 +- .../host/testing/inspect_util.cc | 2 +- .../host/testing/mock_controller.cc | 8 +- .../host/testing/run_all_unittests.cc | 2 +- .../host/transport/acl_data_channel.cc | 51 +++---- .../host/transport/acl_data_packet.cc | 14 +- .../host/transport/command_channel.cc | 32 ++-- .../host/transport/control_packets.cc | 8 +- .../host/transport/emboss_control_packets.cc | 9 +- .../host/transport/fake_sco_data_channel.cc | 4 +- .../host/transport/iso_data_channel.cc | 2 +- .../host/transport/mock_acl_data_channel.cc | 10 +- .../host/transport/sco_data_channel.cc | 24 +-- .../host/transport/sco_data_packet.cc | 2 +- .../host/transport/transport.cc | 14 +- .../internal/host/att/attribute.h | 9 +- .../internal/host/att/bearer.h | 2 +- .../internal/host/common/assert.h | 1 + .../host/common/bounded_inspect_list_node.h | 2 +- .../internal/host/common/byte_buffer.h | 35 +++-- .../internal/host/common/error.h | 8 +- .../internal/host/common/inspectable.h | 2 +- .../internal/host/common/packet_view.h | 20 +-- .../internal/host/common/pipeline_monitor.h | 18 +-- .../internal/host/common/random.h | 2 +- .../internal/host/common/retire_log.h | 6 +- .../internal/host/common/slab_buffer.h | 4 +- .../internal/host/common/smart_task.h | 2 +- .../internal/host/common/weak_self.h | 12 +- .../windowed_inspect_numeric_property.h | 4 +- .../internal/host/gap/bredr_connection.h | 4 +- .../host/gap/bredr_connection_request.h | 2 +- .../internal/host/gap/low_energy_connection.h | 8 +- .../internal/host/hci-spec/lmp_feature_set.h | 2 +- .../internal/host/hci/low_energy_advertiser.h | 2 +- .../host/l2cap/bredr_command_handler.h | 12 +- .../internal/host/l2cap/frame_headers.h | 8 +- .../internal/host/l2cap/pdu.h | 2 +- .../internal/host/l2cap/tx_engine.h | 2 +- .../internal/host/sdp/data_element.h | 10 +- .../internal/host/sdp/pdu.h | 6 +- .../internal/host/sm/pairing_channel.h | 4 +- .../internal/host/sm/pairing_phase.h | 2 +- .../internal/host/testing/fake_controller.h | 6 +- .../internal/host/transport/emboss_packet.h | 14 +- 213 files changed, 1770 insertions(+), 1797 deletions(-) diff --git a/pw_bluetooth_sapphire/fuchsia/bt_hci_virtual/controller.cc b/pw_bluetooth_sapphire/fuchsia/bt_hci_virtual/controller.cc index 903b0acb0c..26bf84df1d 100644 --- a/pw_bluetooth_sapphire/fuchsia/bt_hci_virtual/controller.cc +++ b/pw_bluetooth_sapphire/fuchsia/bt_hci_virtual/controller.cc @@ -94,7 +94,7 @@ void VirtualController::CreateLoopbackDevice( loopback_device_ = std::make_unique(); - BT_ASSERT(request->has_uart_channel()); + PW_CHECK(request->has_uart_channel()); zx_status_t status = loopback_device_->Initialize( std::move(request->uart_channel()), std::string_view(name), diff --git a/pw_bluetooth_sapphire/fuchsia/bt_host/host.cc b/pw_bluetooth_sapphire/fuchsia/bt_host/host.cc index e36727598f..a8c064a5d0 100644 --- a/pw_bluetooth_sapphire/fuchsia/bt_host/host.cc +++ b/pw_bluetooth_sapphire/fuchsia/bt_host/host.cc @@ -142,15 +142,15 @@ void BtHostComponent::BindToHostInterface( return; } - BT_DEBUG_ASSERT(gap_); - BT_DEBUG_ASSERT(gatt_); + PW_DCHECK(gap_); + PW_DCHECK(gatt_); zx::channel channel = host_client.TakeChannel(); host_server_ = std::make_unique( std::move(channel), gap_->AsWeakPtr(), gatt_->GetWeakPtr()); host_server_->set_error_handler([this](zx_status_t status) { - BT_DEBUG_ASSERT(host_server_); + PW_DCHECK(host_server_); bt_log(WARN, "bt-host", "Host interface disconnected"); host_server_ = nullptr; }); diff --git a/pw_bluetooth_sapphire/fuchsia/bt_host/main.cc b/pw_bluetooth_sapphire/fuchsia/bt_host/main.cc index 3dc56932b0..90c110dfde 100644 --- a/pw_bluetooth_sapphire/fuchsia/bt_host/main.cc +++ b/pw_bluetooth_sapphire/fuchsia/bt_host/main.cc @@ -111,7 +111,7 @@ int main() { LifecycleHandler lifecycle_handler(&loop, host->GetWeakPtr()); auto init_cb = [&host, &lifecycle_handler, &loop](bool success) { - BT_DEBUG_ASSERT(host); + PW_DCHECK(host); if (!success) { bt_log( ERROR, "bt-host", "Failed to initialize bt-host; shutting down..."); diff --git a/pw_bluetooth_sapphire/fuchsia/host/controllers/fidl_controller.cc b/pw_bluetooth_sapphire/fuchsia/host/controllers/fidl_controller.cc index 12c926da0e..6e14a6c2d2 100644 --- a/pw_bluetooth_sapphire/fuchsia/host/controllers/fidl_controller.cc +++ b/pw_bluetooth_sapphire/fuchsia/host/controllers/fidl_controller.cc @@ -159,7 +159,7 @@ FidlController::FidlController(fidl::ClientEnd vendor_client_end, [this](zx_status_t status) { OnScoUnbind(status); }, [this](fhbt::ScoPacket packet) { OnReceiveSco(std::move(packet)); }), dispatcher_(dispatcher) { - BT_ASSERT(vendor_client_end.is_valid()); + PW_CHECK(vendor_client_end.is_valid()); vendor_client_end_ = std::move(vendor_client_end); } @@ -373,7 +373,7 @@ void FidlController::GetFeatures( void FidlController::EncodeVendorCommand( pw::bluetooth::VendorCommandParameters parameters, pw::Callback>)> callback) { - BT_ASSERT(vendor_); + PW_CHECK(vendor_); if (!std::holds_alternative( parameters)) { diff --git a/pw_bluetooth_sapphire/fuchsia/host/fidl/bredr_connection_server.cc b/pw_bluetooth_sapphire/fuchsia/host/fidl/bredr_connection_server.cc index 6831b37866..40469d2136 100644 --- a/pw_bluetooth_sapphire/fuchsia/host/fidl/bredr_connection_server.cc +++ b/pw_bluetooth_sapphire/fuchsia/host/fidl/bredr_connection_server.cc @@ -84,7 +84,7 @@ void BrEdrConnectionServer::Receive(ReceiveCallback callback) { void BrEdrConnectionServer::WatchChannelParameters( WatchChannelParametersCallback callback) { - BT_ASSERT_MSG( + PW_CHECK( !pending_watch_channel_parameters_.has_value(), "WatchChannelParameters called while there was already a pending call."); pending_watch_channel_parameters_ = std::move(callback); @@ -99,7 +99,7 @@ void BrEdrConnectionServer::handle_unknown_method(uint64_t ordinal, } bool BrEdrConnectionServer::Activate() { - BT_ASSERT(state_ == State::kActivating); + PW_CHECK(state_ == State::kActivating); WeakPtr self = weak_self_.GetWeakPtr(); bt::l2cap::ChannelId channel_id = channel_->id(); @@ -136,7 +136,7 @@ bool BrEdrConnectionServer::Activate() { } void BrEdrConnectionServer::Deactivate() { - BT_ASSERT(state_ != State::kDeactivated); + PW_CHECK(state_ != State::kDeactivated); state_ = State::kDeactivating; if (!receive_queue_.empty()) { @@ -156,7 +156,7 @@ void BrEdrConnectionServer::Deactivate() { void BrEdrConnectionServer::OnChannelDataReceived(bt::ByteBufferPtr rx_data) { // Note: kActivating is deliberately permitted, as ChannelImpl::Activate() // will synchronously deliver any queued frames. - BT_ASSERT(state_ != State::kDeactivated); + PW_CHECK(state_ != State::kDeactivated); if (state_ == State::kDeactivating) { bt_log(DEBUG, "fidl", @@ -166,14 +166,14 @@ void BrEdrConnectionServer::OnChannelDataReceived(bt::ByteBufferPtr rx_data) { return; } - BT_ASSERT(rx_data); + PW_CHECK(rx_data); if (rx_data->size() == 0) { bt_log( DEBUG, "fidl", "Ignoring empty rx_data for channel %u", channel_->id()); return; } - BT_ASSERT(receive_queue_.size() <= receive_queue_max_frames_); + PW_CHECK(receive_queue_.size() <= receive_queue_max_frames_); // On a full queue, we drop the oldest element, on the theory that newer data // is more useful. This should be true, e.g., for real-time applications such // as voice calls. In the future, we may want to make the drop-head vs. @@ -196,7 +196,7 @@ void BrEdrConnectionServer::OnChannelClosed() { channel_->id()); return; } - BT_ASSERT(state_ == State::kActivated); + PW_CHECK(state_ == State::kActivated); DeactivateAndRequestDestruction(); } diff --git a/pw_bluetooth_sapphire/fuchsia/host/fidl/gatt2_client_server.cc b/pw_bluetooth_sapphire/fuchsia/host/fidl/gatt2_client_server.cc index fe80b7146b..d8edb3b73c 100644 --- a/pw_bluetooth_sapphire/fuchsia/host/fidl/gatt2_client_server.cc +++ b/pw_bluetooth_sapphire/fuchsia/host/fidl/gatt2_client_server.cc @@ -70,7 +70,7 @@ Gatt2ClientServer::Gatt2ClientServer( } Gatt2ClientServer::~Gatt2ClientServer() { - BT_ASSERT(gatt()->UnregisterRemoteServiceWatcher(service_watcher_id_)); + PW_CHECK(gatt()->UnregisterRemoteServiceWatcher(service_watcher_id_)); } void Gatt2ClientServer::OnWatchServicesResult( @@ -233,7 +233,7 @@ void Gatt2ClientServer::WatchServices(std::vector fidl_uuids, "WatchServices: ListServices complete (peer: %s)", bt_str(self->peer_id_)); - BT_ASSERT(self->watch_services_request_); + PW_CHECK(self->watch_services_request_); self->list_services_complete_ = true; self->OnWatchServicesResult( /*removed=*/{}, /*added=*/services, /*modified=*/{}); @@ -280,7 +280,7 @@ void Gatt2ClientServer::ConnectToService( request.Close(ZX_ERR_NOT_FOUND); return; } - BT_ASSERT(service_handle == service->handle()); + PW_CHECK(service_handle == service->handle()); // This removed handler may be called long after the service is removed from // the service map or this server is destroyed, since removed handlers are not @@ -316,12 +316,12 @@ void Gatt2ClientServer::ConnectToService( // service is already shut down, but that should not be possible in this // synchronous callback (the service would not have been returned in the first // place). - BT_ASSERT_MSG(service->AddRemovedHandler(std::move(removed_handler)), - "adding service removed handler failed (service may be shut " - "down) (peer: %s, " - "handle: %#.4x)", - bt_str(peer_id_), - service_handle); + PW_CHECK(service->AddRemovedHandler(std::move(removed_handler)), + "adding service removed handler failed (service may be shut " + "down) (peer: %s, " + "handle: %#.4x)", + bt_str(peer_id_), + service_handle); std::unique_ptr remote_service_server = std::make_unique( @@ -340,7 +340,7 @@ void Gatt2ClientServer::ConnectToService( }); // Error handler should not have been called yet. - BT_ASSERT(services_.count(service_handle) == 1); + PW_CHECK(services_.count(service_handle) == 1); services_[service_handle] = std::move(remote_service_server); } diff --git a/pw_bluetooth_sapphire/fuchsia/host/fidl/gatt2_remote_service_server.cc b/pw_bluetooth_sapphire/fuchsia/host/fidl/gatt2_remote_service_server.cc index afaa0b9f76..51b070e464 100644 --- a/pw_bluetooth_sapphire/fuchsia/host/fidl/gatt2_remote_service_server.cc +++ b/pw_bluetooth_sapphire/fuchsia/host/fidl/gatt2_remote_service_server.cc @@ -241,7 +241,7 @@ void Gatt2RemoteServiceServer::ReadByType(::fuchsia::bluetooth::Uuid uuid, } measure_fbg::Size result_size = measure_fbg::Measure(fidl_result); - BT_ASSERT(result_size.num_handles == 0); + PW_CHECK(result_size.num_handles == 0); bytes_used += result_size.num_bytes; if (bytes_used > kMaxBytes) { @@ -441,7 +441,7 @@ void Gatt2RemoteServiceServer::RegisterCharacteristicNotifier( // `DisableNotifications` completion callback in // `OnCharacteristicNotifierError`, so no notifications should be received // after removing a notifier. - BT_ASSERT_MSG( + PW_CHECK( notifier_iter != self->characteristic_notifiers_.end(), "characteristic notification value received after notifier unregistered" "(peer: %s, characteristic: 0x%lX) ", @@ -509,7 +509,7 @@ void Gatt2RemoteServiceServer::RegisterCharacteristicNotifier( .notifier = notifier_handle.Bind()}; auto [notifier_iter, emplaced] = self->characteristic_notifiers_.emplace( notifier_id, std::move(notifier)); - BT_ASSERT(emplaced); + PW_CHECK(emplaced); // When the client closes the protocol, unregister the notifier. notifier_iter->second.notifier.set_error_handler( diff --git a/pw_bluetooth_sapphire/fuchsia/host/fidl/gatt2_remote_service_server_test.cc b/pw_bluetooth_sapphire/fuchsia/host/fidl/gatt2_remote_service_server_test.cc index 11894bec09..e91c104045 100644 --- a/pw_bluetooth_sapphire/fuchsia/host/fidl/gatt2_remote_service_server_test.cc +++ b/pw_bluetooth_sapphire/fuchsia/host/fidl/gatt2_remote_service_server_test.cc @@ -73,7 +73,7 @@ class Gatt2RemoteServiceServerTest : public bt::fidl::testing::FakeGattFixture { protected: const bt::gatt::testing::FakeClient::WeakPtr& fake_client() const { - BT_ASSERT(fake_client_.is_alive()); + PW_CHECK(fake_client_.is_alive()); return fake_client_; } diff --git a/pw_bluetooth_sapphire/fuchsia/host/fidl/gatt2_server_server.cc b/pw_bluetooth_sapphire/fuchsia/host/fidl/gatt2_server_server.cc index 9318a4c04a..912934a927 100644 --- a/pw_bluetooth_sapphire/fuchsia/host/fidl/gatt2_server_server.cc +++ b/pw_bluetooth_sapphire/fuchsia/host/fidl/gatt2_server_server.cc @@ -186,7 +186,7 @@ void Gatt2ServerServer::OnReadRequest(bt::PeerId peer_id, btg::ReadResponder responder) { auto svc_iter = services_.find(InternalServiceId(service_id)); // GATT must only send read requests for registered services. - BT_ASSERT(svc_iter != services_.end()); + PW_CHECK(svc_iter != services_.end()); auto cb = [responder = std::move(responder)]( LocalService_ReadValue_Result res) mutable { @@ -209,7 +209,7 @@ void Gatt2ServerServer::OnWriteRequest(bt::PeerId peer_id, btg::WriteResponder responder) { auto svc_iter = services_.find(InternalServiceId(service_id)); // GATT must only send write requests for registered services. - BT_ASSERT(svc_iter != services_.end()); + PW_CHECK(svc_iter != services_.end()); auto cb = [responder = std::move(responder)]( LocalService_WriteValue_Result result) mutable { @@ -240,7 +240,7 @@ void Gatt2ServerServer::OnClientCharacteristicConfiguration( bool indicate) { auto svc_iter = services_.find(InternalServiceId(service_id)); // GATT must only send CCC updates for registered services. - BT_ASSERT(svc_iter != services_.end()); + PW_CHECK(svc_iter != services_.end()); auto cb = []() { bt_log(TRACE, "fidl", "characteristic configuration acknowledged"); @@ -263,7 +263,7 @@ bool Gatt2ServerServer::ValidateValueChangedEvent( const char* update_type) { auto iter = services_.find(service_id); // It is impossible for clients to send events to a closed service. - BT_ASSERT(iter != services_.end()); + PW_CHECK(iter != services_.end()); // Subtract credit before validating parameters so that credits aren't // permanently lost from the client's perspective. SubtractCredit(iter->second); @@ -363,7 +363,7 @@ void Gatt2ServerServer::SubtractCredit(Service& svc) { // perspective because new credits are granted before the count reaches 0 // (excessive events will fill the FIDL channel and eventually crash the // client). - BT_ASSERT(svc.credits > 0); + PW_CHECK(svc.credits > 0); svc.credits--; if (svc.credits <= REFRESH_CREDITS_AT) { // Static cast OK because current_credits > 0 and we never add more than diff --git a/pw_bluetooth_sapphire/fuchsia/host/fidl/gatt_remote_service_server.cc b/pw_bluetooth_sapphire/fuchsia/host/fidl/gatt_remote_service_server.cc index 70dcae1997..f7fbf142ae 100644 --- a/pw_bluetooth_sapphire/fuchsia/host/fidl/gatt_remote_service_server.cc +++ b/pw_bluetooth_sapphire/fuchsia/host/fidl/gatt_remote_service_server.cc @@ -78,7 +78,7 @@ GattRemoteServiceServer::GattRemoteServiceServer( service_(std::move(service)), peer_id_(peer_id), weak_self_(this) { - BT_DEBUG_ASSERT(service_.is_alive()); + PW_DCHECK(service_.is_alive()); } GattRemoteServiceServer::~GattRemoteServiceServer() { @@ -397,10 +397,9 @@ void GattRemoteServiceServer::NotifyCharacteristic( } if (status.is_ok()) { - BT_DEBUG_ASSERT(handler_id != bt::gatt::kInvalidId); - BT_DEBUG_ASSERT(self->notify_handlers_.count(handle) == 1u); - BT_DEBUG_ASSERT(self->notify_handlers_[handle] == - bt::gatt::kInvalidId); + PW_DCHECK(handler_id != bt::gatt::kInvalidId); + PW_DCHECK(self->notify_handlers_.count(handle) == 1u); + PW_DCHECK(self->notify_handlers_[handle] == bt::gatt::kInvalidId); self->notify_handlers_[handle] = handler_id; } else { // Remove our handle holder. diff --git a/pw_bluetooth_sapphire/fuchsia/host/fidl/gatt_remote_service_server_test.cc b/pw_bluetooth_sapphire/fuchsia/host/fidl/gatt_remote_service_server_test.cc index 256bd5b9a0..14f1d2cdc6 100644 --- a/pw_bluetooth_sapphire/fuchsia/host/fidl/gatt_remote_service_server_test.cc +++ b/pw_bluetooth_sapphire/fuchsia/host/fidl/gatt_remote_service_server_test.cc @@ -66,7 +66,7 @@ class GattRemoteServiceServerTest : public bt::fidl::testing::FakeGattFixture { protected: const bt::gatt::testing::FakeClient::WeakPtr& fake_client() const { - BT_ASSERT(fake_client_.is_alive()); + PW_CHECK(fake_client_.is_alive()); return fake_client_; } diff --git a/pw_bluetooth_sapphire/fuchsia/host/fidl/gatt_server_server.cc b/pw_bluetooth_sapphire/fuchsia/host/fidl/gatt_server_server.cc index 84a5c2a4e8..63ce0da030 100644 --- a/pw_bluetooth_sapphire/fuchsia/host/fidl/gatt_server_server.cc +++ b/pw_bluetooth_sapphire/fuchsia/host/fidl/gatt_server_server.cc @@ -154,8 +154,8 @@ class GattServerServer::LocalServiceImpl owner_(owner), id_(id), delegate_(std::move(delegate)) { - BT_DEBUG_ASSERT(owner_); - BT_DEBUG_ASSERT(delegate_); + PW_DCHECK(owner_); + PW_DCHECK(delegate_); } // The destructor removes the GATT service @@ -336,7 +336,7 @@ void GattServerServer::PublishService( return; } - BT_DEBUG_ASSERT(self->services_.find(id) == self->services_.end()); + PW_DCHECK(self->services_.find(id) == self->services_.end()); // This will be called if either the delegate or the service connection // closes. @@ -388,7 +388,7 @@ void GattServerServer::OnReadRequest(bt::gatt::IdType service_id, }; auto* delegate = iter->second->delegate(); - BT_DEBUG_ASSERT(delegate); + PW_DCHECK(delegate); delegate->OnReadValue(id, offset, std::move(cb)); } @@ -407,7 +407,7 @@ void GattServerServer::OnWriteRequest(bt::gatt::IdType service_id, auto fidl_value = fidl::To>(value); auto* delegate = iter->second->delegate(); - BT_DEBUG_ASSERT(delegate); + PW_DCHECK(delegate); if (!responder) { delegate->OnWriteWithoutResponse(id, offset, std::move(fidl_value)); @@ -434,7 +434,7 @@ void GattServerServer::OnCharacteristicConfig(bt::gatt::IdType service_id, } auto* delegate = iter->second->delegate(); - BT_DEBUG_ASSERT(delegate); + PW_DCHECK(delegate); delegate->OnCharacteristicConfiguration( chrc_id, peer_id.ToString(), notify, indicate); } diff --git a/pw_bluetooth_sapphire/fuchsia/host/fidl/helpers.cc b/pw_bluetooth_sapphire/fuchsia/host/fidl/helpers.cc index 138cf9199c..f39afc6c98 100644 --- a/pw_bluetooth_sapphire/fuchsia/host/fidl/helpers.cc +++ b/pw_bluetooth_sapphire/fuchsia/host/fidl/helpers.cc @@ -1442,7 +1442,7 @@ bool IsScanFilterValid(const fble::ScanFilter& fidl_filter) { bool PopulateDiscoveryFilter(const fble::ScanFilter& fidl_filter, bt::gap::DiscoveryFilter* out_filter) { - BT_DEBUG_ASSERT(out_filter); + PW_DCHECK(out_filter); if (fidl_filter.service_uuids) { std::vector uuids; @@ -1742,7 +1742,7 @@ fuchsia::bluetooth::le::ScanData AdvertisingDataToFidlScanData( } fble::Peer PeerToFidlLe(const bt::gap::Peer& peer) { - BT_ASSERT(peer.le()); + PW_CHECK(peer.le()); fble::Peer output; output.set_id(fbt::PeerId{peer.identifier().value()}); @@ -1848,7 +1848,7 @@ ServiceDefinitionToServiceRecord( // ProtocolListId = uint8_t, and std::numeric_limits::max() == 255 // == the MAX_SEQUENCE_LENGTH vector limit from // fuchsia.bluetooth.bredr/ServiceDefinition.additional_protocol_descriptor_lists. - BT_ASSERT( + PW_CHECK( definition.additional_protocol_descriptor_lists()->size() <= std::numeric_limits::max()); bt::sdp::ServiceRecord::ProtocolListId protocol_list_id = 1; @@ -1969,7 +1969,7 @@ ServiceDefinitionToServiceRecord( // ProtocolListId = uint8_t, and std::numeric_limits::max() == 255 // == the MAX_SEQUENCE_LENGTH vector limit from // fuchsia.bluetooth.bredr/ServiceDefinition.additional_protocol_descriptor_lists. - BT_ASSERT( + PW_CHECK( definition.additional_protocol_descriptor_lists().size() <= std::numeric_limits::max()); bt::sdp::ServiceRecord::ProtocolListId protocol_list_id = 1; @@ -2654,7 +2654,7 @@ bt::StaticPacket CodecIdFromFidl( CodingFormatFromFidl(fidl_codec_id.assigned_format()); result_view.coding_format().Write(out_coding_format); } else { - BT_ASSERT(fidl_codec_id.is_vendor_format()); + PW_CHECK(fidl_codec_id.is_vendor_format()); result_view.coding_format().Write( pw::bluetooth::emboss::CodingFormat::VENDOR_SPECIFIC); result_view.company_id().Write(fidl_codec_id.vendor_format().company_id()); diff --git a/pw_bluetooth_sapphire/fuchsia/host/fidl/host_server.cc b/pw_bluetooth_sapphire/fuchsia/host/fidl/host_server.cc index 89235bb8dc..9557d3a7ce 100644 --- a/pw_bluetooth_sapphire/fuchsia/host/fidl/host_server.cc +++ b/pw_bluetooth_sapphire/fuchsia/host/fidl/host_server.cc @@ -69,7 +69,7 @@ HostServer::HostServer(zx::channel channel, io_capability_(IOCapability::kNoInputNoOutput), weak_self_(this), weak_pairing_(this) { - BT_ASSERT(gatt_.is_alive()); + PW_CHECK(gatt_.is_alive()); auto self = weak_self_.GetWeakPtr(); adapter->peer_cache()->set_peer_bonded_callback([self](const auto& peer) { @@ -155,7 +155,7 @@ void HostServer::SetPeerWatcher( void HostServer::SetLocalName(::std::string local_name, SetLocalNameCallback callback) { - BT_DEBUG_ASSERT(!local_name.empty()); + PW_DCHECK(!local_name.empty()); adapter()->SetLocalName(std::move(local_name), [self = weak_self_.GetWeakPtr(), callback = std::move(callback)](auto status) { @@ -220,7 +220,7 @@ void HostServer::StartLEDiscovery() { void HostServer::StartDiscovery( ::fuchsia::bluetooth::host::HostStartDiscoveryRequest request) { bt_log(DEBUG, "fidl", "%s", __FUNCTION__); - BT_DEBUG_ASSERT(adapter().is_alive()); + PW_DCHECK(adapter().is_alive()); if (!request.has_token()) { bt_log(WARN, "fidl", "missing Discovery token"); @@ -378,7 +378,7 @@ void HostServer::OnPeerBonded(const bt::gap::Peer& peer) { void HostServer::RegisterLowEnergyConnection( std::unique_ptr conn_ref, bool auto_connect) { - BT_DEBUG_ASSERT(conn_ref); + PW_DCHECK(conn_ref); bt::PeerId id = conn_ref->peer_identifier(); auto iter = le_connections_.find(id); @@ -443,7 +443,7 @@ void HostServer::SetDiscoverable(bool discoverable, bt_log(ERROR, "fidl", "%s: failed (result: %s)", func, bt_str(result)); fpromise::result fidl_result = ResultToFidl(result); if (result.is_ok()) { - BT_ASSERT(session == nullptr); + PW_CHECK(session == nullptr); fidl_result = fpromise::error(fsys::Error::FAILED); } self->requesting_discoverable_ = false; @@ -640,8 +640,8 @@ void HostServer::ConnectLowEnergy(PeerId peer_id, ConnectCallback callback) { // We must be connected and to the right peer auto connection = std::move(result).value(); - BT_ASSERT(connection); - BT_ASSERT(peer_id == connection->peer_identifier()); + PW_CHECK(connection); + PW_CHECK(peer_id == connection->peer_identifier()); callback(fpromise::ok()); @@ -661,7 +661,7 @@ void HostServer::ConnectBrEdr(PeerId peer_id, ConnectCallback callback) { peer_id, func = __FUNCTION__](auto status, auto connection) { if (status.is_error()) { - BT_ASSERT(!connection); + PW_CHECK(!connection); bt_log(INFO, "fidl", "%s: failed to connect BR/EDR transport to peer (peer: %s)", @@ -672,8 +672,8 @@ void HostServer::ConnectBrEdr(PeerId peer_id, ConnectCallback callback) { } // We must be connected and to the right peer - BT_ASSERT(connection); - BT_ASSERT(peer_id == connection->peer_id()); + PW_CHECK(connection); + PW_CHECK(peer_id == connection->peer_id()); callback(fpromise::ok()); }; @@ -713,7 +713,7 @@ void HostServer::Forget(fbt::PeerId peer_id, ForgetCallback callback) { bredr_disconnected ? "" : " BR/EDR"); callback(fpromise::error(fsys::Error::FAILED)); } else { - BT_ASSERT(peer_removed); + PW_CHECK(peer_removed); callback(fpromise::ok()); } } @@ -778,7 +778,7 @@ void HostServer::PairLowEnergy(PeerId peer_id, callback(fpromise::ok()); } }; - BT_ASSERT(adapter()->le()); + PW_CHECK(adapter()->le()); adapter()->le()->Pair( peer_id, *security_level, bondable_mode, std::move(on_complete)); } @@ -799,7 +799,7 @@ void HostServer::PairBrEdr(PeerId peer_id, PairCallback callback) { // instead of hardcoding default. bt::gap::BrEdrSecurityRequirements security{.authentication = false, .secure_connections = false}; - BT_ASSERT(adapter()->bredr()); + PW_CHECK(adapter()->bredr()); adapter()->bredr()->Pair(peer_id, security, std::move(on_complete)); } @@ -952,7 +952,7 @@ void HostServer::PeerWatcherServer::MaybeCallCallback() { bt::gap::Peer* peer = peer_cache_->FindById(id); // All ids in |updated_| are assumed to be valid as they would otherwise // be in |removed_|. - BT_ASSERT(peer); + PW_CHECK(peer); updated_fidl.push_back(fidl_helpers::PeerToFidl(*peer)); } updated_.clear(); @@ -1056,7 +1056,7 @@ void HostServer::CompletePairing(PeerId id, bt::sm::Result<> status) { "pairing complete for peer: %s, status: %s", bt_str(id), bt_str(status)); - BT_DEBUG_ASSERT(pairing_delegate_); + PW_DCHECK(pairing_delegate_); pairing_delegate_->OnPairingComplete(fbt::PeerId{id.value()}, status.is_ok()); } @@ -1086,10 +1086,10 @@ void HostServer::DisplayPasskey(PeerId id, void HostServer::RequestPasskey(PeerId id, PasskeyResponseCallback respond) { bt_log(DEBUG, "fidl", "passkey request for peer: %s", bt_str(id)); auto found_peer = adapter()->peer_cache()->FindById(id); - BT_ASSERT(found_peer); + PW_CHECK(found_peer); auto peer = fidl_helpers::PeerToFidl(*found_peer); - BT_ASSERT(pairing_delegate_); + PW_CHECK(pairing_delegate_); pairing_delegate_->OnPairingRequest( std::move(peer), fsys::PairingMethod::PASSKEY_ENTRY, @@ -1127,10 +1127,10 @@ void HostServer::DisplayPairingRequest(bt::PeerId id, fsys::PairingMethod method, ConfirmCallback confirm) { auto found_peer = adapter()->peer_cache()->FindById(id); - BT_ASSERT(found_peer); + PW_CHECK(found_peer); auto peer = fidl_helpers::PeerToFidl(*found_peer); - BT_ASSERT(pairing_delegate_); + PW_CHECK(pairing_delegate_); uint32_t displayed_passkey = passkey ? *passkey : 0u; pairing_delegate_->OnPairingRequest( std::move(peer), @@ -1160,7 +1160,7 @@ void HostServer::DisplayPairingRequest(bt::PeerId id, } void HostServer::OnConnectionError(Server* server) { - BT_DEBUG_ASSERT(server); + PW_DCHECK(server); servers_.erase(server); } diff --git a/pw_bluetooth_sapphire/fuchsia/host/fidl/host_server_test.cc b/pw_bluetooth_sapphire/fuchsia/host/fidl/host_server_test.cc index 6ee320976f..073fe3d15b 100644 --- a/pw_bluetooth_sapphire/fuchsia/host/fidl/host_server_test.cc +++ b/pw_bluetooth_sapphire/fuchsia/host/fidl/host_server_test.cc @@ -189,8 +189,8 @@ class HostServerTest : public bthost::testing::AdapterTestFixture { bt::gap::Peer* AddFakePeer(const bt::DeviceAddress& address) { bt::gap::Peer* peer = adapter()->peer_cache()->NewPeer(address, /*connectable=*/true); - BT_ASSERT(peer); - BT_ASSERT(peer->temporary()); + PW_CHECK(peer); + PW_CHECK(peer->temporary()); test_device()->AddPeer( std::make_unique(address, pw_dispatcher())); diff --git a/pw_bluetooth_sapphire/fuchsia/host/fidl/host_server_watch_peers_fuzztest.cc b/pw_bluetooth_sapphire/fuchsia/host/fidl/host_server_watch_peers_fuzztest.cc index 45f7058ded..cf4f4a0c40 100644 --- a/pw_bluetooth_sapphire/fuchsia/host/fidl/host_server_watch_peers_fuzztest.cc +++ b/pw_bluetooth_sapphire/fuchsia/host/fidl/host_server_watch_peers_fuzztest.cc @@ -43,7 +43,7 @@ class HostServerFuzzTest final : public bthost::testing::AdapterTestFixture { bt::gap::Peer* const peer = adapter()->peer_cache()->NewPeer( bt::testing::MakePublicDeviceAddress(fuzzed_data_provider), /*connectable=*/true); - BT_ASSERT(peer); + PW_CHECK(peer); bt::gap::testing::PeerFuzzer peer_fuzzer(fuzzed_data_provider, *peer); while (fuzzed_data_provider.remaining_bytes() != 0) { peer_fuzzer.FuzzOneField(); @@ -56,7 +56,7 @@ class HostServerFuzzTest final : public bthost::testing::AdapterTestFixture { peer_watcher()->GetNext( [this, peer, &watch_peers_responses]( fuchsia::bluetooth::host::PeerWatcher_GetNext_Result result) { - BT_ASSERT(result.is_response()); + PW_CHECK(result.is_response()); std::vector<::fuchsia::bluetooth::sys::Peer> updated; if (result.response().is_updated()) { updated = std::move(result.response().updated()); @@ -65,14 +65,14 @@ class HostServerFuzzTest final : public bthost::testing::AdapterTestFixture { if (result.response().is_removed()) { removed = std::move(result.response().removed()); } - BT_ASSERT_MSG(updated.size() == 1, - "peer %s: peers updated = %zu", - bt_str(*peer), - updated.size()); - BT_ASSERT_MSG(removed.size() == 0, - "peer %s: peers removed = %zu", - bt_str(*peer), - removed.size()); + PW_CHECK(updated.size() == 1, + "peer %s: peers updated = %zu", + bt_str(*peer), + updated.size()); + PW_CHECK(removed.size() == 0, + "peer %s: peers removed = %zu", + bt_str(*peer), + removed.size()); HandleWatchPeersResponse(*host_client(), watch_peers_responses, /*max_call_depth=*/1, @@ -80,10 +80,10 @@ class HostServerFuzzTest final : public bthost::testing::AdapterTestFixture { std::move(removed)); }); RunLoopUntilIdle(); - BT_ASSERT_MSG(watch_peers_responses == 1, - "peer %s: WatchPeers returned %d times", - bt_str(*peer), - watch_peers_responses); + PW_CHECK(watch_peers_responses == 1, + "peer %s: WatchPeers returned %d times", + bt_str(*peer), + watch_peers_responses); } private: @@ -121,13 +121,13 @@ class HostServerFuzzTest final : public bthost::testing::AdapterTestFixture { std::vector updated, std::vector removed) { call_counter++; - BT_ASSERT_MSG(call_counter <= max_call_depth, - "max depth (%d) exceeded", - call_counter); + PW_CHECK(call_counter <= max_call_depth, + "max depth (%d) exceeded", + call_counter); peer_watcher()->GetNext( [this, &host, &call_counter, max_call_depth]( fuchsia::bluetooth::host::PeerWatcher_GetNext_Result result) { - BT_ASSERT(result.is_response()); + PW_CHECK(result.is_response()); std::vector<::fuchsia::bluetooth::sys::Peer> updated; if (result.response().is_updated()) { updated = std::move(result.response().updated()); diff --git a/pw_bluetooth_sapphire/fuchsia/host/fidl/iso_stream_server.cc b/pw_bluetooth_sapphire/fuchsia/host/fidl/iso_stream_server.cc index aba3fffd5b..98d1a33dd3 100644 --- a/pw_bluetooth_sapphire/fuchsia/host/fidl/iso_stream_server.cc +++ b/pw_bluetooth_sapphire/fuchsia/host/fidl/iso_stream_server.cc @@ -46,7 +46,7 @@ void IsoStreamServer::OnStreamEstablished( void IsoStreamServer::OnStreamEstablishmentFailed( pw::bluetooth::emboss::StatusCode status) { - BT_ASSERT(status != pw::bluetooth::emboss::StatusCode::SUCCESS); + PW_CHECK(status != pw::bluetooth::emboss::StatusCode::SUCCESS); bt_log(WARN, "fidl", "CIS failed to be established: %u", diff --git a/pw_bluetooth_sapphire/fuchsia/host/fidl/low_energy_central_server.cc b/pw_bluetooth_sapphire/fuchsia/host/fidl/low_energy_central_server.cc index 91b4fc1f9b..b54518e5df 100644 --- a/pw_bluetooth_sapphire/fuchsia/host/fidl/low_energy_central_server.cc +++ b/pw_bluetooth_sapphire/fuchsia/host/fidl/low_energy_central_server.cc @@ -68,7 +68,7 @@ LowEnergyCentralServer::LowEnergyCentralServer( gatt_(std::move(gatt)), requesting_scan_deprecated_(false), weak_self_(this) { - BT_ASSERT(gatt_.is_alive()); + PW_CHECK(gatt_.is_alive()); } LowEnergyCentralServer::~LowEnergyCentralServer() { @@ -96,7 +96,7 @@ LowEnergyCentralServer::ScanResultWatcherServer::ScanResultWatcherServer( error_callback_(std::move(error_cb)) { set_error_handler([this](auto) { bt_log(DEBUG, "fidl", "ScanResultWatcher client closed, stopping scan"); - BT_ASSERT(error_callback_); + PW_CHECK(error_callback_); error_callback_(); }); } @@ -134,7 +134,7 @@ void LowEnergyCentralServer::ScanResultWatcherServer::Watch( "%s: called before previous call completed", __FUNCTION__); Close(ZX_ERR_CANCELED); - BT_ASSERT(error_callback_); + PW_CHECK(error_callback_); error_callback_(); return; } @@ -165,10 +165,10 @@ void LowEnergyCentralServer::ScanResultWatcherServer::MaybeSendPeers() { fble::Peer fidl_peer = fidl_helpers::PeerToFidlLe(*peer); measure_fble::Size peer_size = measure_fble::Measure(fidl_peer); - BT_ASSERT_MSG(peer_size.num_handles == 0, - "Expected fuchsia.bluetooth.le/Peer to not have handles, but " - "%zu handles found", - peer_size.num_handles); + PW_CHECK(peer_size.num_handles == 0, + "Expected fuchsia.bluetooth.le/Peer to not have handles, but " + "%zu handles found", + peer_size.num_handles); bytes_used += peer_size.num_bytes; if (bytes_used > kMaxBytes) { // Don't remove the peer that exceeded the size limit. It will be sent in @@ -363,8 +363,8 @@ void LowEnergyCentralServer::Connect( return; auto conn_iter = self->connections_.find(peer_id); - BT_ASSERT(conn_iter != self->connections_.end()); - BT_ASSERT(conn_iter->second == nullptr); + PW_CHECK(conn_iter != self->connections_.end()); + PW_CHECK(conn_iter->second == nullptr); if (result.is_error()) { bt_log(INFO, @@ -377,8 +377,8 @@ void LowEnergyCentralServer::Connect( } auto conn_ref = std::move(result).value(); - BT_ASSERT(conn_ref); - BT_ASSERT(peer_id == conn_ref->peer_identifier()); + PW_CHECK(conn_ref); + PW_CHECK(peer_id == conn_ref->peer_identifier()); auto closed_cb = [self, peer_id] { if (self.is_alive()) { @@ -392,7 +392,7 @@ void LowEnergyCentralServer::Connect( request.TakeChannel(), std::move(closed_cb)); - BT_ASSERT(!conn_iter->second); + PW_CHECK(!conn_iter->second); conn_iter->second = std::move(server); }; @@ -577,8 +577,8 @@ void LowEnergyCentralServer::ConnectPeripheral( } auto conn_ref = std::move(result).value(); - BT_ASSERT(conn_ref); - BT_ASSERT(peer_id == conn_ref->peer_identifier()); + PW_CHECK(conn_ref); + PW_CHECK(peer_id == conn_ref->peer_identifier()); if (self->gatt_client_servers_.find(peer_id) != self->gatt_client_servers_.end()) { @@ -612,7 +612,7 @@ void LowEnergyCentralServer::ConnectPeripheral( } }); - BT_ASSERT(!iter->second); + PW_CHECK(!iter->second); iter->second = std::move(conn_ref); callback(Status()); }; diff --git a/pw_bluetooth_sapphire/fuchsia/host/fidl/low_energy_central_server_test.cc b/pw_bluetooth_sapphire/fuchsia/host/fidl/low_energy_central_server_test.cc index 13b0b9570e..43f0c08e4f 100644 --- a/pw_bluetooth_sapphire/fuchsia/host/fidl/low_energy_central_server_test.cc +++ b/pw_bluetooth_sapphire/fuchsia/host/fidl/low_energy_central_server_test.cc @@ -100,7 +100,7 @@ class LowEnergyCentralServerTest : public TestingBase { // Ownership of |handle| remains with the caller when this method returns. bool IsClientHandleClosedAfterLoop( fidl::InterfaceHandle* handle) { - BT_ASSERT(handle); + PW_CHECK(handle); fgatt::ClientPtr proxy; proxy.Bind(std::move(*handle)); diff --git a/pw_bluetooth_sapphire/fuchsia/host/fidl/low_energy_connection_server.cc b/pw_bluetooth_sapphire/fuchsia/host/fidl/low_energy_connection_server.cc index 89cbc1dd54..d8673c2257 100644 --- a/pw_bluetooth_sapphire/fuchsia/host/fidl/low_energy_connection_server.cc +++ b/pw_bluetooth_sapphire/fuchsia/host/fidl/low_energy_connection_server.cc @@ -34,7 +34,7 @@ LowEnergyConnectionServer::LowEnergyConnectionServer( peer_id_(conn_->peer_identifier()), adapter_(std::move(adapter)), gatt_(std::move(gatt)) { - BT_DEBUG_ASSERT(conn_); + PW_DCHECK(conn_); set_error_handler([this](zx_status_t) { OnClosed(); }); conn_->set_closed_callback( @@ -105,8 +105,8 @@ void LowEnergyConnectionServer::AcceptCis( connection_params) { if (weak_stream_server.is_alive()) { if (status == pw::bluetooth::emboss::StatusCode::SUCCESS) { - BT_ASSERT(weak_stream_ptr.has_value()); - BT_ASSERT(connection_params.has_value()); + PW_CHECK(weak_stream_ptr.has_value()); + PW_CHECK(connection_params.has_value()); weak_stream_server->OnStreamEstablished(*weak_stream_ptr, *connection_params); } else { diff --git a/pw_bluetooth_sapphire/fuchsia/host/fidl/low_energy_connection_server_test.cc b/pw_bluetooth_sapphire/fuchsia/host/fidl/low_energy_connection_server_test.cc index 3c89006892..bfc4af788f 100644 --- a/pw_bluetooth_sapphire/fuchsia/host/fidl/low_energy_connection_server_test.cc +++ b/pw_bluetooth_sapphire/fuchsia/host/fidl/low_energy_connection_server_test.cc @@ -60,7 +60,7 @@ class LowEnergyConnectionServerTest [&](const bt::gap::Peer& peer) { peer_id = peer.identifier(); }); }); RunLoopUntilIdle(); - BT_ASSERT(peer_id); + PW_CHECK(peer_id); peer_id_ = *peer_id; std::optional @@ -72,8 +72,8 @@ class LowEnergyConnectionServerTest }, bt::gap::LowEnergyConnectionOptions()); RunLoopUntilIdle(); - BT_ASSERT(conn_result); - BT_ASSERT(conn_result->is_ok()); + PW_CHECK(conn_result); + PW_CHECK(conn_result->is_ok()); std::unique_ptr connection = std::move(*conn_result).value(); diff --git a/pw_bluetooth_sapphire/fuchsia/host/fidl/low_energy_peripheral_server.cc b/pw_bluetooth_sapphire/fuchsia/host/fidl/low_energy_peripheral_server.cc index cd937e007a..06603e07b1 100644 --- a/pw_bluetooth_sapphire/fuchsia/host/fidl/low_energy_peripheral_server.cc +++ b/pw_bluetooth_sapphire/fuchsia/host/fidl/low_energy_peripheral_server.cc @@ -38,8 +38,7 @@ namespace bthost { namespace { fble::PeripheralError FidlErrorFromStatus(bt::hci::Result<> status) { - BT_ASSERT_MSG(status.is_error(), - "FidlErrorFromStatus called on success status"); + PW_CHECK(status.is_error(), "FidlErrorFromStatus called on success status"); return status.error_value().Visit( [](bt::HostError host_error) { switch (host_error) { @@ -74,7 +73,7 @@ LowEnergyPeripheralServer::AdvertisementInstance::AdvertisementInstance( parameters_(std::move(parameters)), advertise_complete_cb_(std::move(complete_cb)), weak_self_(this) { - BT_ASSERT(advertise_complete_cb_); + PW_CHECK(advertise_complete_cb_); advertised_peripheral_.Bind(std::move(handle)); advertised_peripheral_.set_error_handler( [this, peripheral_server, id](zx_status_t /*status*/) { @@ -126,14 +125,14 @@ void LowEnergyPeripheralServer::ListenL2cap( void LowEnergyPeripheralServer::AdvertisementInstance::Register( bt::gap::AdvertisementInstance instance) { - BT_ASSERT(!instance_); + PW_CHECK(!instance_); instance_ = std::move(instance); } void LowEnergyPeripheralServer::AdvertisementInstance::OnConnected( bt::gap::AdvertisementId advertisement_id, bt::gap::Adapter::LowEnergy::ConnectionResult result) { - BT_ASSERT(advertisement_id != bt::gap::kInvalidAdvertisementId); + PW_CHECK(advertisement_id != bt::gap::kInvalidAdvertisementId); // HCI advertising ends when a connection is received (even for error // results), so clear the stale advertisement handle. @@ -156,7 +155,7 @@ void LowEnergyPeripheralServer::AdvertisementInstance::OnConnected( bt::PeerId peer_id = conn->peer_identifier(); bt::gap::Peer* peer = peripheral_server_->adapter()->peer_cache()->FindById(peer_id); - BT_ASSERT(peer); + PW_CHECK(peer); bt_log(INFO, LOG_TAG, @@ -195,7 +194,7 @@ LowEnergyPeripheralServer::AdvertisementInstanceDeprecated:: fidl::InterfaceRequest handle) : handle_(std::move(handle)) { - BT_DEBUG_ASSERT(handle_); + PW_DCHECK(handle_); } LowEnergyPeripheralServer::AdvertisementInstanceDeprecated:: @@ -206,7 +205,7 @@ LowEnergyPeripheralServer::AdvertisementInstanceDeprecated:: zx_status_t LowEnergyPeripheralServer::AdvertisementInstanceDeprecated::Register( bt::gap::AdvertisementInstance instance) { - BT_DEBUG_ASSERT(!instance_); + PW_DCHECK(!instance_); instance_ = std::move(instance); @@ -241,7 +240,7 @@ LowEnergyPeripheralServer::LowEnergyPeripheralServer( weak_self_(this) {} LowEnergyPeripheralServer::~LowEnergyPeripheralServer() { - BT_ASSERT(adapter()->bredr()); + PW_CHECK(adapter()->bredr()); } void LowEnergyPeripheralServer::Advertise( @@ -275,7 +274,7 @@ void LowEnergyPeripheralServer::Advertise( std::move(parameters), std::move(advertised_peripheral), std::move(callback)); - BT_ASSERT(inserted); + PW_CHECK(inserted); iter->second.StartAdvertising(); } @@ -314,9 +313,9 @@ void LowEnergyPeripheralServer::StartAdvertising( return; } - BT_ASSERT(self->advertisement_deprecated_); - BT_ASSERT(self->advertisement_deprecated_->id() == - bt::gap::kInvalidAdvertisementId); + PW_CHECK(self->advertisement_deprecated_); + PW_CHECK(self->advertisement_deprecated_->id() == + bt::gap::kInvalidAdvertisementId); fble::Peripheral_StartAdvertising_Result result; if (status.is_error()) { @@ -372,7 +371,7 @@ LowEnergyPeripheralServer::FindConnectionForTesting(bt::PeerId id) const { void LowEnergyPeripheralServer::OnConnectedDeprecated( bt::gap::AdvertisementId advertisement_id, bt::gap::Adapter::LowEnergy::ConnectionResult result) { - BT_ASSERT(advertisement_id != bt::gap::kInvalidAdvertisementId); + PW_CHECK(advertisement_id != bt::gap::kInvalidAdvertisementId); // Abort connection procedure if advertisement was canceled by the client. if (!advertisement_deprecated_ || @@ -406,7 +405,7 @@ void LowEnergyPeripheralServer::OnConnectedDeprecated( auto conn = std::move(result).value(); auto peer_id = conn->peer_identifier(); auto* peer = adapter()->peer_cache()->FindById(peer_id); - BT_ASSERT(peer); + PW_CHECK(peer); bt_log(INFO, LOG_TAG, @@ -427,7 +426,7 @@ LowEnergyPeripheralServer::CreateConnectionServer( std::unique_ptr connection) { zx::channel local, remote; zx_status_t status = zx::channel::create(0, &local, &remote); - BT_ASSERT(status == ZX_OK); + PW_CHECK(status == ZX_OK); auto conn_server_id = next_connection_server_id_++; auto conn_server = std::make_unique( @@ -551,7 +550,7 @@ void LowEnergyPeripheralServer::StartAdvertisingInternal( extended_pdu = parameters.advertising_procedure().is_extended(); } - BT_ASSERT(adapter()->le()); + PW_CHECK(adapter()->le()); adapter()->le()->StartAdvertising(std::move(adv_data), std::move(scan_rsp), interval, diff --git a/pw_bluetooth_sapphire/fuchsia/host/fidl/profile_server.cc b/pw_bluetooth_sapphire/fuchsia/host/fidl/profile_server.cc index 7094ea8b92..f75e7e0ea8 100644 --- a/pw_bluetooth_sapphire/fuchsia/host/fidl/profile_server.cc +++ b/pw_bluetooth_sapphire/fuchsia/host/fidl/profile_server.cc @@ -103,7 +103,7 @@ fbt::ChannelParameters ChannelInfoToFidlChannelParameters( fidlbredr::DataElementPtr DataElementToFidl(const bt::sdp::DataElement* in) { auto elem = std::make_unique(); bt_log(TRACE, "fidl", "DataElementToFidl: %s", in->ToString().c_str()); - BT_DEBUG_ASSERT(in); + PW_DCHECK(in); switch (in->type()) { case bt::sdp::DataElement::Type::kUnsignedInt: { switch (in->size()) { @@ -147,13 +147,13 @@ fidlbredr::DataElementPtr DataElementToFidl(const bt::sdp::DataElement* in) { } case bt::sdp::DataElement::Type::kUuid: { auto uuid = in->Get(); - BT_DEBUG_ASSERT(uuid); + PW_DCHECK(uuid); elem->set_uuid(fidl_helpers::UuidToFidl(*uuid)); return elem; } case bt::sdp::DataElement::Type::kString: { auto bytes = in->Get(); - BT_DEBUG_ASSERT(bytes); + PW_DCHECK(bytes); std::vector data(bytes->cbegin(), bytes->cend()); elem->set_str(data); return elem; @@ -686,8 +686,8 @@ void ProfileServer::Advertise( registering.emplace_back(std::move(rec.value())); } - BT_ASSERT(adapter().is_alive()); - BT_ASSERT(adapter()->bredr()); + PW_CHECK(adapter().is_alive()); + PW_CHECK(adapter()->bredr()); uint64_t next = advertised_total_ + 1; @@ -783,7 +783,7 @@ void ProfileServer::Search( attributes.insert(bt::sdp::kBluetoothProfileDescriptorList); } - BT_DEBUG_ASSERT(adapter().is_alive()); + PW_DCHECK(adapter().is_alive()); auto next = searches_total_ + 1; @@ -866,7 +866,7 @@ void ProfileServer::Connect(fuchsia::bluetooth::PeerId peer_id, cb(fpromise::ok(std::move(fidl_chan.value()))); }; - BT_DEBUG_ASSERT(adapter().is_alive()); + PW_DCHECK(adapter().is_alive()); adapter()->bredr()->OpenL2capChannel( id, @@ -992,7 +992,7 @@ void ProfileServer::OnChannelConnected( return; } - BT_DEBUG_ASSERT(adapter().is_alive()); + PW_DCHECK(adapter().is_alive()); auto handle = channel->link_handle(); auto id = adapter()->bredr()->GetPeerId(handle); @@ -1000,11 +1000,11 @@ void ProfileServer::OnChannelConnected( // thing that we can connect. We can't say anything about what the higher // level protocols will be. auto prot_seq = protocol_list.At(0); - BT_ASSERT(prot_seq); + PW_CHECK(prot_seq); fidlbredr::ProtocolDescriptorPtr desc = DataElementToProtocolDescriptor(prot_seq); - BT_ASSERT(desc); + PW_CHECK(desc); fuchsia::bluetooth::PeerId peer_id{id.value()}; @@ -1141,10 +1141,10 @@ void ProfileServer::OnScoConnectionResult( } size_t parameter_index = result.value().second; - BT_ASSERT_MSG(parameter_index < server->parameters().size(), - "parameter_index (%zu) >= request->parameters.size() (%zu)", - parameter_index, - server->parameters().size()); + PW_CHECK(parameter_index < server->parameters().size(), + "parameter_index (%zu) >= request->parameters.size() (%zu)", + parameter_index, + server->parameters().size()); fidlbredr::ScoConnectionParameters parameters = fidl::Clone(server->parameters()[parameter_index]); parameters.set_max_tx_data_size(max_tx_data_size); @@ -1278,7 +1278,7 @@ ProfileServer::BindBrEdrConnectionServer( std::optional ProfileServer::ChannelToFidl( bt::l2cap::Channel::WeakPtr channel) { - BT_ASSERT(channel.is_alive()); + PW_CHECK(channel.is_alive()); fidlbredr::Channel fidl_chan; fidl_chan.set_channel_mode(ChannelModeToFidl(channel->mode())); fidl_chan.set_max_tx_sdu_size(channel->max_tx_sdu_size()); diff --git a/pw_bluetooth_sapphire/fuchsia/host/fidl/public/pw_bluetooth_sapphire/fuchsia/host/fidl/fake_gatt_fixture.h b/pw_bluetooth_sapphire/fuchsia/host/fidl/public/pw_bluetooth_sapphire/fuchsia/host/fidl/fake_gatt_fixture.h index 2f128a9aa8..fa1a0166e9 100644 --- a/pw_bluetooth_sapphire/fuchsia/host/fidl/public/pw_bluetooth_sapphire/fuchsia/host/fidl/fake_gatt_fixture.h +++ b/pw_bluetooth_sapphire/fuchsia/host/fidl/public/pw_bluetooth_sapphire/fuchsia/host/fidl/fake_gatt_fixture.h @@ -33,14 +33,14 @@ class FakeGattFixture : public bt::testing::TestLoopFixture { protected: const bt::gatt::GATT::WeakPtr& gatt() const { - BT_ASSERT_MSG(weak_gatt_.is_alive(), - "fake GATT layer accessed after it was destroyed!"); + PW_CHECK(weak_gatt_.is_alive(), + "fake GATT layer accessed after it was destroyed!"); return weak_gatt_; } const bt::gatt::testing::FakeLayer::WeakPtr& fake_gatt() const { - BT_ASSERT_MSG(weak_fake_layer_.is_alive(), - "fake GATT layer accessed after it was destroyed!"); + PW_CHECK(weak_fake_layer_.is_alive(), + "fake GATT layer accessed after it was destroyed!"); return weak_fake_layer_; } diff --git a/pw_bluetooth_sapphire/fuchsia/host/fidl/public/pw_bluetooth_sapphire/fuchsia/host/fidl/fake_vendor_server.h b/pw_bluetooth_sapphire/fuchsia/host/fidl/public/pw_bluetooth_sapphire/fuchsia/host/fidl/fake_vendor_server.h index 985962443d..af7812621a 100644 --- a/pw_bluetooth_sapphire/fuchsia/host/fidl/public/pw_bluetooth_sapphire/fuchsia/host/fidl/fake_vendor_server.h +++ b/pw_bluetooth_sapphire/fuchsia/host/fidl/public/pw_bluetooth_sapphire/fuchsia/host/fidl/fake_vendor_server.h @@ -48,8 +48,8 @@ class FakeVendorServer final void EncodeCommand(EncodeCommandRequest& request, EncodeCommandCompleter::Sync& completer) override { - BT_ASSERT(request.set_acl_priority()->priority().has_value()); - BT_ASSERT(request.set_acl_priority()->direction().has_value()); + PW_CHECK(request.set_acl_priority()->priority().has_value()); + PW_CHECK(request.set_acl_priority()->direction().has_value()); std::vector tmp{static_cast( WhichSetAclPriority(request.set_acl_priority()->priority().value(), request.set_acl_priority()->direction().value()))}; diff --git a/pw_bluetooth_sapphire/fuchsia/host/fidl/public/pw_bluetooth_sapphire/fuchsia/host/fidl/server_base.h b/pw_bluetooth_sapphire/fuchsia/host/fidl/public/pw_bluetooth_sapphire/fuchsia/host/fidl/server_base.h index feae41e560..b97052037e 100644 --- a/pw_bluetooth_sapphire/fuchsia/host/fidl/public/pw_bluetooth_sapphire/fuchsia/host/fidl/server_base.h +++ b/pw_bluetooth_sapphire/fuchsia/host/fidl/public/pw_bluetooth_sapphire/fuchsia/host/fidl/server_base.h @@ -58,7 +58,7 @@ class ServerBase : public Server, public Interface { // Constructs a FIDL server by binding a zx::channel. ServerBase(Interface* impl, zx::channel channel) : binding_(impl, std::move(channel)) { - BT_DEBUG_ASSERT(binding_.is_bound()); + PW_DCHECK(binding_.is_bound()); } ~ServerBase() override = default; @@ -93,7 +93,7 @@ class AdapterServerBase : public ServerBase { zx::channel channel) : ServerBase(impl, std::move(channel)), adapter_(std::move(adapter)) { - BT_DEBUG_ASSERT(adapter_.is_alive()); + PW_DCHECK(adapter_.is_alive()); } ~AdapterServerBase() override = default; @@ -117,7 +117,7 @@ class GattServerBase : public ServerBase { fidl::InterfaceRequest request) : ServerBase(impl, std::move(request)), gatt_(std::move(gatt)) { - BT_DEBUG_ASSERT(gatt_.is_alive()); + PW_DCHECK(gatt_.is_alive()); } ~GattServerBase() override = default; diff --git a/pw_bluetooth_sapphire/fuchsia/host/socket/public/pw_bluetooth_sapphire/fuchsia/host/socket/socket_channel_relay.h b/pw_bluetooth_sapphire/fuchsia/host/socket/public/pw_bluetooth_sapphire/fuchsia/host/socket/socket_channel_relay.h index 50d9d8fe27..cae33d87bf 100644 --- a/pw_bluetooth_sapphire/fuchsia/host/socket/public/pw_bluetooth_sapphire/fuchsia/host/socket/socket_channel_relay.h +++ b/pw_bluetooth_sapphire/fuchsia/host/socket/public/pw_bluetooth_sapphire/fuchsia/host/socket/socket_channel_relay.h @@ -201,9 +201,9 @@ SocketChannelRelay::SocketChannelRelay( // detect truncated datagrams. read_buf_(channel_->max_tx_sdu_size() + 1), weak_self_(this) { - BT_ASSERT(dispatcher_); - BT_ASSERT(socket_); - BT_ASSERT(channel_.is_alive()); + PW_CHECK(dispatcher_); + PW_CHECK(socket_); + PW_CHECK(channel_.is_alive()); // Note: binding |this| is safe, as BindWait() wraps the bound method inside // of a lambda which verifies that |this| hasn't been destroyed. @@ -234,7 +234,7 @@ SocketChannelRelay::~SocketChannelRelay() { template bool SocketChannelRelay::Activate() { - BT_ASSERT(state_ == RelayState::kActivating); + PW_CHECK(state_ == RelayState::kActivating); // Note: we assume that BeginWait() does not synchronously dispatch any // events. The wait handler will assert otherwise. @@ -283,7 +283,7 @@ bool SocketChannelRelay::Activate() { template void SocketChannelRelay::Deactivate() { - BT_ASSERT(state_ != RelayState::kDeactivated); + PW_CHECK(state_ != RelayState::kDeactivated); state_ = RelayState::kDeactivating; if (!socket_write_queue_.empty()) { @@ -299,7 +299,7 @@ void SocketChannelRelay::Deactivate() { // We assume that UnbindAndCancelWait() will not trigger a re-entrant call // into Deactivate(). And the RelayIsDestroyedWhenDispatcherIsShutDown test // verifies that to be the case. (If we had re-entrant calls, a - // BT_ASSERT() in the lambda bound by BindWait() would cause an abort.) + // PW_CHECK() in the lambda bound by BindWait() would cause an abort.) UnbindAndCancelWait(&sock_read_waiter_); UnbindAndCancelWait(&sock_write_waiter_); UnbindAndCancelWait(&sock_close_waiter_); @@ -324,7 +324,7 @@ void SocketChannelRelay::DeactivateAndRequestDestruction() { template void SocketChannelRelay::OnSocketReadable(zx_status_t status) { - BT_ASSERT(state_ == RelayState::kActivated); + PW_CHECK(state_ == RelayState::kActivated); if (!CopyFromSocketToChannel() || !BeginWait("socket read waiter", &sock_read_waiter_)) { DeactivateAndRequestDestruction(); @@ -333,7 +333,7 @@ void SocketChannelRelay::OnSocketReadable(zx_status_t status) { template void SocketChannelRelay::OnSocketWritable(zx_status_t status) { - BT_ASSERT(state_ == RelayState::kActivated); + PW_CHECK(state_ == RelayState::kActivated); if (socket_write_queue_.empty()) { // The write queue may be emptied before this signal handler is called if // the first packet in the write queue gets dropped and the subsequent @@ -350,7 +350,7 @@ void SocketChannelRelay::OnSocketWritable(zx_status_t status) { template void SocketChannelRelay::OnSocketClosed(zx_status_t status) { - BT_ASSERT(state_ == RelayState::kActivated); + PW_CHECK(state_ == RelayState::kActivated); DeactivateAndRequestDestruction(); } @@ -359,7 +359,7 @@ void SocketChannelRelay::OnChannelDataReceived( ByteBufferPtr rx_data) { // Note: kActivating is deliberately permitted, as ChannelImpl::Activate() // will synchronously deliver any queued frames. - BT_ASSERT(state_ != RelayState::kDeactivated); + PW_CHECK(state_ != RelayState::kDeactivated); TRACE_DURATION("bluetooth", "SocketChannelRelay::OnChannelDataReceived", "channel id", @@ -374,7 +374,7 @@ void SocketChannelRelay::OnChannelDataReceived( return; } - BT_ASSERT(rx_data); + PW_CHECK(rx_data); if (rx_data->size() == 0) { bt_log(DEBUG, "l2cap", @@ -384,7 +384,7 @@ void SocketChannelRelay::OnChannelDataReceived( return; } - BT_ASSERT(socket_write_queue_.size() <= socket_write_queue_max_frames_); + PW_CHECK(socket_write_queue_.size() <= socket_write_queue_max_frames_); // On a full queue, we drop the oldest element, on the theory that newer data // is more useful. This should be true, e.g., for real-time applications such // as voice calls. In the future, we may want to make the drop-head vs. @@ -413,8 +413,8 @@ void SocketChannelRelay::OnChannelDataReceived( template void SocketChannelRelay::OnChannelClosed() { - BT_ASSERT(state_ != RelayState::kActivating); - BT_ASSERT(state_ != RelayState::kDeactivated); + PW_CHECK(state_ != RelayState::kActivating); + PW_CHECK(state_ != RelayState::kDeactivated); if (state_ == RelayState::kDeactivating) { bt_log(DEBUG, @@ -425,7 +425,7 @@ void SocketChannelRelay::OnChannelClosed() { return; } - BT_ASSERT(state_ == RelayState::kActivated); + PW_CHECK(state_ == RelayState::kActivated); if (!socket_write_queue_.empty()) { ServiceSocketWriteQueue(); } @@ -446,14 +446,14 @@ bool SocketChannelRelay::CopyFromSocketToChannel() { size_t n_bytes_read = 0; read_res = socket_.read( 0, read_buf_.mutable_data(), read_buf_.size(), &n_bytes_read); - BT_ASSERT_MSG(read_res == ZX_OK || read_res == ZX_ERR_SHOULD_WAIT || - read_res == ZX_ERR_PEER_CLOSED, - "%s", - zx_status_get_string(read_res)); - BT_ASSERT_MSG(n_bytes_read <= read_buf_.size(), - "(n_bytes_read=%zu, read_buf_size=%zu)", - n_bytes_read, - read_buf_.size()); + PW_CHECK(read_res == ZX_OK || read_res == ZX_ERR_SHOULD_WAIT || + read_res == ZX_ERR_PEER_CLOSED, + "%s", + zx_status_get_string(read_res)); + PW_CHECK(n_bytes_read <= read_buf_.size(), + "(n_bytes_read=%zu, read_buf_size=%zu)", + n_bytes_read, + read_buf_.size()); if (read_res == ZX_ERR_SHOULD_WAIT) { return true; } @@ -467,7 +467,7 @@ bool SocketChannelRelay::CopyFromSocketToChannel() { return false; } - BT_ASSERT(n_bytes_read > 0); + PW_CHECK(n_bytes_read > 0); socket_packet_recv_count_++; if (n_bytes_read > channel_->max_tx_sdu_size()) { bt_log(WARN, @@ -509,15 +509,15 @@ void SocketChannelRelay::ServiceSocketWriteQueue() { "channel_id", channel_->id()); do { - BT_ASSERT(!socket_write_queue_.empty()); - BT_ASSERT(socket_write_queue_.front()); + PW_CHECK(!socket_write_queue_.empty()); + PW_CHECK(socket_write_queue_.front()); TRACE_DURATION("bluetooth", "SocketChannelRelay::ServiceSocketWriteQueue write", "channel_id", channel_->id()); const ByteBuffer& rx_data = *socket_write_queue_.front(); - BT_ASSERT_MSG(rx_data.size(), "Zero-length message on write queue"); + PW_CHECK(rx_data.size(), "Zero-length message on write queue"); socket_packet_sent_count_++; TRACE_FLOW_END("bluetooth", @@ -530,12 +530,12 @@ void SocketChannelRelay::ServiceSocketWriteQueue() { size_t n_bytes_written = 0; write_res = socket_.write(0, rx_data.data(), rx_data.size(), &n_bytes_written); - BT_ASSERT_MSG(write_res == ZX_OK || write_res == ZX_ERR_SHOULD_WAIT || - write_res == ZX_ERR_PEER_CLOSED, - "%s", - zx_status_get_string(write_res)); + PW_CHECK(write_res == ZX_OK || write_res == ZX_ERR_SHOULD_WAIT || + write_res == ZX_ERR_PEER_CLOSED, + "%s", + zx_status_get_string(write_res)); if (write_res != ZX_OK) { - BT_ASSERT(n_bytes_written == 0); + PW_CHECK(n_bytes_written == 0); bt_log(TRACE, "l2cap", "Failed to write %zu bytes to socket for channel %u: %s", @@ -544,10 +544,10 @@ void SocketChannelRelay::ServiceSocketWriteQueue() { zx_status_get_string(write_res)); break; } - BT_ASSERT_MSG(n_bytes_written == rx_data.size(), - "(n_bytes_written=%zu, rx_data.size()=%zu)", - n_bytes_written, - rx_data.size()); + PW_CHECK(n_bytes_written == rx_data.size(), + "(n_bytes_written=%zu, rx_data.size()=%zu)", + n_bytes_written, + rx_data.size()); socket_write_queue_.pop_front(); } while (write_res == ZX_OK && !socket_write_queue_.empty()); @@ -597,20 +597,19 @@ void SocketChannelRelay::BindWait( async::WaitBase* actual_wait, zx_status_t status, const zx_packet_signal_t* signal) { - BT_ASSERT_MSG( - self.is_alive(), "(%s, channel_id=%u)", wait_name, channel_id); - BT_ASSERT_MSG(actual_dispatcher == self->dispatcher_, - "(%s, channel_id=%u)", - wait_name, - channel_id); - BT_ASSERT_MSG(actual_wait == expected_wait, - "(%s, channel_id=%u)", - wait_name, - channel_id); - BT_ASSERT_MSG(status == ZX_OK || status == ZX_ERR_CANCELED, - "(%s, channel_id=%u)", - wait_name, - channel_id); + PW_CHECK(self.is_alive(), "(%s, channel_id=%u)", wait_name, channel_id); + PW_CHECK(actual_dispatcher == self->dispatcher_, + "(%s, channel_id=%u)", + wait_name, + channel_id); + PW_CHECK(actual_wait == expected_wait, + "(%s, channel_id=%u)", + wait_name, + channel_id); + PW_CHECK(status == ZX_OK || status == ZX_ERR_CANCELED, + "(%s, channel_id=%u)", + wait_name, + channel_id); if (status == ZX_ERR_CANCELED) { // Dispatcher is shutting down. bt_log(DEBUG, @@ -622,19 +621,19 @@ void SocketChannelRelay::BindWait( return; } - BT_ASSERT_MSG(signal, "(%s, channel_id=%u)", wait_name, channel_id); - BT_ASSERT_MSG(signal->trigger == expected_wait->trigger(), - "(%s, channel_id=%u)", - wait_name, - channel_id); - BT_ASSERT_MSG(self->state_ != RelayState::kActivating, - "(%s, channel_id=%u)", - wait_name, - channel_id); - BT_ASSERT_MSG(self->state_ != RelayState::kDeactivated, - "(%s, channel_id=%u)", - wait_name, - channel_id); + PW_CHECK(signal, "(%s, channel_id=%u)", wait_name, channel_id); + PW_CHECK(signal->trigger == expected_wait->trigger(), + "(%s, channel_id=%u)", + wait_name, + channel_id); + PW_CHECK(self->state_ != RelayState::kActivating, + "(%s, channel_id=%u)", + wait_name, + channel_id); + PW_CHECK(self->state_ != RelayState::kDeactivated, + "(%s, channel_id=%u)", + wait_name, + channel_id); if (self->state_ == RelayState::kDeactivating) { bt_log(DEBUG, @@ -651,15 +650,15 @@ void SocketChannelRelay::BindWait( template bool SocketChannelRelay::BeginWait(const char* wait_name, async::Wait* wait) { - BT_ASSERT(state_ != RelayState::kDeactivating); - BT_ASSERT(state_ != RelayState::kDeactivated); + PW_CHECK(state_ != RelayState::kDeactivating); + PW_CHECK(state_ != RelayState::kDeactivated); if (wait->is_pending()) { return true; } zx_status_t wait_res = wait->Begin(dispatcher_); - BT_ASSERT(wait_res == ZX_OK || wait_res == ZX_ERR_BAD_STATE); + PW_CHECK(wait_res == ZX_OK || wait_res == ZX_ERR_BAD_STATE); if (wait_res != ZX_OK) { bt_log(ERROR, @@ -675,14 +674,14 @@ bool SocketChannelRelay::BeginWait(const char* wait_name, template void SocketChannelRelay::UnbindAndCancelWait(async::Wait* wait) { - BT_ASSERT(state_ != RelayState::kActivating); - BT_ASSERT(state_ != RelayState::kDeactivated); + PW_CHECK(state_ != RelayState::kActivating); + PW_CHECK(state_ != RelayState::kDeactivated); zx_status_t cancel_res; wait->set_handler(nullptr); cancel_res = wait->Cancel(); - BT_ASSERT_MSG(cancel_res == ZX_OK || cancel_res == ZX_ERR_NOT_FOUND, - "Cancel failed: %s", - zx_status_get_string(cancel_res)); + PW_CHECK(cancel_res == ZX_OK || cancel_res == ZX_ERR_NOT_FOUND, + "Cancel failed: %s", + zx_status_get_string(cancel_res)); } template diff --git a/pw_bluetooth_sapphire/fuchsia/host/socket/public/pw_bluetooth_sapphire/fuchsia/host/socket/socket_factory.h b/pw_bluetooth_sapphire/fuchsia/host/socket/public/pw_bluetooth_sapphire/fuchsia/host/socket/socket_factory.h index 6f41c8e74a..fbc54cc4a6 100644 --- a/pw_bluetooth_sapphire/fuchsia/host/socket/public/pw_bluetooth_sapphire/fuchsia/host/socket/socket_factory.h +++ b/pw_bluetooth_sapphire/fuchsia/host/socket/public/pw_bluetooth_sapphire/fuchsia/host/socket/socket_factory.h @@ -120,19 +120,18 @@ zx::socket SocketFactory::MakeSocketForChannel( auto relay = std::make_unique( std::move(local_socket), channel, - typename RelayT::DeactivationCallback( - [self = weak_self_.GetWeakPtr(), - id = unique_id, - closed_cb = std::move(closed_callback)]() mutable { - BT_DEBUG_ASSERT_MSG(self.is_alive(), "(unique_id=%u)", id); - size_t n_erased = self->channel_to_relay_.erase(id); - BT_DEBUG_ASSERT_MSG( - n_erased == 1, "(n_erased=%zu, unique_id=%u)", n_erased, id); - - if (closed_cb) { - closed_cb(); - } - })); + typename RelayT::DeactivationCallback([self = weak_self_.GetWeakPtr(), + id = unique_id, + closed_cb = std::move( + closed_callback)]() mutable { + PW_DCHECK(self.is_alive(), "(unique_id=%u)", id); + size_t n_erased = self->channel_to_relay_.erase(id); + PW_DCHECK(n_erased == 1, "(n_erased=%zu, unique_id=%u)", n_erased, id); + + if (closed_cb) { + closed_cb(); + } + })); // Note: Activate() may abort, if |channel| has been Activated() without // going through this SocketFactory. diff --git a/pw_bluetooth_sapphire/fuchsia/host/socket/socket_channel_relay_test.cc b/pw_bluetooth_sapphire/fuchsia/host/socket/socket_channel_relay_test.cc index 3cba172ae5..9c7a1c34a5 100644 --- a/pw_bluetooth_sapphire/fuchsia/host/socket/socket_channel_relay_test.cc +++ b/pw_bluetooth_sapphire/fuchsia/host/socket/socket_channel_relay_test.cc @@ -176,7 +176,7 @@ class SocketChannelRelayLifetimeTest : public SocketChannelRelayTest { return was_deactivation_callback_invoked_; } RelayT* relay() { - BT_DEBUG_ASSERT(relay_); + PW_DCHECK(relay_); return relay_.get(); } void DestroyRelay() { relay_ = nullptr; } diff --git a/pw_bluetooth_sapphire/host/att/attribute.cc b/pw_bluetooth_sapphire/host/att/attribute.cc index 3ef68cc017..2e79019f04 100644 --- a/pw_bluetooth_sapphire/host/att/attribute.cc +++ b/pw_bluetooth_sapphire/host/att/attribute.cc @@ -45,16 +45,16 @@ Attribute::Attribute(AttributeGrouping* group, type_(type), read_reqs_(read_reqs), write_reqs_(write_reqs) { - BT_DEBUG_ASSERT(group_); - BT_DEBUG_ASSERT(is_initialized()); + PW_DCHECK(group_); + PW_DCHECK(is_initialized()); } Attribute::Attribute() : handle_(kInvalidHandle) {} void Attribute::SetValue(const ByteBuffer& value) { - BT_DEBUG_ASSERT(value.size()); - BT_DEBUG_ASSERT(value.size() <= kMaxAttributeValueLength); - BT_DEBUG_ASSERT(!write_reqs_.allowed()); + PW_DCHECK(value.size()); + PW_DCHECK(value.size() <= kMaxAttributeValueLength); + PW_DCHECK(!write_reqs_.allowed()); value_ = DynamicByteBuffer(value); } @@ -90,12 +90,12 @@ AttributeGrouping::AttributeGrouping(const UUID& group_type, size_t attr_count, const ByteBuffer& decl_value) : start_handle_(start_handle), active_(false) { - BT_DEBUG_ASSERT(start_handle_ != kInvalidHandle); - BT_DEBUG_ASSERT(decl_value.size()); + PW_DCHECK(start_handle_ != kInvalidHandle); + PW_DCHECK(decl_value.size()); // It is a programmer error to provide an attr_count which overflows a handle // - this is why the below static cast is OK. - BT_ASSERT(kHandleMax - start_handle >= attr_count); + PW_CHECK(kHandleMax - start_handle >= attr_count); auto handle_attr_count = static_cast(attr_count); end_handle_ = start_handle + handle_attr_count; @@ -121,12 +121,12 @@ Attribute* AttributeGrouping::AddAttribute( if (complete()) return nullptr; - BT_DEBUG_ASSERT(attributes_[attributes_.size() - 1].handle() < end_handle_); + PW_DCHECK(attributes_[attributes_.size() - 1].handle() < end_handle_); // Groupings may not exceed kHandleMax attributes, so if we are incomplete per // the `complete()` check, we necessarily have < kHandleMax attributes. Thus // it is safe to cast attributes_.size() into a Handle. - BT_ASSERT(attributes_.size() < kHandleMax - start_handle_); + PW_CHECK(attributes_.size() < kHandleMax - start_handle_); Handle handle = start_handle_ + static_cast(attributes_.size()); attributes_.push_back(Attribute(this, handle, type, read_reqs, write_reqs)); diff --git a/pw_bluetooth_sapphire/host/att/bearer.cc b/pw_bluetooth_sapphire/host/att/bearer.cc index 7a28cf8c77..8f9195c7c2 100644 --- a/pw_bluetooth_sapphire/host/att/bearer.cc +++ b/pw_bluetooth_sapphire/host/att/bearer.cc @@ -193,8 +193,8 @@ Bearer::PendingTransaction::PendingTransaction(OpCode opcode_in, callback(std::move(callback_in)), pdu(std::move(pdu_in)), security_retry_level(sm::SecurityLevel::kNoSecurity) { - BT_ASSERT(this->callback); - BT_ASSERT(this->pdu); + PW_CHECK(this->callback); + PW_CHECK(this->pdu); } Bearer::PendingRemoteTransaction::PendingRemoteTransaction(TransactionId id_in, @@ -211,8 +211,8 @@ Bearer::TransactionQueue::TransactionQueue(TransactionQueue&& other) } Bearer::PendingTransactionPtr Bearer::TransactionQueue::ClearCurrent() { - BT_DEBUG_ASSERT(current_); - BT_DEBUG_ASSERT(timeout_task_.is_pending()); + PW_DCHECK(current_); + PW_DCHECK(timeout_task_.is_pending()); timeout_task_.Cancel(); @@ -227,7 +227,7 @@ void Bearer::TransactionQueue::TrySendNext( const l2cap::Channel::WeakPtr& chan, pw::async::TaskFunction timeout_cb, pw::chrono::SystemClock::duration timeout) { - BT_DEBUG_ASSERT(chan.is_alive()); + PW_DCHECK(chan.is_alive()); // Abort if a transaction is currently pending or there are no transactions // queued. @@ -239,8 +239,8 @@ void Bearer::TransactionQueue::TrySendNext( current_ = std::move(queue_.front()); queue_.pop(); while (current()) { - BT_DEBUG_ASSERT(!timeout_task_.is_pending()); - BT_DEBUG_ASSERT(current()->pdu); + PW_DCHECK(!timeout_task_.is_pending()); + PW_DCHECK(current()->pdu); // We copy the PDU payload in case it needs to be retried following a // security upgrade. @@ -296,7 +296,7 @@ Bearer::Bearer(l2cap::Channel::WeakPtr chan, pw::async::Dispatcher& dispatcher) next_remote_transaction_id_(1u), next_handler_id_(1u), weak_self_(this) { - BT_DEBUG_ASSERT(chan_); + PW_DCHECK(chan_); if (chan_->link_type() == bt::LinkType::kLE) { min_mtu_ = kLEMinMTU; @@ -331,7 +331,7 @@ void Bearer::ShutDownInternal(bool due_to_timeout) { if (shut_down_) { return; } - BT_ASSERT(is_open()); + PW_CHECK(is_open()); shut_down_ = true; bt_log(DEBUG, "att", "bearer shutting down"); @@ -362,14 +362,14 @@ void Bearer::ShutDownInternal(bool due_to_timeout) { } void Bearer::StartTransaction(ByteBufferPtr pdu, TransactionCallback callback) { - BT_ASSERT(pdu); - BT_ASSERT(callback); + PW_CHECK(pdu); + PW_CHECK(callback); [[maybe_unused]] bool _ = SendInternal(std::move(pdu), std::move(callback)); } bool Bearer::SendWithoutResponse(ByteBufferPtr pdu) { - BT_ASSERT(pdu); + PW_CHECK(pdu); return SendInternal(std::move(pdu), {}); } @@ -377,7 +377,7 @@ bool Bearer::SendInternal(ByteBufferPtr pdu, TransactionCallback callback) { auto _check_callback_empty = fit::defer([&callback]() { // Ensure that callback was either never present or called/moved before // SendInternal returns - BT_ASSERT(!callback); + PW_CHECK(!callback); }); if (!is_open()) { @@ -389,7 +389,7 @@ bool Bearer::SendInternal(ByteBufferPtr pdu, TransactionCallback callback) { return false; } - BT_ASSERT_MSG(IsPacketValid(*pdu), "packet has bad length!"); + PW_CHECK(IsPacketValid(*pdu), "packet has bad length!"); PacketReader reader(pdu.get()); MethodType type = GetMethodType(reader.opcode()); @@ -401,9 +401,9 @@ bool Bearer::SendInternal(ByteBufferPtr pdu, TransactionCallback callback) { switch (type) { case MethodType::kCommand: case MethodType::kNotification: - BT_ASSERT_MSG(!callback, - "opcode %#.2x has no response but callback was provided", - reader.opcode()); + PW_CHECK(!callback, + "opcode %#.2x has no response but callback was provided", + reader.opcode()); // Send the command. No flow control is necessary. chan_->Send(std::move(pdu)); @@ -420,10 +420,9 @@ bool Bearer::SendInternal(ByteBufferPtr pdu, TransactionCallback callback) { } PW_MODIFY_DIAGNOSTICS_POP(); - BT_ASSERT_MSG( - callback, - "transaction with opcode %#.2x has response that requires callback!", - reader.opcode()); + PW_CHECK(callback, + "transaction with opcode %#.2x has response that requires callback!", + reader.opcode()); tq->Enqueue(std::make_unique( reader.opcode(), std::move(callback), std::move(pdu))); @@ -433,7 +432,7 @@ bool Bearer::SendInternal(ByteBufferPtr pdu, TransactionCallback callback) { } Bearer::HandlerId Bearer::RegisterHandler(OpCode opcode, Handler handler) { - BT_DEBUG_ASSERT(handler); + PW_DCHECK(handler); if (!is_open()) return kInvalidHandlerId; @@ -451,7 +450,7 @@ Bearer::HandlerId Bearer::RegisterHandler(OpCode opcode, Handler handler) { return kInvalidHandlerId; auto res = handler_id_map_.emplace(id, opcode); - BT_ASSERT_MSG(res.second, "handler ID got reused (id: %zu)", id); + PW_CHECK(res.second, "handler ID got reused (id: %zu)", id); handlers_[opcode] = std::move(handler); @@ -459,7 +458,7 @@ Bearer::HandlerId Bearer::RegisterHandler(OpCode opcode, Handler handler) { } void Bearer::UnregisterHandler(HandlerId id) { - BT_DEBUG_ASSERT(id != kInvalidHandlerId); + PW_DCHECK(id != kInvalidHandlerId); auto iter = handler_id_map_.find(id); if (iter == handler_id_map_.end()) { @@ -472,7 +471,7 @@ void Bearer::UnregisterHandler(HandlerId id) { } bool Bearer::Reply(TransactionId tid, ByteBufferPtr pdu) { - BT_DEBUG_ASSERT(pdu); + PW_DCHECK(pdu); if (tid == kInvalidTransactionId) return false; @@ -537,7 +536,7 @@ bool Bearer::IsPacketValid(const ByteBuffer& packet) { } void Bearer::TryStartNextTransaction(TransactionQueue* tq) { - BT_DEBUG_ASSERT(tq); + PW_DCHECK(tq); if (!is_open()) { bt_log(TRACE, "att", "Cannot process transactions; bearer is closed"); @@ -558,7 +557,7 @@ void Bearer::SendErrorResponse(OpCode request_opcode, Handle attribute_handle, ErrorCode error_code) { auto buffer = NewBuffer(sizeof(Header) + sizeof(ErrorResponseParams)); - BT_ASSERT(buffer); + PW_CHECK(buffer); PacketWriter packet(kErrorResponse, buffer.get()); auto* payload = packet.mutable_payload(); @@ -572,8 +571,8 @@ void Bearer::SendErrorResponse(OpCode request_opcode, void Bearer::HandleEndTransaction(TransactionQueue* tq, const PacketReader& packet) { - BT_DEBUG_ASSERT(is_open()); - BT_DEBUG_ASSERT(tq); + PW_DCHECK(is_open()); + PW_DCHECK(tq); if (!tq->current()) { bt_log(DEBUG, @@ -589,7 +588,7 @@ void Bearer::HandleEndTransaction(TransactionQueue* tq, if (packet.opcode() == kErrorResponse) { // We should never hit this branch for indications. - BT_DEBUG_ASSERT(tq->current()->opcode != kIndication); + PW_DCHECK(tq->current()->opcode != kIndication); if (packet.payload_size() == sizeof(ErrorResponseParams)) { const auto& payload = packet.payload(); @@ -608,7 +607,7 @@ void Bearer::HandleEndTransaction(TransactionQueue* tq, target_opcode = MatchingTransactionCode(packet.opcode()); } - BT_DEBUG_ASSERT(tq->current()->opcode != kInvalidOpCode); + PW_DCHECK(tq->current()->opcode != kInvalidOpCode); if (tq->current()->opcode != target_opcode) { bt_log(DEBUG, @@ -621,7 +620,7 @@ void Bearer::HandleEndTransaction(TransactionQueue* tq, // The transaction is complete. auto transaction = tq->ClearCurrent(); - BT_DEBUG_ASSERT(transaction); + PW_DCHECK(transaction); const sm::SecurityLevel security_requirement = error.has_value() @@ -646,7 +645,7 @@ void Bearer::HandleEndTransaction(TransactionQueue* tq, return; } - BT_ASSERT(error.has_value()); + PW_CHECK(error.has_value()); bt_log(TRACE, "att", "Received security error %s for transaction; requesting upgrade to " @@ -673,7 +672,7 @@ void Bearer::HandleEndTransaction(TransactionQueue* tq, // Re-send the request as described in Vol 3, Part G, 8.1. Since |t| was // originally resolved with an Error Response, it must have come out of // |request_queue_|. - BT_DEBUG_ASSERT(GetMethodType(t->opcode) == MethodType::kRequest); + PW_DCHECK(GetMethodType(t->opcode) == MethodType::kRequest); t->security_retry_level = security_requirement; self->request_queue_.Enqueue(std::move(t)); self->TryStartNextTransaction(&self->request_queue_); @@ -707,7 +706,7 @@ Bearer::TransactionId Bearer::NextRemoteTransactionId() { void Bearer::HandleBeginTransaction(RemoteTransaction* currently_pending, const PacketReader& packet) { - BT_DEBUG_ASSERT(currently_pending); + PW_DCHECK(currently_pending); if (currently_pending->has_value()) { bt_log(DEBUG, @@ -766,8 +765,8 @@ void Bearer::OnChannelClosed() { } void Bearer::OnRxBFrame(ByteBufferPtr sdu) { - BT_DEBUG_ASSERT(sdu); - BT_DEBUG_ASSERT(is_open()); + PW_DCHECK(sdu); + PW_DCHECK(is_open()); TRACE_DURATION("bluetooth", "att::Bearer::OnRxBFrame", "length", sdu->size()); diff --git a/pw_bluetooth_sapphire/host/att/database.cc b/pw_bluetooth_sapphire/host/att/database.cc index fd8b6d0b86..1e3cd38741 100644 --- a/pw_bluetooth_sapphire/host/att/database.cc +++ b/pw_bluetooth_sapphire/host/att/database.cc @@ -42,7 +42,7 @@ Database::Iterator::Iterator(GroupingList* list, const UUID* type, bool groups_only) : start_(start), end_(end), grp_only_(groups_only), attr_offset_(0u) { - BT_DEBUG_ASSERT(list); + PW_DCHECK(list); grp_end_ = list->end(); if (type) @@ -81,7 +81,7 @@ const Attribute* Database::Iterator::get() const { if (AtEnd() || !grp_iter_->active()) return nullptr; - BT_DEBUG_ASSERT(attr_offset_ < grp_iter_->attributes().size()); + PW_DCHECK(attr_offset_ < grp_iter_->attributes().size()); return &grp_iter_->attributes()[attr_offset_]; } @@ -94,7 +94,7 @@ void Database::Iterator::Advance() { // If this grouping has more attributes to look at. if (attr_offset_ < grp_iter_->attributes().size() - 1) { size_t end_offset = grp_iter_->end_handle() - grp_iter_->start_handle(); - BT_DEBUG_ASSERT(end_offset < grp_iter_->attributes().size()); + PW_DCHECK(end_offset < grp_iter_->attributes().size()); // Advance. attr_offset_++; @@ -120,7 +120,7 @@ void Database::Iterator::Advance() { // next group below. attr_offset_ = 0u; } else { - BT_DEBUG_ASSERT(attr_offset_ == 0u); + PW_DCHECK(attr_offset_ == 0u); } // Advance the group. @@ -146,18 +146,18 @@ void Database::Iterator::Advance() { Database::Database(Handle range_start, Handle range_end) : WeakSelf(this), range_start_(range_start), range_end_(range_end) { - BT_DEBUG_ASSERT(range_start_ < range_end_); - BT_DEBUG_ASSERT(range_start_ >= kHandleMin); - BT_DEBUG_ASSERT(range_end_ <= kHandleMax); + PW_DCHECK(range_start_ < range_end_); + PW_DCHECK(range_start_ >= kHandleMin); + PW_DCHECK(range_end_ <= kHandleMax); } Database::Iterator Database::GetIterator(Handle start, Handle end, const UUID* type, bool groups_only) { - BT_DEBUG_ASSERT(start >= range_start_); - BT_DEBUG_ASSERT(end <= range_end_); - BT_DEBUG_ASSERT(start <= end); + PW_DCHECK(start >= range_start_); + PW_DCHECK(end <= range_end_); + PW_DCHECK(start <= end); return Iterator(&groupings_, start, end, type, groups_only); } @@ -208,7 +208,7 @@ AttributeGrouping* Database::NewGrouping(const UUID& group_type, auto iter = groupings_.emplace(pos, group_type, start_handle, attr_count, decl_value); - BT_DEBUG_ASSERT(iter != groupings_.end()); + PW_DCHECK(iter != groupings_.end()); return &*iter; } @@ -238,7 +238,7 @@ const Attribute* Database::FindAttribute(Handle handle) { return nullptr; size_t index = handle - iter->start_handle(); - BT_DEBUG_ASSERT(index < iter->attributes().size()); + PW_DCHECK(index < iter->attributes().size()); return &iter->attributes()[index]; } @@ -247,7 +247,7 @@ void Database::ExecuteWriteQueue(PeerId peer_id, PrepareWriteQueue write_queue, const sm::SecurityProperties& security, WriteCallback callback) { - BT_ASSERT(callback); + PW_CHECK(callback); // When destroyed, invokes |callback| with success if it hasn't already been // called diff --git a/pw_bluetooth_sapphire/host/att/database_test.cc b/pw_bluetooth_sapphire/host/att/database_test.cc index fd1301ec66..69239f2fb2 100644 --- a/pw_bluetooth_sapphire/host/att/database_test.cc +++ b/pw_bluetooth_sapphire/host/att/database_test.cc @@ -42,7 +42,7 @@ const StaticByteBuffer kTestValue2('x', 'x', 'x'); // Returns the handles of each attribute visited by advancing |iter| until the // end. std::vector IterHandles(Database::Iterator* iter) { - BT_DEBUG_ASSERT(iter); + PW_DCHECK(iter); std::vector handles; for (; !iter->AtEnd(); iter->Advance()) { diff --git a/pw_bluetooth_sapphire/host/att/error.cc b/pw_bluetooth_sapphire/host/att/error.cc index d5dc998511..0e4d521889 100644 --- a/pw_bluetooth_sapphire/host/att/error.cc +++ b/pw_bluetooth_sapphire/host/att/error.cc @@ -78,7 +78,7 @@ std::string ProtocolErrorTraits::ToString( "%s (ATT %#.2hhx)", ErrorToString(ecode), static_cast(ecode)); - BT_DEBUG_ASSERT(status.ok()); + PW_DCHECK(status.ok()); return out; } diff --git a/pw_bluetooth_sapphire/host/common/advertising_data.cc b/pw_bluetooth_sapphire/host/common/advertising_data.cc index d2dd5a91d8..c6c5ffa824 100644 --- a/pw_bluetooth_sapphire/host/common/advertising_data.cc +++ b/pw_bluetooth_sapphire/host/common/advertising_data.cc @@ -105,14 +105,14 @@ std::string EncodeUri(const std::string& uri) { if (std::equal(scheme, scheme + scheme_len, uri.begin())) { const pw::Result encoded_scheme = pw::utf8::EncodeCodePoint(i + 2); - BT_DEBUG_ASSERT(encoded_scheme.ok()); + PW_DCHECK(encoded_scheme.ok()); return std::string(encoded_scheme->as_view()) + uri.substr(scheme_len); } } // First codepoint (U+0001) is for uncompressed schemes. const pw::Result encoded_scheme = pw::utf8::EncodeCodePoint(1u); - BT_DEBUG_ASSERT(encoded_scheme.ok()); + PW_DCHECK(encoded_scheme.ok()); return std::string(encoded_scheme->as_view()) + uri; } @@ -322,7 +322,7 @@ AdvertisingData::ParseResult AdvertisingData::FromBytes( // While parsing through the advertising data fields, we do not need to // validate that per-field sizes do not overflow a uint8_t because they, by // construction, are obtained from a uint8_t. - BT_DEBUG_ASSERT(field.size() <= std::numeric_limits::max()); + PW_DCHECK(field.size() <= std::numeric_limits::max()); PW_MODIFY_DIAGNOSTICS_PUSH(); PW_MODIFY_DIAGNOSTIC(ignored, "-Wswitch-enum"); switch (type) { @@ -383,7 +383,7 @@ AdvertisingData::ParseResult AdvertisingData::FromBytes( const BufferView manuf_data(field.data() + kManufacturerIdSize, field.size() - kManufacturerIdSize); - BT_ASSERT(out_ad.SetManufacturerData(id, manuf_data)); + PW_CHECK(out_ad.SetManufacturerData(id, manuf_data)); break; } case DataType::kServiceData16Bit: @@ -404,7 +404,7 @@ AdvertisingData::ParseResult AdvertisingData::FromBytes( } const BufferView service_data(field.data() + uuid_size, field.size() - uuid_size); - BT_ASSERT(out_ad.SetServiceData(uuid, service_data)); + PW_CHECK(out_ad.SetServiceData(uuid, service_data)); break; } case DataType::kAppearance: { @@ -422,7 +422,7 @@ AdvertisingData::ParseResult AdvertisingData::FromBytes( case DataType::kURI: { // Assertion is safe as AddUri only fails when field size > uint8_t, // which is impossible. - BT_ASSERT(out_ad.AddUri(DecodeUri(field.ToString()))); + PW_CHECK(out_ad.AddUri(DecodeUri(field.ToString()))); break; } case DataType::kFlags: { @@ -452,7 +452,7 @@ void AdvertisingData::Copy(AdvertisingData* out) const { *out = AdvertisingData(); if (local_name_) { - BT_ASSERT(out->SetLocalName(*local_name_)); + PW_CHECK(out->SetLocalName(*local_name_)); } if (tx_power_) { @@ -466,21 +466,21 @@ void AdvertisingData::Copy(AdvertisingData* out) const { out->service_uuids_ = service_uuids_; for (const auto& it : manufacturer_data_) { - BT_ASSERT(out->SetManufacturerData(it.first, it.second.view())); + PW_CHECK(out->SetManufacturerData(it.first, it.second.view())); } for (const auto& it : service_data_) { - BT_ASSERT(out->SetServiceData(it.first, it.second.view())); + PW_CHECK(out->SetServiceData(it.first, it.second.view())); } for (const auto& it : uris_) { - BT_ASSERT_MSG(out->AddUri(it), "Copying invalid AD with too-long URI"); + PW_CHECK(out->AddUri(it), "Copying invalid AD with too-long URI"); } } [[nodiscard]] bool AdvertisingData::AddServiceUuid(const UUID& uuid) { auto iter = service_uuids_.find(uuid.CompactSize()); - BT_ASSERT(iter != service_uuids_.end()); + PW_CHECK(iter != service_uuids_.end()); BoundedUuids& uuids = iter->second; return uuids.AddUuid(uuid); } @@ -654,7 +654,7 @@ size_t AdvertisingData::CalculateBlockSize(bool include_flags) const { bool AdvertisingData::WriteBlock(MutableByteBuffer* buffer, std::optional flags) const { - BT_DEBUG_ASSERT(buffer); + PW_DCHECK(buffer); size_t min_buf_size = CalculateBlockSize(flags.has_value()); if (buffer->size() < min_buf_size) { @@ -684,7 +684,7 @@ bool AdvertisingData::WriteBlock(MutableByteBuffer* buffer, } if (local_name_) { - BT_ASSERT(local_name_->name.size() <= kMaxNameLength); + PW_CHECK(local_name_->name.size() <= kMaxNameLength); (*buffer)[pos++] = static_cast(local_name_->name.size()) + 1; // 1 for null char (*buffer)[pos++] = static_cast(DataType::kCompleteLocalName); @@ -696,7 +696,7 @@ bool AdvertisingData::WriteBlock(MutableByteBuffer* buffer, for (const auto& manuf_pair : manufacturer_data_) { size_t data_size = manuf_pair.second.size(); - BT_ASSERT(data_size <= kMaxManufacturerDataLength); + PW_CHECK(data_size <= kMaxManufacturerDataLength); (*buffer)[pos++] = 1 + 2 + static_cast(data_size); // 1 for type, 2 for Manuf. Code @@ -711,7 +711,7 @@ bool AdvertisingData::WriteBlock(MutableByteBuffer* buffer, UUID uuid = service_data_pair.first; size_t encoded_service_data_size = EncodedServiceDataSize(uuid, service_data_pair.second.view()); - BT_ASSERT(encoded_service_data_size <= kMaxEncodedServiceDataLength); + PW_CHECK(encoded_service_data_size <= kMaxEncodedServiceDataLength); (*buffer)[pos++] = 1 + static_cast(encoded_service_data_size); // 1 for type (*buffer)[pos++] = @@ -724,7 +724,7 @@ bool AdvertisingData::WriteBlock(MutableByteBuffer* buffer, for (const auto& uri : uris_) { std::string s = EncodeUri(uri); - BT_ASSERT(s.size() <= kMaxEncodedUriLength); + PW_CHECK(s.size() <= kMaxEncodedUriLength); (*buffer)[pos++] = 1 + static_cast(s.size()); // 1 for type (*buffer)[pos++] = static_cast(DataType::kURI); buffer->Write(reinterpret_cast(s.c_str()), s.length(), pos); @@ -737,17 +737,17 @@ bool AdvertisingData::WriteBlock(MutableByteBuffer* buffer, } // 1 for type - BT_ASSERT(1 + uuid_width * bounded_uuids.set().size() <= - std::numeric_limits::max()); + PW_CHECK(1 + uuid_width * bounded_uuids.set().size() <= + std::numeric_limits::max()); (*buffer)[pos++] = 1 + uuid_width * static_cast(bounded_uuids.set().size()); (*buffer)[pos++] = static_cast( ServiceUuidTypeForUuidSize(uuid_width, /*complete=*/false)); for (const auto& uuid : bounded_uuids.set()) { - BT_ASSERT_MSG(uuid.CompactSize() == uuid_width, - "UUID: %s - Expected Width: %d", - bt_str(uuid), - uuid_width); + PW_CHECK(uuid.CompactSize() == uuid_width, + "UUID: %s - Expected Width: %d", + bt_str(uuid), + uuid_width); auto target = buffer->mutable_view(pos); pos += uuid.ToBytes(&target); } @@ -808,7 +808,7 @@ bool AdvertisingData::operator!=(const AdvertisingData& other) const { } bool AdvertisingData::BoundedUuids::AddUuid(UUID uuid) { - BT_ASSERT(set_.size() <= bound_); + PW_CHECK(set_.size() <= bound_); if (set_.size() < bound_) { if (!set_.insert(uuid).second) { bt_log(INFO, diff --git a/pw_bluetooth_sapphire/host/common/byte_buffer.cc b/pw_bluetooth_sapphire/host/common/byte_buffer.cc index 1ec6d307ab..1031ef083f 100644 --- a/pw_bluetooth_sapphire/host/common/byte_buffer.cc +++ b/pw_bluetooth_sapphire/host/common/byte_buffer.cc @@ -22,19 +22,19 @@ namespace bt { void ByteBuffer::Copy(MutableByteBuffer* out_buffer) const { - BT_ASSERT(out_buffer); + PW_CHECK(out_buffer); CopyRaw(out_buffer->mutable_data(), out_buffer->size(), 0, size()); } void ByteBuffer::Copy(MutableByteBuffer* out_buffer, size_t pos, size_t size) const { - BT_ASSERT(out_buffer); + PW_CHECK(out_buffer); CopyRaw(out_buffer->mutable_data(), out_buffer->size(), pos, size); } std::string ByteBuffer::Printable(size_t pos, size_t size) const { - BT_ASSERT(pos + size <= this->size()); + PW_CHECK(pos + size <= this->size()); const char* region_start = reinterpret_cast(data() + pos); std::string_view view(region_start, size); @@ -57,18 +57,18 @@ std::string ByteBuffer::Printable(size_t pos, size_t size) const { } BufferView ByteBuffer::view(size_t pos, size_t size) const { - BT_ASSERT_MSG(pos <= this->size(), - "offset past buffer (pos: %zu, size: %zu)", - pos, - this->size()); + PW_CHECK(pos <= this->size(), + "offset past buffer (pos: %zu, size: %zu)", + pos, + this->size()); return BufferView(data() + pos, std::min(size, this->size() - pos)); } pw::span ByteBuffer::subspan(size_t pos, size_t size) const { - BT_ASSERT_MSG(pos <= this->size(), - "offset past buffer (pos: %zu, size: %zu)", - pos, - this->size()); + PW_CHECK(pos <= this->size(), + "offset past buffer (pos: %zu, size: %zu)", + pos, + this->size()); return pw::span(reinterpret_cast(data()) + pos, std::min(size, this->size() - pos)); } @@ -107,27 +107,27 @@ void ByteBuffer::CopyRaw(void* dst_data, size_t dst_capacity, size_t src_offset, size_t copy_size) const { - BT_ASSERT_MSG(copy_size == 0 || dst_data != nullptr, - "%zu byte write to pointer %p", - copy_size, - dst_data); - BT_ASSERT_MSG(copy_size <= dst_capacity, - "destination not large enough (required: %zu, available: %zu)", - copy_size, - dst_capacity); - BT_ASSERT_MSG(src_offset <= this->size(), - "offset exceeds source range (begin: %zu, copy_size: %zu)", - src_offset, - this->size()); - BT_ASSERT_MSG( + PW_CHECK(copy_size == 0 || dst_data != nullptr, + "%zu byte write to pointer %p", + copy_size, + dst_data); + PW_CHECK(copy_size <= dst_capacity, + "destination not large enough (required: %zu, available: %zu)", + copy_size, + dst_capacity); + PW_CHECK(src_offset <= this->size(), + "offset exceeds source range (begin: %zu, copy_size: %zu)", + src_offset, + this->size()); + PW_CHECK( std::numeric_limits::max() - copy_size >= src_offset, "end of source range overflows size_t (src_offset: %zu, copy_size: %zu)", src_offset, copy_size); - BT_ASSERT_MSG(src_offset + copy_size <= this->size(), - "end exceeds source range (end: %zu, copy_size: %zu)", - src_offset + copy_size, - this->size()); + PW_CHECK(src_offset + copy_size <= this->size(), + "end exceeds source range (end: %zu, copy_size: %zu)", + src_offset + copy_size, + this->size()); // Data pointers for zero-length buffers are nullptr, over which memcpy has // undefined behavior, even for count = 0. Skip the memcpy invocation in that @@ -145,20 +145,20 @@ void MutableByteBuffer::Write(const uint8_t* data, size_t size, size_t pos) { } MutableBufferView MutableByteBuffer::mutable_view(size_t pos, size_t size) { - BT_ASSERT_MSG(pos <= this->size(), - "offset past buffer (pos: %zu, size: %zu)", - pos, - this->size()); + PW_CHECK(pos <= this->size(), + "offset past buffer (pos: %zu, size: %zu)", + pos, + this->size()); return MutableBufferView(mutable_data() + pos, std::min(size, this->size() - pos)); } pw::span MutableByteBuffer::mutable_subspan(size_t pos, size_t size) { - BT_ASSERT_MSG(pos <= this->size(), - "offset past buffer (pos: %zu, size: %zu)", - pos, - this->size()); + PW_CHECK(pos <= this->size(), + "offset past buffer (pos: %zu, size: %zu)", + pos, + this->size()); return pw::span(reinterpret_cast(mutable_data()) + pos, std::min(size, this->size() - pos)); } @@ -176,15 +176,15 @@ DynamicByteBuffer::DynamicByteBuffer(size_t buffer_size) // TODO(armansito): For now this is dumb but we should properly handle the // case when we're out of memory. - BT_ASSERT_MSG(buffer_.get(), "failed to allocate buffer"); + PW_CHECK(buffer_.get(), "failed to allocate buffer"); } DynamicByteBuffer::DynamicByteBuffer(const ByteBuffer& buffer) : buffer_size_(buffer.size()), buffer_(buffer.size() ? std::make_unique(buffer.size()) : nullptr) { - BT_ASSERT_MSG(!buffer_size_ || buffer_.get(), - "|buffer| cannot be nullptr when |buffer_size| is non-zero"); + PW_CHECK(!buffer_size_ || buffer_.get(), + "|buffer| cannot be nullptr when |buffer_size| is non-zero"); buffer.Copy(this); } @@ -200,8 +200,8 @@ DynamicByteBuffer::DynamicByteBuffer(const std::string& buffer) { DynamicByteBuffer::DynamicByteBuffer(size_t buffer_size, std::unique_ptr buffer) : buffer_size_(buffer_size), buffer_(std::move(buffer)) { - BT_ASSERT_MSG(!buffer_size_ || buffer_.get(), - "|buffer| cannot be nullptr when |buffer_size| is non-zero"); + PW_CHECK(!buffer_size_ || buffer_.get(), + "|buffer| cannot be nullptr when |buffer_size| is non-zero"); } DynamicByteBuffer::DynamicByteBuffer(DynamicByteBuffer&& other) { @@ -273,7 +273,7 @@ BufferView::BufferView(pw::span bytes) BufferView::BufferView(const void* bytes, size_t size) : size_(size), bytes_(static_cast(bytes)) { // If |size| non-zero then |bytes| cannot be nullptr. - BT_ASSERT_MSG(!size_ || bytes_, "|bytes_| cannot be nullptr if |size_| > 0"); + PW_CHECK(!size_ || bytes_, "|bytes_| cannot be nullptr if |size_| > 0"); } BufferView::BufferView() = default; @@ -287,7 +287,7 @@ ByteBuffer::const_iterator BufferView::cbegin() const { return bytes_; } ByteBuffer::const_iterator BufferView::cend() const { return bytes_ + size_; } MutableBufferView::MutableBufferView(MutableByteBuffer* buffer) { - BT_ASSERT(buffer); + PW_CHECK(buffer); size_ = buffer->size(); bytes_ = buffer->mutable_data(); } @@ -295,7 +295,7 @@ MutableBufferView::MutableBufferView(MutableByteBuffer* buffer) { MutableBufferView::MutableBufferView(void* bytes, size_t size) : size_(size), bytes_(static_cast(bytes)) { // If |size| non-zero then |bytes| cannot be nullptr. - BT_ASSERT_MSG(!size_ || bytes_, "|bytes_| cannot be nullptr if |size_| > 0"); + PW_CHECK(!size_ || bytes_, "|bytes_| cannot be nullptr if |size_| > 0"); } MutableBufferView::MutableBufferView() = default; diff --git a/pw_bluetooth_sapphire/host/common/device_address.cc b/pw_bluetooth_sapphire/host/common/device_address.cc index df405d4690..78b266801b 100644 --- a/pw_bluetooth_sapphire/host/common/device_address.cc +++ b/pw_bluetooth_sapphire/host/common/device_address.cc @@ -46,7 +46,7 @@ DeviceAddressBytes::DeviceAddressBytes( } DeviceAddressBytes::DeviceAddressBytes(const ByteBuffer& bytes) { - BT_DEBUG_ASSERT(bytes.size() == bytes_.size()); + PW_DCHECK(bytes.size() == bytes_.size()); std::copy(bytes.cbegin(), bytes.cend(), bytes_.begin()); } @@ -67,7 +67,7 @@ std::string DeviceAddressBytes::ToString() const { bytes_[2], bytes_[1], bytes_[0]); - BT_DEBUG_ASSERT(result.ok()); + PW_DCHECK(result.ok()); return out; } diff --git a/pw_bluetooth_sapphire/host/common/device_class.cc b/pw_bluetooth_sapphire/host/common/device_class.cc index 9bed3e34cb..644947d1f3 100644 --- a/pw_bluetooth_sapphire/host/common/device_class.cc +++ b/pw_bluetooth_sapphire/host/common/device_class.cc @@ -24,8 +24,8 @@ namespace bt { namespace { DeviceClass::ServiceClass bit_no_to_service_class(uint8_t bit_no) { - BT_DEBUG_ASSERT(bit_no >= 13); - BT_DEBUG_ASSERT(bit_no < 24); + PW_DCHECK(bit_no >= 13); + PW_DCHECK(bit_no < 24); switch (bit_no) { case 13: return DeviceClass::ServiceClass::kLimitedDiscoverableMode; @@ -89,12 +89,12 @@ DeviceClass::DeviceClass(MajorClass major_class) : bytes_{0x00, static_cast(major_class), 0x00} {} DeviceClass::DeviceClass(std::initializer_list bytes) { - BT_DEBUG_ASSERT(bytes.size() == bytes_.size()); + PW_DCHECK(bytes.size() == bytes_.size()); std::copy(bytes.begin(), bytes.end(), bytes_.begin()); } DeviceClass::DeviceClass(uint32_t value) { - BT_DEBUG_ASSERT(value < 1 << 24); // field should only populate 24 bits + PW_DCHECK(value < 1 << 24); // field should only populate 24 bits bytes_ = { static_cast((value >> 0) & 0xFF), static_cast((value >> 8) & 0xFF), diff --git a/pw_bluetooth_sapphire/host/common/error_test.cc b/pw_bluetooth_sapphire/host/common/error_test.cc index cd6b29dce8..0ce2a9ec33 100644 --- a/pw_bluetooth_sapphire/host/common/error_test.cc +++ b/pw_bluetooth_sapphire/host/common/error_test.cc @@ -186,13 +186,13 @@ TEST(ErrorTest, ResultFromNonSuccessProtocolErrorThatOnlyHoldsErrors) { TEST(ErrorDeathTest, ReadingHostErrorThatIsNotPresentIsFatal) { const Error error = MakeError(TestError::kFail1); ASSERT_DEATH_IF_SUPPORTED([[maybe_unused]] auto _ = error.host_error(), - "HostError"); + "host_error"); } TEST(ErrorDeathTest, ReadingProtocolErrorThatIsNotPresentIsFatal) { const Error error(HostError::kFailed); ASSERT_DEATH_IF_SUPPORTED([[maybe_unused]] auto _ = error.protocol_error(), - "protocol error"); + "protocol_error"); } TEST(ErrorTest, ResultIsAnyOf) { diff --git a/pw_bluetooth_sapphire/host/common/random.cc b/pw_bluetooth_sapphire/host/common/random.cc index 85f15c6a94..d055f7cc75 100644 --- a/pw_bluetooth_sapphire/host/common/random.cc +++ b/pw_bluetooth_sapphire/host/common/random.cc @@ -24,7 +24,7 @@ pw::random::RandomGenerator* g_random_generator = nullptr; pw::random::RandomGenerator* random_generator() { return g_random_generator; } void set_random_generator(pw::random::RandomGenerator* generator) { - BT_ASSERT(!generator || !g_random_generator); + PW_CHECK(!generator || !g_random_generator); g_random_generator = generator; } diff --git a/pw_bluetooth_sapphire/host/common/retire_log.cc b/pw_bluetooth_sapphire/host/common/retire_log.cc index dbd5530b48..f880c9f368 100644 --- a/pw_bluetooth_sapphire/host/common/retire_log.cc +++ b/pw_bluetooth_sapphire/host/common/retire_log.cc @@ -20,13 +20,13 @@ namespace bt::internal { RetireLog::RetireLog(size_t min_depth, size_t max_depth) : min_depth_(min_depth), max_depth_(max_depth) { - BT_ASSERT(min_depth_ > 0); - BT_ASSERT(min_depth_ <= max_depth_); + PW_CHECK(min_depth_ > 0); + PW_CHECK(min_depth_ <= max_depth_); // For simplicity, log indexes are computed with doubles, so limit the depth // to 2**53 in which precision is preserved, assuming IEEE-754 DPFPs. - BT_ASSERT(max_depth_ <= - (decltype(max_depth_){1} << std::numeric_limits::digits)); + PW_CHECK(max_depth_ <= + (decltype(max_depth_){1} << std::numeric_limits::digits)); buffer_.reserve(max_depth_); std::apply( [this](auto&... scratchpad) { (scratchpad.reserve(max_depth_), ...); }, diff --git a/pw_bluetooth_sapphire/host/common/supplement_data.cc b/pw_bluetooth_sapphire/host/common/supplement_data.cc index 1460e9af1b..4245db74f1 100644 --- a/pw_bluetooth_sapphire/host/common/supplement_data.cc +++ b/pw_bluetooth_sapphire/host/common/supplement_data.cc @@ -25,7 +25,7 @@ namespace bt { bool ParseUuids(const BufferView& data, UUIDElemSize uuid_size, UuidFunction func) { - BT_ASSERT(func); + PW_CHECK(func); if (data.size() % uuid_size) { return false; @@ -98,15 +98,15 @@ SupplementDataReader::SupplementDataReader(const ByteBuffer& data) bool SupplementDataReader::GetNextField(DataType* out_type, BufferView* out_data) { - BT_DEBUG_ASSERT(out_type); - BT_DEBUG_ASSERT(out_data); + PW_DCHECK(out_type); + PW_DCHECK(out_data); if (!HasMoreData()) return false; size_t tlv_len = remaining_[0]; size_t cur_struct_size = tlv_len + 1; - BT_DEBUG_ASSERT(cur_struct_size <= remaining_.size()); + PW_DCHECK(cur_struct_size <= remaining_.size()); *out_type = static_cast(remaining_[1]); *out_data = remaining_.view(2, tlv_len - 1); @@ -127,7 +127,7 @@ bool SupplementDataReader::HasMoreData() const { SupplementDataWriter::SupplementDataWriter(MutableByteBuffer* buffer) : buffer_(buffer), bytes_written_(0u) { - BT_DEBUG_ASSERT(buffer_); + PW_DCHECK(buffer_); } bool SupplementDataWriter::WriteField(DataType type, const ByteBuffer& data) { diff --git a/pw_bluetooth_sapphire/host/common/uuid.cc b/pw_bluetooth_sapphire/host/common/uuid.cc index c7bc30905c..0404d8403a 100644 --- a/pw_bluetooth_sapphire/host/common/uuid.cc +++ b/pw_bluetooth_sapphire/host/common/uuid.cc @@ -63,7 +63,7 @@ UUID UUID::Generate() { UUID::UUID(const ByteBuffer& bytes) { bool result = FromBytes(bytes, this); - BT_ASSERT_MSG(result, "|bytes| must contain a 16, 32, or 128-bit UUID"); + PW_CHECK(result, "|bytes| must contain a 16, 32, or 128-bit UUID"); } bool UUID::operator==(const UUID& uuid) const { return value_ == uuid.value_; } @@ -117,7 +117,7 @@ std::string UUID::ToString() const { value_[2], value_[1], value_[0]); - BT_DEBUG_ASSERT(result.ok()); + PW_DCHECK(result.ok()); return out; } @@ -174,7 +174,7 @@ std::optional UUID::As16Bit() const { } uint16_t UUID::ValueAs16Bit() const { - BT_DEBUG_ASSERT(type_ == Type::k16Bit); + PW_DCHECK(type_ == Type::k16Bit); return pw::bytes::ConvertOrderFrom( cpp20::endian::little, @@ -182,7 +182,7 @@ uint16_t UUID::ValueAs16Bit() const { } uint32_t UUID::ValueAs32Bit() const { - BT_DEBUG_ASSERT(type_ != Type::k128Bit); + PW_DCHECK(type_ != Type::k128Bit); return pw::bytes::ConvertOrderFrom( cpp20::endian::little, diff --git a/pw_bluetooth_sapphire/host/common/uuid_string_util.cc b/pw_bluetooth_sapphire/host/common/uuid_string_util.cc index a5db1728a7..5e5f0d1c0a 100644 --- a/pw_bluetooth_sapphire/host/common/uuid_string_util.cc +++ b/pw_bluetooth_sapphire/host/common/uuid_string_util.cc @@ -44,7 +44,7 @@ constexpr char kScanUuidFormatString[] = // place, I've decided that it sucks. I'm explicitly naming this using the // "Uuid" style as a reminder to fix style elsewhere. bool ParseUuidString(const std::string& uuid_string, UInt128* out_bytes) { - BT_DEBUG_ASSERT(out_bytes); + PW_DCHECK(out_bytes); if (uuid_string.length() == 4) { // Possibly a 16-bit short UUID, parse it in context of the Base UUID. @@ -87,7 +87,7 @@ bool IsStringValidUuid(const std::string& uuid_string) { } bool StringToUuid(const std::string& uuid_string, UUID* out_uuid) { - BT_DEBUG_ASSERT(out_uuid); + PW_DCHECK(out_uuid); UInt128 bytes; if (!ParseUuidString(uuid_string, &bytes)) { diff --git a/pw_bluetooth_sapphire/host/common/weak_self_test.cc b/pw_bluetooth_sapphire/host/common/weak_self_test.cc index e15a440f59..02d81c9611 100644 --- a/pw_bluetooth_sapphire/host/common/weak_self_test.cc +++ b/pw_bluetooth_sapphire/host/common/weak_self_test.cc @@ -242,9 +242,9 @@ class CountingWeakManager { std::optional> GetWeakRef() { // Make sure the weak ref doesn't accidentally get cleared after it's set. if (count_get_weak_ref_ == 0) { - BT_ASSERT(!manager_.HasWeakRef()); + PW_CHECK(!manager_.HasWeakRef()); } else { - BT_ASSERT(manager_.HasWeakRef()); + PW_CHECK(manager_.HasWeakRef()); } count_get_weak_ref_++; return manager_.GetWeakRef(); diff --git a/pw_bluetooth_sapphire/host/gap/adapter.cc b/pw_bluetooth_sapphire/host/gap/adapter.cc index 7ac1684cee..8ed40580b4 100644 --- a/pw_bluetooth_sapphire/host/gap/adapter.cc +++ b/pw_bluetooth_sapphire/host/gap/adapter.cc @@ -143,7 +143,7 @@ class AdapterImpl final : public Adapter { LowEnergyAdvertisingManager::ConnectionCallback advertisement_connect_cb = nullptr; if (connectable) { - BT_ASSERT(connectable->connection_cb); + PW_CHECK(connectable->connection_cb); // All advertisement connections are first registered with // LowEnergyConnectionManager before being reported to higher layers. @@ -621,8 +621,8 @@ AdapterImpl::AdapterImpl(pw::async::Dispatcher& pw_dispatcher, dispatcher_(pw_dispatcher), weak_self_(this), weak_self_adapter_(this) { - BT_DEBUG_ASSERT(hci_.is_alive()); - BT_DEBUG_ASSERT(gatt_.is_alive()); + PW_DCHECK(hci_.is_alive()); + PW_DCHECK(gatt_.is_alive()); auto self = weak_self_.GetWeakPtr(); hci_->SetTransportErrorCallback([self] { @@ -679,16 +679,16 @@ AdapterImpl::~AdapterImpl() { bool AdapterImpl::Initialize(InitializeCallback callback, fit::closure transport_error_cb) { - BT_DEBUG_ASSERT(callback); - BT_DEBUG_ASSERT(transport_error_cb); + PW_DCHECK(callback); + PW_DCHECK(transport_error_cb); if (IsInitialized()) { bt_log(WARN, "gap", "Adapter already initialized"); return false; } - BT_DEBUG_ASSERT(!IsInitializing()); - BT_DEBUG_ASSERT(!init_seq_runner_); + PW_DCHECK(!IsInitializing()); + PW_DCHECK(!init_seq_runner_); init_state_ = State::kInitializing; init_cb_ = std::move(callback); @@ -713,7 +713,7 @@ void AdapterImpl::ShutDown() { bt_log(DEBUG, "gap", "adapter shutting down"); if (IsInitializing()) { - BT_DEBUG_ASSERT(!init_seq_runner_->IsReady()); + PW_DCHECK(!init_seq_runner_->IsReady()); init_seq_runner_->Cancel(); } @@ -1055,7 +1055,7 @@ void AdapterImpl::InitializeStep1() { } void AdapterImpl::InitializeStep2() { - BT_DEBUG_ASSERT(IsInitializing()); + PW_DCHECK(IsInitializing()); // Low Energy MUST be supported. We don't support BR/EDR-only controllers. if (!state_.IsLowEnergySupported()) { @@ -1074,7 +1074,7 @@ void AdapterImpl::InitializeStep2() { hci_spec::HCIVersionToString(state_.hci_version).c_str()); } - BT_DEBUG_ASSERT(init_seq_runner_->IsReady()); + PW_DCHECK(init_seq_runner_->IsReady()); // If the controller supports the Read Buffer Size command then send it. // Otherwise we'll default to 0 when initializing the ACLDataChannel. @@ -1322,9 +1322,9 @@ void AdapterImpl::InitializeStep2() { } void AdapterImpl::InitializeStep3() { - BT_ASSERT(IsInitializing()); - BT_ASSERT(init_seq_runner_->IsReady()); - BT_ASSERT(!init_seq_runner_->HasQueuedCommands()); + PW_CHECK(IsInitializing()); + PW_CHECK(init_seq_runner_->IsReady()); + PW_CHECK(!init_seq_runner_->HasQueuedCommands()); if (!state_.bredr_data_buffer_info.IsAvailable() && !state_.low_energy_state.acl_data_buffer_info().IsAvailable()) { @@ -1501,7 +1501,7 @@ void AdapterImpl::InitializeStep3() { void AdapterImpl::InitializeStep4() { // Initialize the scan manager and low energy adapters based on current // feature support - BT_DEBUG_ASSERT(IsInitializing()); + PW_DCHECK(IsInitializing()); // We use the public controller address as the local LE identity address. DeviceAddress adapter_identity(DeviceAddress::Type::kLEPublic, @@ -1638,8 +1638,8 @@ bool AdapterImpl::CompleteInitialization(bool success) { } void AdapterImpl::InitQueueReadLMPFeatureMaskPage(uint8_t page) { - BT_DEBUG_ASSERT(init_seq_runner_); - BT_DEBUG_ASSERT(init_seq_runner_->IsReady()); + PW_DCHECK(init_seq_runner_); + PW_DCHECK(init_seq_runner_->IsReady()); if (max_lmp_feature_page_index_.has_value() && page > max_lmp_feature_page_index_.value()) { @@ -1781,9 +1781,9 @@ void AdapterImpl::OnTransportError() { } void AdapterImpl::OnLeAutoConnectRequest(Peer* peer) { - BT_DEBUG_ASSERT(le_connection_manager_); - BT_DEBUG_ASSERT(peer); - BT_DEBUG_ASSERT(peer->le()); + PW_DCHECK(le_connection_manager_); + PW_DCHECK(peer); + PW_DCHECK(peer->le()); PeerId peer_id = peer->identifier(); @@ -1817,7 +1817,7 @@ void AdapterImpl::OnLeAutoConnectRequest(Peer* peer) { } auto conn = std::move(result).value(); - BT_ASSERT(conn); + PW_CHECK(conn); bt_log(INFO, "gap", "peer auto-connected (peer: %s)", bt_str(peer_id)); if (self->auto_conn_cb_) { self->auto_conn_cb_(std::move(conn)); diff --git a/pw_bluetooth_sapphire/host/gap/bredr_connection.cc b/pw_bluetooth_sapphire/host/gap/bredr_connection.cc index 07528a770d..c6120f3643 100644 --- a/pw_bluetooth_sapphire/host/gap/bredr_connection.cc +++ b/pw_bluetooth_sapphire/host/gap/bredr_connection.cc @@ -92,9 +92,9 @@ void BrEdrConnection::Interrogate(BrEdrInterrogator::ResultCallback callback) { } void BrEdrConnection::OnInterrogationComplete() { - BT_ASSERT_MSG(!interrogation_complete(), - "%s on a connection that's already been interrogated", - __FUNCTION__); + PW_CHECK(!interrogation_complete(), + "%s on a connection that's already been interrogated", + __FUNCTION__); // Fulfill and clear request so that the dtor does not signal requester(s) // with errors. @@ -111,7 +111,7 @@ void BrEdrConnection::AddRequestCallback( return; } - BT_ASSERT(request_); + PW_CHECK(request_); request_->AddCallback(std::move(cb)); } @@ -119,7 +119,7 @@ void BrEdrConnection::CreateOrUpdatePairingState( PairingStateType type, const PairingDelegate::WeakPtr& pairing_delegate, BrEdrSecurityMode security_mode) { - BT_ASSERT(pairing_state_manager_); + PW_CHECK(pairing_state_manager_); pairing_state_manager_->CreateOrUpdatePairingState(type, pairing_delegate); set_security_mode(security_mode); } diff --git a/pw_bluetooth_sapphire/host/gap/bredr_connection_manager.cc b/pw_bluetooth_sapphire/host/gap/bredr_connection_manager.cc index f8846f7689..9d4550ce07 100644 --- a/pw_bluetooth_sapphire/host/gap/bredr_connection_manager.cc +++ b/pw_bluetooth_sapphire/host/gap/bredr_connection_manager.cc @@ -95,7 +95,7 @@ std::string ReasonAsString(DisconnectReason reason) { void SetPageScanEnabled(bool enabled, hci::Transport::WeakPtr hci, hci::ResultFunction<> cb) { - BT_DEBUG_ASSERT(cb); + PW_DCHECK(cb); auto read_enable = hci::EmbossCommandPacket::New< pw::bluetooth::emboss::ReadScanEnableCommandWriter>( hci_spec::kReadScanEnable); @@ -171,7 +171,7 @@ hci::CommandChannel::EventHandlerId BrEdrConnectionManager::AddEventHandler( } }, std::move(cb)); - BT_DEBUG_ASSERT(event_id); + PW_DCHECK(event_id); event_handler_ids_.push_back(event_id); return event_id; } @@ -197,9 +197,9 @@ BrEdrConnectionManager::BrEdrConnectionManager( legacy_pairing_enabled_(legacy_pairing_enabled), dispatcher_(dispatcher), weak_self_(this) { - BT_DEBUG_ASSERT(hci_.is_alive()); - BT_DEBUG_ASSERT(cache_); - BT_DEBUG_ASSERT(l2cap_); + PW_DCHECK(hci_.is_alive()); + PW_DCHECK(cache_); + PW_DCHECK(l2cap_); hci_cmd_runner_ = std::make_unique( hci_->command_channel()->AsWeakPtr()); @@ -334,7 +334,7 @@ PeerId BrEdrConnectionManager::GetPeerId( } auto* peer = cache_->FindByAddress(it->second.link().peer_address()); - BT_DEBUG_ASSERT_MSG(peer, "Couldn't find peer for handle %#.4x", handle); + PW_DCHECK(peer, "Couldn't find peer for handle %#.4x", handle); return peer->identifier(); } @@ -412,7 +412,7 @@ BrEdrConnectionManager::SearchId BrEdrConnectionManager::AddServiceSearch( PeerId peer_id, auto& service_attributes) { if (self.is_alive()) { Peer* const peer = self->cache_->FindById(peer_id); - BT_ASSERT(peer); + PW_CHECK(peer); peer->MutBrEdr().AddService(uuid); } client_cb(peer_id, service_attributes); @@ -629,15 +629,15 @@ void BrEdrConnectionManager::AttachInspect(inspect::Node& parent, void BrEdrConnectionManager::WritePageTimeout( pw::chrono::SystemClock::duration page_timeout, hci::ResultFunction<> cb) { - BT_ASSERT(page_timeout >= hci_spec::kMinPageTimeoutDuration); - BT_ASSERT(page_timeout <= hci_spec::kMaxPageTimeoutDuration); + PW_CHECK(page_timeout >= hci_spec::kMinPageTimeoutDuration); + PW_CHECK(page_timeout <= hci_spec::kMaxPageTimeoutDuration); const int64_t raw_page_timeout = page_timeout / hci_spec::kDurationPerPageTimeoutUnit; - BT_ASSERT(raw_page_timeout >= - static_cast(pw::bluetooth::emboss::PageTimeout::MIN)); - BT_ASSERT(raw_page_timeout <= - static_cast(pw::bluetooth::emboss::PageTimeout::MAX)); + PW_CHECK(raw_page_timeout >= + static_cast(pw::bluetooth::emboss::PageTimeout::MIN)); + PW_CHECK(raw_page_timeout <= + static_cast(pw::bluetooth::emboss::PageTimeout::MAX)); auto write_page_timeout_cmd = hci::EmbossCommandPacket::New< pw::bluetooth::emboss::WritePageTimeoutCommandWriter>( @@ -790,7 +790,7 @@ void BrEdrConnectionManager::InitializeConnection( bt_str(peer_id)); // We should never have more than one link to a given peer - BT_DEBUG_ASSERT(!FindConnectionById(peer_id)); + PW_DCHECK(!FindConnectionById(peer_id)); // The controller has completed the HCI connection procedure, so the // connection request can no longer be failed by a lower layer error. Now tie @@ -832,7 +832,7 @@ void BrEdrConnectionManager::InitializeConnection( hci_, std::move(request), dispatcher_); - BT_ASSERT(success); + PW_CHECK(success); BrEdrConnection& connection = conn_iter->second; connection.AttachInspect(inspect_properties_.connections_node_, @@ -985,8 +985,7 @@ void BrEdrConnectionManager::CompleteConnectionSetup( hci::CommandChannel::EventCallbackResult BrEdrConnectionManager::OnAuthenticationComplete( const hci::EmbossEventPacket& event) { - BT_DEBUG_ASSERT(event.event_code() == - hci_spec::kAuthenticationCompleteEventCode); + PW_DCHECK(event.event_code() == hci_spec::kAuthenticationCompleteEventCode); auto params = event.view(); hci_spec::ConnectionHandle connection_handle = @@ -1515,7 +1514,7 @@ BrEdrConnectionManager::OnLinkKeyNotification( } // Reuse current properties - BT_DEBUG_ASSERT(peer->bredr()->link_key()); + PW_DCHECK(peer->bredr()->link_key()); sec_props = peer->bredr()->link_key()->security(); key_type = static_cast(sec_props.GetLinkKeyType()); @@ -1545,7 +1544,7 @@ BrEdrConnectionManager::OnLinkKeyNotification( } else { // The connection request's legacy pairing state object must exist at this // point since we created it in the request's constructor. - BT_ASSERT(request.value()->legacy_pairing_state()); + PW_CHECK(request.value()->legacy_pairing_state()); request.value()->legacy_pairing_state()->OnLinkKeyNotification( key_value, static_cast(key_type)); } @@ -1837,7 +1836,7 @@ BrEdrConnectionManager::OnPinCodeRequest(const hci::EmbossEventPacket& event) { void BrEdrConnectionManager::HandleNonAclConnectionRequest( const DeviceAddress& addr, pw::bluetooth::emboss::LinkType link_type) { - BT_DEBUG_ASSERT(link_type != pw::bluetooth::emboss::LinkType::ACL); + PW_DCHECK(link_type != pw::bluetooth::emboss::LinkType::ACL); // Initialize the peer if it doesn't exist, to ensure we have allocated a // PeerId diff --git a/pw_bluetooth_sapphire/host/gap/bredr_discovery_manager.cc b/pw_bluetooth_sapphire/host/gap/bredr_discovery_manager.cc index 6e9e59c0b2..f03658f20d 100644 --- a/pw_bluetooth_sapphire/host/gap/bredr_discovery_manager.cc +++ b/pw_bluetooth_sapphire/host/gap/bredr_discovery_manager.cc @@ -42,7 +42,7 @@ Peer* AddOrUpdateConnectablePeer(PeerCache* cache, const DeviceAddress& addr) { } else { peer->set_connectable(true); } - BT_ASSERT(peer); + PW_CHECK(peer); return peer; } @@ -104,21 +104,21 @@ BrEdrDiscoveryManager::BrEdrDiscoveryManager( desired_inquiry_mode_(mode), current_inquiry_mode_(pw::bluetooth::emboss::InquiryMode::STANDARD), weak_self_(this) { - BT_DEBUG_ASSERT(cache_); - BT_DEBUG_ASSERT(cmd_.is_alive()); + PW_DCHECK(cache_); + PW_DCHECK(cmd_.is_alive()); result_handler_id_ = cmd_->AddEventHandler( hci_spec::kInquiryResultEventCode, fit::bind_member<&BrEdrDiscoveryManager::InquiryResult>(this)); - BT_DEBUG_ASSERT(result_handler_id_); + PW_DCHECK(result_handler_id_); rssi_handler_id_ = cmd_->AddEventHandler( hci_spec::kInquiryResultWithRSSIEventCode, cpp20::bind_front(&BrEdrDiscoveryManager::InquiryResultWithRssi, this)); - BT_DEBUG_ASSERT(rssi_handler_id_); + PW_DCHECK(rssi_handler_id_); eir_handler_id_ = cmd_->AddEventHandler( hci_spec::kExtendedInquiryResultEventCode, cpp20::bind_front(&BrEdrDiscoveryManager::ExtendedInquiryResult, this)); - BT_DEBUG_ASSERT(eir_handler_id_); + PW_DCHECK(eir_handler_id_); // Set the Inquiry Scan Settings WriteInquiryScanSettings( @@ -133,7 +133,7 @@ BrEdrDiscoveryManager::~BrEdrDiscoveryManager() { } void BrEdrDiscoveryManager::RequestDiscovery(DiscoveryCallback callback) { - BT_DEBUG_ASSERT(callback); + PW_DCHECK(callback); bt_log(INFO, "gap-bredr", "RequestDiscovery"); @@ -224,8 +224,7 @@ void BrEdrDiscoveryManager::MaybeStartInquiry() { return; } - BT_DEBUG_ASSERT(event.event_code() == - hci_spec::kInquiryCompleteEventCode); + PW_DCHECK(event.event_code() == hci_spec::kInquiryCompleteEventCode); self->zombie_discovering_.clear(); if (bt_is_error(status, TRACE, "gap", "inquiry complete error")) { @@ -242,7 +241,7 @@ void BrEdrDiscoveryManager::MaybeStartInquiry() { // Stops the inquiry procedure. void BrEdrDiscoveryManager::StopInquiry() { - BT_DEBUG_ASSERT(result_handler_id_); + PW_DCHECK(result_handler_id_); bt_log(TRACE, "gap-bredr", "cancelling inquiry"); const hci::EmbossCommandPacket inq_cancel = hci::EmbossCommandPacket::New< @@ -257,7 +256,7 @@ void BrEdrDiscoveryManager::StopInquiry() { hci::CommandChannel::EventCallbackResult BrEdrDiscoveryManager::InquiryResult( const hci::EmbossEventPacket& event) { - BT_DEBUG_ASSERT(event.event_code() == hci_spec::kInquiryResultEventCode); + PW_DCHECK(event.event_code() == hci_spec::kInquiryResultEventCode); std::unordered_set peers; auto view = event.view(); @@ -466,8 +465,8 @@ void BrEdrDiscoveryManager::RequestPeerName(PeerId id) { pw::bluetooth::emboss::RemoteNameRequestCommandWriter>( hci_spec::kRemoteNameRequest); auto params = packet.view_t(); - BT_DEBUG_ASSERT(peer->bredr()); - BT_DEBUG_ASSERT(peer->bredr()->page_scan_repetition_mode()); + PW_DCHECK(peer->bredr()); + PW_DCHECK(peer->bredr()->page_scan_repetition_mode()); params.bd_addr().CopyFrom(peer->address().value().view()); params.page_scan_repetition_mode().Write( *(peer->bredr()->page_scan_repetition_mode())); @@ -491,8 +490,8 @@ void BrEdrDiscoveryManager::RequestPeerName(PeerId id) { return; } - BT_DEBUG_ASSERT(event.event_code() == - hci_spec::kRemoteNameRequestCompleteEventCode); + PW_DCHECK(event.event_code() == + hci_spec::kRemoteNameRequestCompleteEventCode); self->requesting_names_.erase(id); Peer* const cached_peer = self->cache_->FindById(id); @@ -522,7 +521,7 @@ void BrEdrDiscoveryManager::RequestPeerName(PeerId id) { } void BrEdrDiscoveryManager::RequestDiscoverable(DiscoverableCallback callback) { - BT_DEBUG_ASSERT(callback); + PW_DCHECK(callback); auto self = weak_self_.GetWeakPtr(); auto result_cb = [self, cb = callback.share()](const hci::Result<>& result) { @@ -684,7 +683,7 @@ BrEdrDiscoveryManager::AddDiscoverySession() { // constructor. std::unique_ptr session( new BrEdrDiscoverySession(weak_self_.GetWeakPtr())); - BT_DEBUG_ASSERT(discovering_.find(session.get()) == discovering_.end()); + PW_DCHECK(discovering_.find(session.get()) == discovering_.end()); discovering_.insert(session.get()); bt_log(INFO, "gap-bredr", @@ -715,7 +714,7 @@ BrEdrDiscoveryManager::AddDiscoverableSession() { // constructor. std::unique_ptr session( new BrEdrDiscoverableSession(weak_self_.GetWeakPtr())); - BT_DEBUG_ASSERT(discoverable_.find(session.get()) == discoverable_.end()); + PW_DCHECK(discoverable_.find(session.get()) == discoverable_.end()); discoverable_.insert(session.get()); bt_log(INFO, "gap-bredr", diff --git a/pw_bluetooth_sapphire/host/gap/bredr_interrogator.cc b/pw_bluetooth_sapphire/host/gap/bredr_interrogator.cc index b59f6efe9f..a3280ffa5c 100644 --- a/pw_bluetooth_sapphire/host/gap/bredr_interrogator.cc +++ b/pw_bluetooth_sapphire/host/gap/bredr_interrogator.cc @@ -31,7 +31,7 @@ BrEdrInterrogator::BrEdrInterrogator(Peer::WeakPtr peer, handle_(handle), cmd_runner_(std::move(cmd_channel)), weak_self_(this) { - BT_ASSERT(peer_.is_alive()); + PW_CHECK(peer_.is_alive()); } void BrEdrInterrogator::Start(ResultCallback callback) { @@ -251,8 +251,8 @@ void BrEdrInterrogator::QueueReadRemoteVersionInformation() { if (hci_is_error(event, WARN, "gap", "read remote version info failed")) { return; } - BT_DEBUG_ASSERT(event.event_code() == - hci_spec::kReadRemoteVersionInfoCompleteEventCode); + PW_DCHECK(event.event_code() == + hci_spec::kReadRemoteVersionInfoCompleteEventCode); bt_log(TRACE, "gap", "read remote version info completed (peer id: %s)", diff --git a/pw_bluetooth_sapphire/host/gap/discovery_filter.cc b/pw_bluetooth_sapphire/host/gap/discovery_filter.cc index 11d85c198b..168e87c50b 100644 --- a/pw_bluetooth_sapphire/host/gap/discovery_filter.cc +++ b/pw_bluetooth_sapphire/host/gap/discovery_filter.cc @@ -89,7 +89,7 @@ bool DiscoveryFilter::MatchLowEnergyResult( return rssi_ok; } - BT_DEBUG_ASSERT(advertising_data.has_value()); + PW_DCHECK(advertising_data.has_value()); const AdvertisingData& ad = advertising_data->get(); if (flags_) { diff --git a/pw_bluetooth_sapphire/host/gap/generic_access_client.cc b/pw_bluetooth_sapphire/host/gap/generic_access_client.cc index 9d2c8469dd..0657ebc80b 100644 --- a/pw_bluetooth_sapphire/host/gap/generic_access_client.cc +++ b/pw_bluetooth_sapphire/host/gap/generic_access_client.cc @@ -23,8 +23,8 @@ namespace bt::gap::internal { GenericAccessClient::GenericAccessClient(PeerId peer_id, gatt::RemoteService::WeakPtr service) : WeakSelf(this), service_(std::move(service)), peer_id_(peer_id) { - BT_ASSERT(service_.is_alive()); - BT_ASSERT(service_->uuid() == kGenericAccessService); + PW_CHECK(service_.is_alive()); + PW_CHECK(service_->uuid() == kGenericAccessService); } void GenericAccessClient::ReadDeviceName(DeviceNameCallback callback) { diff --git a/pw_bluetooth_sapphire/host/gap/legacy_pairing_state.cc b/pw_bluetooth_sapphire/host/gap/legacy_pairing_state.cc index e78f020737..3aba028ae9 100644 --- a/pw_bluetooth_sapphire/host/gap/legacy_pairing_state.cc +++ b/pw_bluetooth_sapphire/host/gap/legacy_pairing_state.cc @@ -65,7 +65,7 @@ LegacyPairingState::LegacyPairingState( std::move(peer), std::move(pairing_delegate), outgoing_connection) { // We can only populate |link_|, |send_auth_request_callback_|, and // |status_callback_| if the ACL connection is complete. - BT_ASSERT(link.is_alive()); + PW_CHECK(link.is_alive()); BuildEstablishedLink( std::move(link), std::move(auth_cb), std::move(status_cb)); @@ -113,7 +113,7 @@ void LegacyPairingState::InitiatePairing(StatusCallback status_cb) { return; } - BT_ASSERT(peer_.is_alive()); + PW_CHECK(peer_.is_alive()); // If we interrogated the peer and they support SSP, we should be using SSP // since we also support SSP. @@ -126,7 +126,7 @@ void LegacyPairingState::InitiatePairing(StatusCallback status_cb) { return; } - BT_ASSERT(pairing_delegate_.is_alive()); + PW_CHECK(pairing_delegate_.is_alive()); // Only initiate pairing if we have output capabilities to display a PIN pw::bluetooth::emboss::IoCapability io_capability = @@ -143,7 +143,7 @@ void LegacyPairingState::InitiatePairing(StatusCallback status_cb) { } if (state_ == State::kIdle) { - BT_ASSERT(!is_pairing()); + PW_CHECK(!is_pairing()); // TODO(fxbug.dev/348676274): Do not downgrade to LP if peer was // previously bonded with SSP @@ -176,7 +176,7 @@ void LegacyPairingState::InitiatePairing(StatusCallback status_cb) { // L2CAP channels), but each should wait for the results of any ongoing // pairing procedure before sending their own HCI_Authentication_Request. if (is_pairing()) { - BT_ASSERT(state_ != State::kIdle); + PW_CHECK(state_ != State::kIdle); bt_log(INFO, "gap-bredr", "Already pairing on link %#.4x for peer id %s; blocking callback on " @@ -190,7 +190,7 @@ void LegacyPairingState::InitiatePairing(StatusCallback status_cb) { } else { // In the error state, we should expect no pairing to be created and cancel // this particular request immediately. - BT_ASSERT(state_ == State::kFailed); + PW_CHECK(state_ == State::kFailed); status_cb(handle(), ToResult(HostError::kCanceled)); } } @@ -201,7 +201,7 @@ std::optional LegacyPairingState::OnLinkKeyRequest() { return std::nullopt; } - BT_ASSERT(peer_.is_alive()); + PW_CHECK(peer_.is_alive()); // If we interrogated the peer and they support SSP, we should be using SSP // since we also support SSP. @@ -232,10 +232,10 @@ std::optional LegacyPairingState::OnLinkKeyRequest() { "Recalling link key for bonded peer %s", bt_str(peer_id_)); - BT_ASSERT(peer_->bredr()->link_key().has_value()); + PW_CHECK(peer_->bredr()->link_key().has_value()); link_key = peer_->bredr()->link_key(); - BT_ASSERT(link_key->security().enc_key_size() == - hci_spec::kBrEdrLinkKeySize); + PW_CHECK(link_key->security().enc_key_size() == + hci_spec::kBrEdrLinkKeySize); if (link_.is_alive()) { const hci_spec::LinkKeyType link_key_type = @@ -254,7 +254,7 @@ std::optional LegacyPairingState::OnLinkKeyRequest() { // the peer initiates the authentication procedure and has a valid link key). if (state_ == State::kIdle) { if (link_key.has_value()) { - BT_ASSERT(!is_pairing()); + PW_CHECK(!is_pairing()); current_pairing_ = Pairing::MakeResponderForBonded(); state_ = State::kWaitEncryption; return link_key->key(); @@ -262,7 +262,7 @@ std::optional LegacyPairingState::OnLinkKeyRequest() { return std::nullopt; } - BT_ASSERT(is_pairing()); + PW_CHECK(is_pairing()); // TODO(fxbug.dev/348676274): Do not downgrade to LP if peer was // previously bonded with SSP @@ -273,7 +273,7 @@ std::optional LegacyPairingState::OnLinkKeyRequest() { SecurityPropertiesMeetRequirements( link_key->security(), current_pairing_->preferred_security)) { // Skip Legacy Pairing and just perform authentication with existing key - BT_ASSERT(current_pairing_->initiator); + PW_CHECK(current_pairing_->initiator); state_ = State::kInitiatorWaitAuthComplete; return link_key->key(); } @@ -291,11 +291,11 @@ void LegacyPairingState::OnPinCodeRequest(UserPinCodeCallback cb) { } if (state_ == State::kIdle) { - BT_ASSERT(!is_pairing()); + PW_CHECK(!is_pairing()); current_pairing_ = Pairing::MakeResponder(outgoing_connection_); } - BT_ASSERT(pairing_delegate_.is_alive()); + PW_CHECK(pairing_delegate_.is_alive()); // Get our I/O capabilities pw::bluetooth::emboss::IoCapability io_capability = @@ -307,10 +307,10 @@ void LegacyPairingState::OnPinCodeRequest(UserPinCodeCallback cb) { // Capability (Core Spec v5.4, Vol 3, Part C, 5.2.2.5, Table 5.5) so all PINs // will be randomly generated. if (initiator()) { - BT_ASSERT(io_capability != - pw::bluetooth::emboss::IoCapability::NO_INPUT_NO_OUTPUT); - BT_ASSERT(io_capability != - pw::bluetooth::emboss::IoCapability::KEYBOARD_ONLY); + PW_CHECK(io_capability != + pw::bluetooth::emboss::IoCapability::NO_INPUT_NO_OUTPUT); + PW_CHECK(io_capability != + pw::bluetooth::emboss::IoCapability::KEYBOARD_ONLY); // Randomly generate a 4-digit passkey uint16_t random_pin; @@ -378,7 +378,7 @@ void LegacyPairingState::OnLinkKeyNotification(const UInt128& link_key, return; } - BT_ASSERT(peer_.is_alive()); + PW_CHECK(peer_.is_alive()); // Legacy Pairing generates a Combination key type (Core Spec v5.4, Vol 4, // Part E, 7.7.24) @@ -397,7 +397,7 @@ void LegacyPairingState::OnLinkKeyNotification(const UInt128& link_key, // The resulting link security properties are computed by both the Link // Manager (Controller) and the Host subsystem, so check that they agree. - BT_ASSERT(is_pairing()); + PW_CHECK(is_pairing()); sm::SecurityProperties sec_props = sm::SecurityProperties(key_type); current_pairing_->security_properties = sec_props; @@ -405,7 +405,7 @@ void LegacyPairingState::OnLinkKeyNotification(const UInt128& link_key, bredr_security_ = sec_props; // Link keys resulting from legacy pairing are assigned lowest security level. - BT_ASSERT(sec_props.level() == sm::SecurityLevel::kNoSecurity); + PW_CHECK(sec_props.level() == sm::SecurityLevel::kNoSecurity); if (!link_.is_alive()) { // Connection is not complete yet so temporarily store this to later give @@ -441,7 +441,7 @@ void LegacyPairingState::OnLinkKeyNotification(const UInt128& link_key, void LegacyPairingState::OnAuthenticationComplete( pw::bluetooth::emboss::StatusCode status_code) { - BT_ASSERT(link_.is_alive()); + PW_CHECK(link_.is_alive()); if (is_pairing() && peer_->bredr() && peer_->bredr()->bonded() && status_code == pw::bluetooth::emboss::StatusCode::PIN_OR_KEY_MISSING) { @@ -482,14 +482,14 @@ void LegacyPairingState::OnAuthenticationComplete( } // HCI_Authentication_Complete events are only received by initiators - BT_ASSERT(initiator()); + PW_CHECK(initiator()); // After successful authentication, we can now enable encryption EnableEncryption(); } void LegacyPairingState::OnEncryptionChange(hci::Result result) { - BT_ASSERT(link_.is_alive()); + PW_CHECK(link_.is_alive()); if (state_ != State::kWaitEncryption) { // Ignore encryption changes when not expecting them because they may be @@ -571,7 +571,7 @@ LegacyPairingState::Pairing::MakeResponderForBonded() { } void LegacyPairingState::EnableEncryption() { - BT_ASSERT(link_.is_alive()); + PW_CHECK(link_.is_alive()); if (!link_->StartEncryption()) { bt_log( @@ -614,8 +614,8 @@ void LegacyPairingState::SignalStatus(hci::Result<> status, } void LegacyPairingState::InitiateNextPairingRequest() { - BT_ASSERT(state_ == State::kIdle); - BT_ASSERT(!is_pairing()); + PW_CHECK(state_ == State::kIdle); + PW_CHECK(!is_pairing()); if (!link_.is_alive()) { bt_log(WARN, @@ -626,7 +626,7 @@ void LegacyPairingState::InitiateNextPairingRequest() { return; } - BT_ASSERT(peer_.is_alive()); + PW_CHECK(peer_.is_alive()); // If we interrogated the peer and they support SSP, we should be using SSP // since we also support SSP. @@ -661,7 +661,7 @@ std::vector LegacyPairingState::CompletePairingRequests( std::vector callbacks_to_signal; if (!is_pairing()) { - BT_ASSERT(request_queue_.empty()); + PW_CHECK(request_queue_.empty()); return callbacks_to_signal; } @@ -678,7 +678,7 @@ std::vector LegacyPairingState::CompletePairingRequests( return callbacks_to_signal; } - BT_ASSERT(state_ == State::kIdle); + PW_CHECK(state_ == State::kIdle); sm::SecurityProperties security_properties = sm::SecurityProperties(hci_spec::LinkKeyType::kCombination); diff --git a/pw_bluetooth_sapphire/host/gap/low_energy_address_manager.cc b/pw_bluetooth_sapphire/host/gap/low_energy_address_manager.cc index 26e96c04f0..1286e08e6a 100644 --- a/pw_bluetooth_sapphire/host/gap/low_energy_address_manager.cc +++ b/pw_bluetooth_sapphire/host/gap/low_energy_address_manager.cc @@ -33,9 +33,9 @@ LowEnergyAddressManager::LowEnergyAddressManager( needs_refresh_(false), refreshing_(false), weak_self_(this) { - BT_DEBUG_ASSERT(public_.type() == DeviceAddress::Type::kLEPublic); - BT_DEBUG_ASSERT(delegate_); - BT_DEBUG_ASSERT(cmd_.is_alive()); + PW_DCHECK(public_.type() == DeviceAddress::Type::kLEPublic); + PW_DCHECK(delegate_); + PW_DCHECK(cmd_.is_alive()); } LowEnergyAddressManager::~LowEnergyAddressManager() { CancelExpiry(); } @@ -64,7 +64,7 @@ void LowEnergyAddressManager::EnablePrivacy(bool enabled) { } void LowEnergyAddressManager::EnsureLocalAddress(AddressCallback callback) { - BT_DEBUG_ASSERT(callback); + PW_DCHECK(callback); // Report the address right away if it doesn't need refreshing. if (!needs_refresh_) { @@ -165,7 +165,7 @@ void LowEnergyAddressManager::CancelExpiry() { } bool LowEnergyAddressManager::CanUpdateRandomAddress() const { - BT_DEBUG_ASSERT(delegate_); + PW_DCHECK(delegate_); return delegate_(); } diff --git a/pw_bluetooth_sapphire/host/gap/low_energy_advertising_manager.cc b/pw_bluetooth_sapphire/host/gap/low_energy_advertising_manager.cc index b6365b7a5f..a56379ed11 100644 --- a/pw_bluetooth_sapphire/host/gap/low_energy_advertising_manager.cc +++ b/pw_bluetooth_sapphire/host/gap/low_energy_advertising_manager.cc @@ -51,8 +51,8 @@ AdvertisementInstance::AdvertisementInstance() : id_(kInvalidAdvertisementId) {} AdvertisementInstance::AdvertisementInstance( AdvertisementId id, WeakSelf::WeakPtr owner) : id_(id), owner_(std::move(owner)) { - BT_DEBUG_ASSERT(id_ != kInvalidAdvertisementId); - BT_DEBUG_ASSERT(owner_.is_alive()); + PW_DCHECK(id_ != kInvalidAdvertisementId); + PW_DCHECK(owner_.is_alive()); } AdvertisementInstance::~AdvertisementInstance() { Reset(); } @@ -104,8 +104,8 @@ LowEnergyAdvertisingManager::LowEnergyAdvertisingManager( : advertiser_(advertiser), local_addr_delegate_(local_addr_delegate), weak_self_(this) { - BT_DEBUG_ASSERT(advertiser_); - BT_DEBUG_ASSERT(local_addr_delegate_); + PW_DCHECK(advertiser_); + PW_DCHECK(local_addr_delegate_); } LowEnergyAdvertisingManager::~LowEnergyAdvertisingManager() { diff --git a/pw_bluetooth_sapphire/host/gap/low_energy_advertising_manager_test.cc b/pw_bluetooth_sapphire/host/gap/low_energy_advertising_manager_test.cc index 376cb824b3..43fedebfed 100644 --- a/pw_bluetooth_sapphire/host/gap/low_energy_advertising_manager_test.cc +++ b/pw_bluetooth_sapphire/host/gap/low_energy_advertising_manager_test.cc @@ -66,7 +66,7 @@ class FakeLowEnergyAdvertiser final : public hci::LowEnergyAdvertiser { : hci::LowEnergyAdvertiser(hci, kDefaultMaxAdSize), ads_(ad_store), hci_(hci) { - BT_ASSERT(ads_); + PW_CHECK(ads_); } ~FakeLowEnergyAdvertiser() override = default; diff --git a/pw_bluetooth_sapphire/host/gap/low_energy_connection.cc b/pw_bluetooth_sapphire/host/gap/low_energy_connection.cc index f88a36999f..9d6997e3b6 100644 --- a/pw_bluetooth_sapphire/host/gap/low_energy_connection.cc +++ b/pw_bluetooth_sapphire/host/gap/low_energy_connection.cc @@ -111,15 +111,15 @@ LowEnergyConnection::LowEnergyConnection( refs_(/*convert=*/[](const auto& refs) { return refs.size(); }), weak_self_(this), weak_delegate_(this) { - BT_ASSERT(peer_.is_alive()); - BT_ASSERT(link_); - BT_ASSERT(conn_mgr_.is_alive()); - BT_ASSERT(gatt_.is_alive()); - BT_ASSERT(hci_.is_alive()); - BT_ASSERT(peer_disconnect_callback_); - BT_ASSERT(error_callback_); + PW_CHECK(peer_.is_alive()); + PW_CHECK(link_); + PW_CHECK(conn_mgr_.is_alive()); + PW_CHECK(gatt_.is_alive()); + PW_CHECK(hci_.is_alive()); + PW_CHECK(peer_disconnect_callback_); + PW_CHECK(error_callback_); cmd_ = hci_->command_channel()->AsWeakPtr(); - BT_ASSERT(cmd_.is_alive()); + PW_CHECK(cmd_.is_alive()); link_->set_peer_disconnect_callback( [this](const auto&, auto reason) { peer_disconnect_callback_(reason); }); @@ -151,19 +151,19 @@ LowEnergyConnection::AddRef() { }; auto accept_cis_cb = [self](iso::CigCisIdentifier id, iso::CisEstablishedCallback cb) { - BT_ASSERT(self.is_alive()); + PW_CHECK(self.is_alive()); return self->AcceptCis(id, std::move(cb)); }; auto bondable_cb = [self] { - BT_ASSERT(self.is_alive()); + PW_CHECK(self.is_alive()); return self->bondable_mode(); }; auto security_cb = [self] { - BT_ASSERT(self.is_alive()); + PW_CHECK(self.is_alive()); return self->security(); }; auto role_cb = [self] { - BT_ASSERT(self.is_alive()); + PW_CHECK(self.is_alive()); return self->role(); }; std::unique_ptr conn_ref( @@ -174,7 +174,7 @@ LowEnergyConnection::AddRef() { std::move(bondable_cb), std::move(security_cb), std::move(role_cb))); - BT_ASSERT(conn_ref); + PW_CHECK(conn_ref); refs_.Mutable()->insert(conn_ref.get()); @@ -189,10 +189,10 @@ LowEnergyConnection::AddRef() { } void LowEnergyConnection::DropRef(LowEnergyConnectionHandle* ref) { - BT_DEBUG_ASSERT(ref); + PW_DCHECK(ref); size_t res = refs_.Mutable()->erase(ref); - BT_ASSERT_MSG(res == 1u, "DropRef called with wrong connection reference"); + PW_CHECK(res == 1u, "DropRef called with wrong connection reference"); bt_log(DEBUG, "gap-le", "dropped ref (peer: %s, handle: %#.4x, count: %lu)", @@ -229,7 +229,7 @@ void LowEnergyConnection::DropRef(LowEnergyConnectionHandle* ref) { sm::LevelToString(level), bt_str(self->peer_id()), handle); - BT_ASSERT(self->handle() == handle); + PW_CHECK(self->handle() == handle); self->OnSecurityRequest(level, std::move(cb)); }; l2cap::ChannelManager::LEFixedChannels fixed_channels = @@ -247,7 +247,7 @@ void LowEnergyConnection::DropRef(LowEnergyConnectionHandle* ref) { // Used to respond to protocol/service requests for increased security. void LowEnergyConnection::OnSecurityRequest(sm::SecurityLevel level, sm::ResultFunction<> cb) { - BT_ASSERT(sm_); + PW_CHECK(sm_); sm_->UpgradeSecurity( level, [callback = std::move(cb), peer_id = peer_id(), handle = handle()]( @@ -270,23 +270,23 @@ void LowEnergyConnection::OnSecurityRequest(sm::SecurityLevel level, void LowEnergyConnection::UpgradeSecurity(sm::SecurityLevel level, sm::BondableMode bondable_mode, sm::ResultFunction<> cb) { - BT_ASSERT(sm_); + PW_CHECK(sm_); sm_->set_bondable_mode(bondable_mode); OnSecurityRequest(level, std::move(cb)); } void LowEnergyConnection::set_security_mode(LESecurityMode mode) { - BT_ASSERT(sm_); + PW_CHECK(sm_); sm_->set_security_mode(mode); } sm::BondableMode LowEnergyConnection::bondable_mode() const { - BT_ASSERT(sm_); + PW_CHECK(sm_); return sm_->bondable_mode(); } sm::SecurityProperties LowEnergyConnection::security() const { - BT_ASSERT(sm_); + PW_CHECK(sm_); return sm_->security(); } @@ -297,7 +297,7 @@ void LowEnergyConnection::ResetSecurityManager(sm::IOCapability ioc) { } void LowEnergyConnection::OnInterrogationComplete() { - BT_ASSERT(!interrogation_completed_); + PW_CHECK(!interrogation_completed_); interrogation_completed_ = true; MaybeUpdateConnectionParameters(); } @@ -360,7 +360,7 @@ void LowEnergyConnection::RegisterEventHandlers() { // TODO(fxbug.dev/42159733): Wait to update connection parameters until all // initialization procedures have completed. void LowEnergyConnection::StartConnectionPausePeripheralTimeout() { - BT_ASSERT(!conn_pause_peripheral_timeout_.has_value()); + PW_CHECK(!conn_pause_peripheral_timeout_.has_value()); conn_pause_peripheral_timeout_.emplace( dispatcher_, [this](pw::async::Context /*ctx*/, pw::Status status) { if (!status.ok()) { @@ -381,7 +381,7 @@ void LowEnergyConnection::StartConnectionPausePeripheralTimeout() { // TODO(fxbug.dev/42159733): Wait to update connection parameters until all // initialization procedures have completed. void LowEnergyConnection::StartConnectionPauseCentralTimeout() { - BT_ASSERT(!conn_pause_central_timeout_.has_value()); + PW_CHECK(!conn_pause_central_timeout_.has_value()); conn_pause_central_timeout_.emplace( dispatcher_, [this](pw::async::Context /*ctx*/, pw::Status status) { if (!status.ok()) { @@ -457,7 +457,7 @@ void LowEnergyConnection::OnNewLEConnectionParams( bt_str(peer_id()), link_->handle()); - BT_ASSERT(peer_.is_alive()); + PW_CHECK(peer_.is_alive()); peer_->MutLe().SetPreferredConnectionParameters(params); @@ -466,13 +466,12 @@ void LowEnergyConnection::OnNewLEConnectionParams( void LowEnergyConnection::RequestConnectionParameterUpdate( const hci_spec::LEPreferredConnectionParameters& params) { - BT_ASSERT_MSG( - link_->role() == pw::bluetooth::emboss::ConnectionRole::PERIPHERAL, - "tried to send connection parameter update request as central"); + PW_CHECK(link_->role() == pw::bluetooth::emboss::ConnectionRole::PERIPHERAL, + "tried to send connection parameter update request as central"); - BT_ASSERT(peer_.is_alive()); + PW_CHECK(peer_.is_alive()); // Ensure interrogation has completed. - BT_ASSERT(peer_->le()->feature_interrogation_complete()); + PW_CHECK(peer_->le()->feature_interrogation_complete()); // TODO(fxbug.dev/42126713): check local controller support for LL Connection // Parameters Request procedure (mask is currently in Adapter le state, @@ -546,7 +545,7 @@ void LowEnergyConnection::HandleRequestConnectionParameterUpdateCommandStatus( void LowEnergyConnection::L2capRequestConnectionParameterUpdate( const hci_spec::LEPreferredConnectionParameters& params) { - BT_ASSERT_MSG( + PW_CHECK( link_->role() == pw::bluetooth::emboss::ConnectionRole::PERIPHERAL, "tried to send l2cap connection parameter update request as central"); @@ -604,7 +603,7 @@ void LowEnergyConnection::UpdateConnectionParams( auto status_cb_wrapper = [handle = handle(), cb = std::move(status_cb)]( auto id, const hci::EmbossEventPacket& event) mutable { - BT_ASSERT(event.event_code() == hci_spec::kCommandStatusEventCode); + PW_CHECK(event.event_code() == hci_spec::kCommandStatusEventCode); hci_is_error(event, TRACE, "gap-le", @@ -622,10 +621,10 @@ void LowEnergyConnection::UpdateConnectionParams( void LowEnergyConnection::OnLEConnectionUpdateComplete( const hci::EmbossEventPacket& event) { - BT_ASSERT(event.event_code() == hci_spec::kLEMetaEventCode); + PW_CHECK(event.event_code() == hci_spec::kLEMetaEventCode); auto view = event.view(); - BT_ASSERT(view.subevent_code().Read() == - hci_spec::kLEConnectionUpdateCompleteSubeventCode); + PW_CHECK(view.subevent_code().Read() == + hci_spec::kLEConnectionUpdateCompleteSubeventCode); auto payload = event.view< pw::bluetooth::emboss::LEConnectionUpdateCompleteSubeventView>(); @@ -662,7 +661,7 @@ void LowEnergyConnection::OnLEConnectionUpdateComplete( payload.supervision_timeout().UncheckedRead()); link_->set_low_energy_parameters(params); - BT_ASSERT(peer_.is_alive()); + PW_CHECK(peer_.is_alive()); peer_->MutLe().SetConnectionParameters(params); } @@ -679,7 +678,7 @@ void LowEnergyConnection::MaybeUpdateConnectionParameters() { // been read by now, just use the default parameters. // TODO(fxbug.dev/42144795): Wait for preferred connection parameters to be // read. - BT_ASSERT(peer_.is_alive()); + PW_CHECK(peer_.is_alive()); auto conn_params = peer_->le()->preferred_connection_parameters().value_or( kDefaultPreferredConnectionParameters); UpdateConnectionParams(conn_params); diff --git a/pw_bluetooth_sapphire/host/gap/low_energy_connection_handle.cc b/pw_bluetooth_sapphire/host/gap/low_energy_connection_handle.cc index fbdade3571..0e9549937c 100644 --- a/pw_bluetooth_sapphire/host/gap/low_energy_connection_handle.cc +++ b/pw_bluetooth_sapphire/host/gap/low_energy_connection_handle.cc @@ -35,7 +35,7 @@ LowEnergyConnectionHandle::LowEnergyConnectionHandle( bondable_cb_(std::move(bondable_cb)), security_cb_(std::move(security_cb)), role_cb_(std::move(role_cb)) { - BT_ASSERT(peer_id_.IsValid()); + PW_CHECK(peer_id_.IsValid()); } LowEnergyConnectionHandle::~LowEnergyConnectionHandle() { @@ -45,7 +45,7 @@ LowEnergyConnectionHandle::~LowEnergyConnectionHandle() { } void LowEnergyConnectionHandle::Release() { - BT_ASSERT(active_); + PW_CHECK(active_); active_ = false; if (release_cb_) { release_cb_(this); @@ -64,22 +64,22 @@ void LowEnergyConnectionHandle::MarkClosed() { iso::AcceptCisStatus LowEnergyConnectionHandle::AcceptCis( iso::CigCisIdentifier id, iso::CisEstablishedCallback cis_established_cb) { - BT_ASSERT(active_); + PW_CHECK(active_); return accept_cis_cb_(id, std::move(cis_established_cb)); } sm::BondableMode LowEnergyConnectionHandle::bondable_mode() const { - BT_ASSERT(active_); + PW_CHECK(active_); return bondable_cb_(); } sm::SecurityProperties LowEnergyConnectionHandle::security() const { - BT_ASSERT(active_); + PW_CHECK(active_); return security_cb_(); } pw::bluetooth::emboss::ConnectionRole LowEnergyConnectionHandle::role() const { - BT_ASSERT(active_); + PW_CHECK(active_); return role_cb_(); } diff --git a/pw_bluetooth_sapphire/host/gap/low_energy_connection_manager.cc b/pw_bluetooth_sapphire/host/gap/low_energy_connection_manager.cc index fbd6a68bb4..0fe0d69de0 100644 --- a/pw_bluetooth_sapphire/host/gap/low_energy_connection_manager.cc +++ b/pw_bluetooth_sapphire/host/gap/low_energy_connection_manager.cc @@ -130,12 +130,12 @@ LowEnergyConnectionManager::LowEnergyConnectionManager( hci_connector_(connector), local_address_delegate_(addr_delegate), weak_self_(this) { - BT_DEBUG_ASSERT(peer_cache_); - BT_DEBUG_ASSERT(l2cap_); - BT_DEBUG_ASSERT(gatt_.is_alive()); - BT_DEBUG_ASSERT(hci_.is_alive()); - BT_DEBUG_ASSERT(hci_connector_); - BT_DEBUG_ASSERT(local_address_delegate_); + PW_DCHECK(peer_cache_); + PW_DCHECK(l2cap_); + PW_DCHECK(gatt_.is_alive()); + PW_DCHECK(hci_.is_alive()); + PW_DCHECK(hci_connector_); + PW_DCHECK(local_address_delegate_); } LowEnergyConnectionManager::~LowEnergyConnectionManager() { @@ -247,7 +247,7 @@ bool LowEnergyConnectionManager::Disconnect(PeerId peer_id, auto request_iter = pending_requests_.find(peer_id); if (request_iter != pending_requests_.end()) { - BT_ASSERT(current_request_->request.peer_id() != peer_id); + PW_CHECK(current_request_->request.peer_id() != peer_id); request_iter->second.NotifyCallbacks(fit::error(HostError::kCanceled)); pending_requests_.erase(request_iter); } @@ -384,7 +384,7 @@ void LowEnergyConnectionManager::RegisterRemoteInitiatedLink( std::unique_ptr link, sm::BondableMode bondable_mode, ConnectionResultCallback callback) { - BT_ASSERT(link); + PW_CHECK(link); Peer* peer = UpdatePeerWithLink(*link); auto peer_id = peer->identifier(); @@ -480,7 +480,7 @@ void LowEnergyConnectionManager::OpenL2capChannel( } auto& connection = connection_iterator->second; - BT_DEBUG_ASSERT(connection); + PW_DCHECK(connection); connection->OpenL2capChannel(psm, params, std::move(cb)); } @@ -491,10 +491,10 @@ void LowEnergyConnectionManager::SetDisconnectCallbackForTesting( void LowEnergyConnectionManager::ReleaseReference( LowEnergyConnectionHandle* handle) { - BT_ASSERT(handle); + PW_CHECK(handle); auto iter = connections_.find(handle->peer_identifier()); - BT_ASSERT(iter != connections_.end()); + PW_CHECK(iter != connections_.end()); iter->second->DropRef(handle); if (iter->second->ref_count() != 0u) @@ -573,7 +573,7 @@ void LowEnergyConnectionManager::TryCreateNextConnection() { void LowEnergyConnectionManager::OnLocalInitiatedConnectResult( hci::Result> result) { - BT_ASSERT(current_request_.has_value()); + PW_CHECK(current_request_.has_value()); internal::LowEnergyConnectionRequest request = std::move(current_request_->request); @@ -602,7 +602,7 @@ void LowEnergyConnectionManager::OnRemoteInitiatedConnectResult( PeerId peer_id, hci::Result> result) { auto remote_connector_node = remote_connectors_.extract(peer_id); - BT_ASSERT(!remote_connector_node.empty()); + PW_CHECK(!remote_connector_node.empty()); internal::LowEnergyConnectionRequest request = std::move(remote_connector_node.mapped().request); @@ -665,7 +665,7 @@ void LowEnergyConnectionManager::ProcessConnectResult( bool LowEnergyConnectionManager::InitializeConnection( std::unique_ptr connection, internal::LowEnergyConnectionRequest request) { - BT_ASSERT(connection); + PW_CHECK(connection); auto peer_id = connection->peer_id(); @@ -686,7 +686,7 @@ bool LowEnergyConnectionManager::InitializeConnection( } Peer* peer = peer_cache_->FindById(peer_id); - BT_ASSERT(peer); + PW_CHECK(peer); connection->AttachInspect( inspect_connections_node_, @@ -702,7 +702,7 @@ bool LowEnergyConnectionManager::InitializeConnection( auto [conn_iter, inserted] = connections_.try_emplace(peer_id, std::move(connection)); - BT_ASSERT(inserted); + PW_CHECK(inserted); conn_iter->second->set_peer_conn_token(peer->MutLe().RegisterConnection()); @@ -725,13 +725,13 @@ bool LowEnergyConnectionManager::InitializeConnection( void LowEnergyConnectionManager::CleanUpConnection( std::unique_ptr conn) { - BT_ASSERT(conn); + PW_CHECK(conn); // Mark the peer peer as no longer connected. Peer* peer = peer_cache_->FindById(conn->peer_id()); - BT_ASSERT_MSG(peer, - "A connection was active for an unknown peer! (id: %s)", - bt_str(conn->peer_id())); + PW_CHECK(peer, + "A connection was active for an unknown peer! (id: %s)", + bt_str(conn->peer_id())); conn.reset(); } diff --git a/pw_bluetooth_sapphire/host/gap/low_energy_connection_manager_test.cc b/pw_bluetooth_sapphire/host/gap/low_energy_connection_manager_test.cc index 881ba9a39d..1302fa9348 100644 --- a/pw_bluetooth_sapphire/host/gap/low_energy_connection_manager_test.cc +++ b/pw_bluetooth_sapphire/host/gap/low_energy_connection_manager_test.cc @@ -225,10 +225,10 @@ class LowEnergyConnectionManagerTest : public TestingBase { if (canceled) { canceled_peers_.insert(address); } else if (connected) { - BT_DEBUG_ASSERT(connected_peers_.find(address) == connected_peers_.end()); + PW_DCHECK(connected_peers_.find(address) == connected_peers_.end()); connected_peers_.insert(address); } else { - BT_DEBUG_ASSERT(connected_peers_.find(address) != connected_peers_.end()); + PW_DCHECK(connected_peers_.find(address) != connected_peers_.end()); connected_peers_.erase(address); } } @@ -537,7 +537,7 @@ TEST_F(LowEnergyConnectionManagerTest, ConnectSinglePeer) { struct TestObject final { explicit TestObject(bool* d) : deleted(d) { - BT_DEBUG_ASSERT(deleted); + PW_DCHECK(deleted); *deleted = false; } diff --git a/pw_bluetooth_sapphire/host/gap/low_energy_connector.cc b/pw_bluetooth_sapphire/host/gap/low_energy_connector.cc index 6261e0ab74..7d9eb3736b 100644 --- a/pw_bluetooth_sapphire/host/gap/low_energy_connector.cc +++ b/pw_bluetooth_sapphire/host/gap/low_energy_connector.cc @@ -62,17 +62,17 @@ LowEnergyConnector::LowEnergyConnector( options_(options), hci_(std::move(hci)), le_connection_manager_(std::move(conn_mgr)) { - BT_ASSERT(peer_cache_); - BT_ASSERT(l2cap_); - BT_ASSERT(gatt_.is_alive()); - BT_ASSERT(hci_.is_alive()); - BT_ASSERT(le_connection_manager_.is_alive()); + PW_CHECK(peer_cache_); + PW_CHECK(l2cap_); + PW_CHECK(gatt_.is_alive()); + PW_CHECK(hci_.is_alive()); + PW_CHECK(le_connection_manager_.is_alive()); cmd_ = hci_->command_channel()->AsWeakPtr(); - BT_ASSERT(cmd_.is_alive()); + PW_CHECK(cmd_.is_alive()); auto peer = peer_cache_->FindById(peer_id_); - BT_ASSERT(peer); + PW_CHECK(peer); peer_address_ = peer->address(); request_create_connection_task_.set_function( @@ -106,10 +106,10 @@ void LowEnergyConnector::StartOutbound( hci::LowEnergyConnector* connector, LowEnergyDiscoveryManager::WeakPtr discovery_manager, ResultCallback cb) { - BT_ASSERT(*state_ == State::kDefault); - BT_ASSERT(discovery_manager.is_alive()); - BT_ASSERT(connector); - BT_ASSERT(request_timeout.count() != 0); + PW_CHECK(*state_ == State::kDefault); + PW_CHECK(discovery_manager.is_alive()); + PW_CHECK(connector); + PW_CHECK(request_timeout.count() != 0); hci_connector_ = connector; discovery_manager_ = std::move(discovery_manager); hci_request_timeout_ = request_timeout; @@ -125,15 +125,15 @@ void LowEnergyConnector::StartOutbound( void LowEnergyConnector::StartInbound( std::unique_ptr connection, ResultCallback cb) { - BT_ASSERT(*state_ == State::kDefault); - BT_ASSERT(connection); + PW_CHECK(*state_ == State::kDefault); + PW_CHECK(connection); // Connection address should resolve to same peer as the given peer ID. Peer* conn_peer = peer_cache_->FindByAddress(connection->peer_address()); - BT_ASSERT(conn_peer); - BT_ASSERT_MSG(peer_id_ == conn_peer->identifier(), - "peer_id_ (%s) != connection peer (%s)", - bt_str(peer_id_), - bt_str(conn_peer->identifier())); + PW_CHECK(conn_peer); + PW_CHECK(peer_id_ == conn_peer->identifier(), + "peer_id_ (%s) != connection peer (%s)", + bt_str(peer_id_), + bt_str(conn_peer->identifier())); result_cb_ = std::move(cb); set_is_outbound(false); @@ -242,7 +242,7 @@ void LowEnergyConnector::OnScanStart(LowEnergyDiscoverySessionPtr session) { if (*state_ == State::kFailed) { return; } - BT_ASSERT(*state_ == State::kStartingScanning); + PW_CHECK(*state_ == State::kStartingScanning); // Failed to start scan, abort connection procedure. if (!session) { @@ -263,7 +263,7 @@ void LowEnergyConnector::OnScanStart(LowEnergyDiscoverySessionPtr session) { if (!status.ok()) { return; } - BT_ASSERT(*state_ == State::kScanning); + PW_CHECK(*state_ == State::kScanning); bt_log(INFO, "gap-le", "scan for pending connection timed out (peer: %s)", @@ -279,7 +279,7 @@ void LowEnergyConnector::OnScanStart(LowEnergyDiscoverySessionPtr session) { // The error callback must be set before the result callback in case the // result callback is called synchronously. discovery_session_->set_error_callback([self] { - BT_ASSERT(self->state_.value() == State::kScanning); + PW_CHECK(self->state_.value() == State::kScanning); bt_log(INFO, "gap-le", "discovery error while scanning for peer (peer: %s)", @@ -289,7 +289,7 @@ void LowEnergyConnector::OnScanStart(LowEnergyDiscoverySessionPtr session) { }); discovery_session_->SetResultCallback([self](auto& peer) { - BT_ASSERT(self->state_.value() == State::kScanning); + PW_CHECK(self->state_.value() == State::kScanning); if (peer.identifier() != self->peer_id_) { return; @@ -310,8 +310,8 @@ void LowEnergyConnector::OnScanStart(LowEnergyDiscoverySessionPtr session) { void LowEnergyConnector::RequestCreateConnection() { // Scanning may be skipped. When the peer disconnects during/after // interrogation, a retry may be initiated by calling this method. - BT_ASSERT(*state_ == State::kDefault || *state_ == State::kScanning || - *state_ == State::kPauseBeforeConnectionRetry); + PW_CHECK(*state_ == State::kDefault || *state_ == State::kScanning || + *state_ == State::kPauseBeforeConnectionRetry); // Pause discovery until connection complete. std::optional pause_token; @@ -331,7 +331,7 @@ void LowEnergyConnector::RequestCreateConnection() { // TODO(fxbug.dev/42149416): Use slow interval & window for auto connections // during background scan. - BT_ASSERT(hci_connector_->CreateConnection( + PW_CHECK(hci_connector_->CreateConnection( /*use_accept_list=*/false, peer_address_, kLEScanFastInterval, @@ -353,7 +353,7 @@ void LowEnergyConnector::OnConnectResult( NotifyFailure(status); return; } - BT_ASSERT(link); + PW_CHECK(link); bt_log(INFO, "gap-le", @@ -367,14 +367,14 @@ void LowEnergyConnector::OnConnectResult( bool LowEnergyConnector::InitializeConnection( std::unique_ptr link) { - BT_ASSERT(link); + PW_CHECK(link); auto peer_disconnect_cb = fit::bind_member<&LowEnergyConnector::OnPeerDisconnect>(this); auto error_cb = [this]() { NotifyFailure(); }; Peer* peer = peer_cache_->FindById(peer_id_); - BT_ASSERT(peer); + PW_CHECK(peer); auto connection = LowEnergyConnection::Create(peer->GetWeakPtr(), std::move(link), options_, @@ -399,13 +399,13 @@ bool LowEnergyConnector::InitializeConnection( } void LowEnergyConnector::StartInterrogation() { - BT_ASSERT((*is_outbound_ && *state_ == State::kConnecting) || - (!*is_outbound_ && *state_ == State::kDefault)); - BT_ASSERT(connection_); + PW_CHECK((*is_outbound_ && *state_ == State::kConnecting) || + (!*is_outbound_ && *state_ == State::kDefault)); + PW_CHECK(connection_); state_.Set(State::kInterrogating); auto peer = peer_cache_->FindById(peer_id_); - BT_ASSERT(peer); + PW_CHECK(peer); bool sca_supported = adapter_state_.SupportedCommands().le_request_peer_sca().Read(); interrogator_.emplace( @@ -418,14 +418,14 @@ void LowEnergyConnector::OnInterrogationComplete(hci::Result<> status) { // If a disconnect event is received before interrogation completes, state_ // will be either kFailed or kPauseBeforeConnectionRetry depending on the // status of the disconnect. - BT_ASSERT(*state_ == State::kInterrogating || *state_ == State::kFailed || - *state_ == State::kPauseBeforeConnectionRetry); + PW_CHECK(*state_ == State::kInterrogating || *state_ == State::kFailed || + *state_ == State::kPauseBeforeConnectionRetry); if (*state_ == State::kFailed || *state_ == State::kPauseBeforeConnectionRetry) { return; } - BT_ASSERT(connection_); + PW_CHECK(connection_); // If the controller responds to an interrogation command with the 0x3e // "kConnectionFailedToBeEstablished" error, it will send a Disconnection @@ -460,7 +460,7 @@ void LowEnergyConnector::OnPeerDisconnect( pw::bluetooth::emboss::StatusCode status_code) { // The peer can't disconnect while scanning or connecting, and we unregister // from disconnects after kFailed & kComplete. - BT_ASSERT_MSG( + PW_CHECK( *state_ == State::kInterrogating || *state_ == State::kAwaitingConnectionFailedToBeEstablishedDisconnect, "Received peer disconnect during invalid state (state: %s, status: %s)", @@ -504,9 +504,9 @@ bool LowEnergyConnector::MaybeRetryConnection() { } void LowEnergyConnector::NotifySuccess() { - BT_ASSERT(*state_ == State::kInterrogating); - BT_ASSERT(connection_); - BT_ASSERT(result_cb_); + PW_CHECK(*state_ == State::kInterrogating); + PW_CHECK(connection_); + PW_CHECK(result_cb_); state_.Set(State::kComplete); diff --git a/pw_bluetooth_sapphire/host/gap/low_energy_discovery_manager.cc b/pw_bluetooth_sapphire/host/gap/low_energy_discovery_manager.cc index 06f7421716..d05a9318de 100644 --- a/pw_bluetooth_sapphire/host/gap/low_energy_discovery_manager.cc +++ b/pw_bluetooth_sapphire/host/gap/low_energy_discovery_manager.cc @@ -37,7 +37,7 @@ const char* kInspectScanWindowPropertyName = "scan_window_ms"; LowEnergyDiscoverySession::LowEnergyDiscoverySession( bool active, LowEnergyDiscoveryManager::WeakPtr manager) : alive_(true), active_(active), manager_(std::move(manager)) { - BT_ASSERT(manager_.is_alive()); + PW_CHECK(manager_.is_alive()); } LowEnergyDiscoverySession::~LowEnergyDiscoverySession() { @@ -65,7 +65,7 @@ void LowEnergyDiscoverySession::SetResultCallback(PeerFoundCallback callback) { } void LowEnergyDiscoverySession::Stop() { - BT_DEBUG_ASSERT(alive_); + PW_DCHECK(alive_); if (manager_.is_alive()) { manager_->RemoveSession(this); } @@ -73,7 +73,7 @@ void LowEnergyDiscoverySession::Stop() { } void LowEnergyDiscoverySession::NotifyDiscoveryResult(const Peer& peer) const { - BT_ASSERT(peer.le()); + PW_CHECK(peer.le()); if (!alive_ || !peer_found_callback_) { return; @@ -103,8 +103,8 @@ LowEnergyDiscoveryManager::LowEnergyDiscoveryManager( peer_cache_(peer_cache), paused_count_(0), scanner_(scanner) { - BT_DEBUG_ASSERT(peer_cache_); - BT_DEBUG_ASSERT(scanner_); + PW_DCHECK(peer_cache_); + PW_DCHECK(scanner_); scanner_->set_delegate(this); } @@ -117,7 +117,7 @@ LowEnergyDiscoveryManager::~LowEnergyDiscoveryManager() { void LowEnergyDiscoveryManager::StartDiscovery(bool active, SessionCallback callback) { - BT_ASSERT(callback); + PW_CHECK(callback); bt_log(INFO, "gap-le", "start %s discovery", active ? "active" : "passive"); // If a request to start or stop is currently pending then this one will @@ -130,7 +130,7 @@ void LowEnergyDiscoveryManager::StartDiscovery(bool active, if (!pending_.empty() || (scanner_->state() == hci::LowEnergyScanner::State::kStopping && sessions_.empty())) { - BT_ASSERT(!scanner_->IsScanning()); + PW_CHECK(!scanner_->IsScanning()); pending_.push_back( DiscoveryRequest{.active = active, .callback = std::move(callback)}); return; @@ -190,7 +190,7 @@ LowEnergyDiscoveryManager::PauseDiscovery() { return; } - BT_ASSERT(paused()); + PW_CHECK(paused()); paused_count_.Set(*paused_count_ - 1); if (*paused_count_ == 0) { ResumeDiscovery(); @@ -243,14 +243,14 @@ LowEnergyDiscoveryManager::AddSession(bool active) { void LowEnergyDiscoveryManager::RemoveSession( LowEnergyDiscoverySession* session) { - BT_ASSERT(session); + PW_CHECK(session); // Only alive sessions are allowed to call this method. If there is at least // one alive session object out there, then we MUST be scanning. - BT_ASSERT(session->alive()); + PW_CHECK(session->alive()); auto iter = std::find(sessions_.begin(), sessions_.end(), session); - BT_ASSERT(iter != sessions_.end()); + PW_CHECK(iter != sessions_.end()); bool active = session->active(); @@ -298,7 +298,7 @@ void LowEnergyDiscoveryManager::OnPeerFound( // Create a new entry if we found the device during general discovery. if (!peer) { peer = peer_cache_->NewPeer(result.address(), result.connectable()); - BT_ASSERT(peer); + PW_CHECK(peer); } else if (!peer->connectable() && result.connectable()) { bt_log(DEBUG, "gap-le", @@ -506,7 +506,7 @@ void LowEnergyDiscoveryManager::NotifyPending() { cb(std::move(new_sessions[i])); } } - BT_ASSERT(pending_.empty()); + PW_CHECK(pending_.empty()); } void LowEnergyDiscoveryManager::StartScan(bool active) { @@ -560,7 +560,7 @@ void LowEnergyDiscoveryManager::StopScan() { } void LowEnergyDiscoveryManager::ResumeDiscovery() { - BT_ASSERT(!paused()); + PW_CHECK(!paused()); if (!scanner_->IsIdle()) { bt_log(TRACE, "gap-le", "attempt to resume discovery when it is not idle"); @@ -599,7 +599,7 @@ void LowEnergyDiscoveryManager::DeactivateAndNotifySessions() { // Due to the move, sessions_ should be empty before the loop and any // callbacks will add sessions to pending_ so it should be empty // afterwards as well. - BT_ASSERT(sessions_.empty()); + PW_CHECK(sessions_.empty()); } } // namespace bt::gap diff --git a/pw_bluetooth_sapphire/host/gap/low_energy_discovery_manager_test.cc b/pw_bluetooth_sapphire/host/gap/low_energy_discovery_manager_test.cc index ca2d6cf7da..638cde23e4 100644 --- a/pw_bluetooth_sapphire/host/gap/low_energy_discovery_manager_test.cc +++ b/pw_bluetooth_sapphire/host/gap/low_energy_discovery_manager_test.cc @@ -112,7 +112,7 @@ class LowEnergyDiscoveryManagerTest : public TestingBase { std::vector InspectProperties() const { auto hierarchy = InspectHierarchy(); auto children = hierarchy.take_children(); - BT_ASSERT(children.size() == 1u); + PW_CHECK(children.size() == 1u); return children.front().node_ptr()->take_properties(); } #endif // NINSPECT @@ -278,12 +278,12 @@ class LowEnergyDiscoveryManagerTest : public TestingBase { bool active = true) { std::unique_ptr session; discovery_manager()->StartDiscovery(active, [&](auto cb_session) { - BT_ASSERT(cb_session); + PW_CHECK(cb_session); session = std::move(cb_session); }); RunUntilIdle(); - BT_ASSERT(session); + PW_CHECK(session); return session; } @@ -1055,7 +1055,7 @@ TEST_F(LowEnergyDiscoveryManagerTest, StartAndDisablePassiveScanQuickly) { // Session will be destroyed in callback, stopping scan. discovery_manager()->StartDiscovery( - /*active=*/false, [&](auto cb_session) { BT_ASSERT(cb_session); }); + /*active=*/false, [&](auto cb_session) { PW_CHECK(cb_session); }); RunUntilIdle(); EXPECT_FALSE(test_device()->le_scan_state().enabled); @@ -1065,10 +1065,10 @@ TEST_F(LowEnergyDiscoveryManagerTest, StartAndDisablePassiveScanQuickly) { // requests will be processed at the same time, and second call to // StartDiscovery() retains its session. discovery_manager()->StartDiscovery( - /*active=*/false, [&](auto cb_session) { BT_ASSERT(cb_session); }); + /*active=*/false, [&](auto cb_session) { PW_CHECK(cb_session); }); std::unique_ptr session; discovery_manager()->StartDiscovery(/*active=*/false, [&](auto cb_session) { - BT_ASSERT(cb_session); + PW_CHECK(cb_session); session = std::move(cb_session); }); RunUntilIdle(); @@ -1164,14 +1164,14 @@ TEST_F(LowEnergyDiscoveryManagerTest, StartActiveScanDuringPassiveScan) { TEST_F(LowEnergyDiscoveryManagerTest, StartActiveScanWhileStartingPassiveScan) { std::unique_ptr passive_session; discovery_manager()->StartDiscovery(/*active=*/false, [&](auto cb_session) { - BT_ASSERT(cb_session); + PW_CHECK(cb_session); passive_session = std::move(cb_session); }); ASSERT_FALSE(passive_session); std::unique_ptr active_session; discovery_manager()->StartDiscovery(/*active=*/true, [&](auto cb_session) { - BT_ASSERT(cb_session); + PW_CHECK(cb_session); active_session = std::move(cb_session); }); ASSERT_FALSE(active_session); @@ -1537,7 +1537,7 @@ TEST_F(LowEnergyDiscoveryManagerTest, Inspect) { std::unique_ptr passive_session; discovery_manager()->StartDiscovery(/*active=*/false, [&](auto cb_session) { - BT_ASSERT(cb_session); + PW_CHECK(cb_session); passive_session = std::move(cb_session); }); EXPECT_THAT(InspectProperties(), diff --git a/pw_bluetooth_sapphire/host/gap/low_energy_interrogator.cc b/pw_bluetooth_sapphire/host/gap/low_energy_interrogator.cc index f54be9a369..a4955e17a4 100644 --- a/pw_bluetooth_sapphire/host/gap/low_energy_interrogator.cc +++ b/pw_bluetooth_sapphire/host/gap/low_energy_interrogator.cc @@ -34,7 +34,7 @@ LowEnergyInterrogator::LowEnergyInterrogator( weak_self_(this) {} void LowEnergyInterrogator::Start(ResultCallback callback) { - BT_ASSERT(!callback_); + PW_CHECK(!callback_); callback_ = std::move(callback); if (!peer_.is_alive()) { @@ -42,7 +42,7 @@ void LowEnergyInterrogator::Start(ResultCallback callback) { return; } - BT_ASSERT(peer_->le().has_value()); + PW_CHECK(peer_->le().has_value()); // Always read remote version information as a test of whether the connection // was *actually* successfully established. If the connection failed to be @@ -140,9 +140,9 @@ void LowEnergyInterrogator::QueueRequestPeerSca() { cmd_runner_.RunCommands([this](hci::Result<> result) { // This shouldn't happen since we verified that the peer supports SCA // updates - BT_DEBUG_ASSERT_MSG(!result.is_error(), - "request for SCA from peer %s failed", - bt_str(peer_id_)); + PW_DCHECK(!result.is_error(), + "request for SCA from peer %s failed", + bt_str(peer_id_)); // Report success since the data is not critical and we don't want to // interrupt pairing Complete(fit::ok()); @@ -198,8 +198,8 @@ void LowEnergyInterrogator::QueueReadRemoteVersionInformation() { event, WARN, "gap-le", "read remote version info failed")) { return; } - BT_DEBUG_ASSERT(event.event_code() == - hci_spec::kReadRemoteVersionInfoCompleteEventCode); + PW_DCHECK(event.event_code() == + hci_spec::kReadRemoteVersionInfoCompleteEventCode); bt_log(TRACE, "gap-le", "read remote version info completed (peer: %s)", diff --git a/pw_bluetooth_sapphire/host/gap/pairing_state_manager.cc b/pw_bluetooth_sapphire/host/gap/pairing_state_manager.cc index f9123fce00..a5930af5d3 100644 --- a/pw_bluetooth_sapphire/host/gap/pairing_state_manager.cc +++ b/pw_bluetooth_sapphire/host/gap/pairing_state_manager.cc @@ -65,10 +65,10 @@ PairingStateManager::PairingStateManager( // We should also check that |peer| and |outgoing_connection| are unchanged // before and after connection is complete - BT_ASSERT(legacy_pairing_state_->peer()->identifier() == - peer_->identifier()); - BT_ASSERT(legacy_pairing_state_->outgoing_connection() == - outgoing_connection); + PW_CHECK(legacy_pairing_state_->peer()->identifier() == + peer_->identifier()); + PW_CHECK(legacy_pairing_state_->outgoing_connection() == + outgoing_connection); } } diff --git a/pw_bluetooth_sapphire/host/gap/peer.cc b/pw_bluetooth_sapphire/host/gap/peer.cc index f8d506fa29..efb761cbd8 100644 --- a/pw_bluetooth_sapphire/host/gap/peer.cc +++ b/pw_bluetooth_sapphire/host/gap/peer.cc @@ -87,7 +87,7 @@ Peer::LowEnergyData::LowEnergyData(Peer* owner) : ""; }), service_changed_gatt_data_({.notify = false, .indicate = false}) { - BT_DEBUG_ASSERT(peer_); + PW_DCHECK(peer_); } void Peer::LowEnergyData::AttachInspect(inspect::Node& parent, @@ -205,13 +205,13 @@ Peer::ConnectionToken Peer::LowEnergyData::RegisterConnection() { void Peer::LowEnergyData::SetConnectionParameters( const hci_spec::LEConnectionParameters& params) { - BT_DEBUG_ASSERT(peer_->connectable()); + PW_DCHECK(peer_->connectable()); conn_params_ = params; } void Peer::LowEnergyData::SetPreferredConnectionParameters( const hci_spec::LEPreferredConnectionParameters& params) { - BT_DEBUG_ASSERT(peer_->connectable()); + PW_DCHECK(peer_->connectable()); preferred_conn_params_ = params; } @@ -220,8 +220,8 @@ bool Peer::LowEnergyData::StoreBond(const sm::PairingData& bond_data) { } void Peer::LowEnergyData::SetBondData(const sm::PairingData& bond_data) { - BT_DEBUG_ASSERT(peer_->connectable()); - BT_DEBUG_ASSERT(peer_->address().type() != DeviceAddress::Type::kLEAnonymous); + PW_DCHECK(peer_->connectable()); + PW_DCHECK(peer_->address().type() != DeviceAddress::Type::kLEAnonymous); // Make sure the peer is non-temporary. peer_->TryMakeNonTemporary(); @@ -241,7 +241,7 @@ void Peer::LowEnergyData::SetBondData(const sm::PairingData& bond_data) { } void Peer::LowEnergyData::ClearBondData() { - BT_ASSERT(bond_data_->has_value()); + PW_CHECK(bond_data_->has_value()); if (bond_data_->value().irk) { peer_->set_identity_known(false); } @@ -280,13 +280,13 @@ void Peer::LowEnergyData::OnConnectionStateMaybeChanged( Peer::BrEdrData::BrEdrData(Peer* owner) : peer_(owner), services_({}, MakeContainerOfToStringConvertFunction()) { - BT_DEBUG_ASSERT(peer_); - BT_DEBUG_ASSERT(peer_->identity_known()); + PW_DCHECK(peer_); + PW_DCHECK(peer_->identity_known()); // Devices that are capable of BR/EDR and use a LE random device address will // end up with separate entries for the BR/EDR and LE addresses. - BT_DEBUG_ASSERT(peer_->address().type() != DeviceAddress::Type::kLERandom && - peer_->address().type() != DeviceAddress::Type::kLEAnonymous); + PW_DCHECK(peer_->address().type() != DeviceAddress::Type::kLERandom && + peer_->address().type() != DeviceAddress::Type::kLEAnonymous); address_ = {DeviceAddress::Type::kBREDR, peer_->address().value()}; } @@ -304,8 +304,7 @@ void Peer::BrEdrData::AttachInspect(inspect::Node& parent, std::string name) { void Peer::BrEdrData::SetInquiryData( const pw::bluetooth::emboss::InquiryResultView& view) { - BT_DEBUG_ASSERT(peer_->address().value() == - DeviceAddressBytes{view.bd_addr()}); + PW_DCHECK(peer_->address().value() == DeviceAddressBytes{view.bd_addr()}); SetInquiryData( DeviceClass(view.class_of_device().BackingStorage().ReadUInt()), view.clock_offset().BackingStorage().ReadUInt(), @@ -314,8 +313,7 @@ void Peer::BrEdrData::SetInquiryData( void Peer::BrEdrData::SetInquiryData( const pw::bluetooth::emboss::InquiryResultWithRssiView& view) { - BT_DEBUG_ASSERT(peer_->address().value() == - DeviceAddressBytes{view.bd_addr()}); + PW_DCHECK(peer_->address().value() == DeviceAddressBytes{view.bd_addr()}); SetInquiryData( DeviceClass(view.class_of_device().BackingStorage().ReadUInt()), view.clock_offset().BackingStorage().ReadUInt(), @@ -325,8 +323,7 @@ void Peer::BrEdrData::SetInquiryData( void Peer::BrEdrData::SetInquiryData( const pw::bluetooth::emboss::ExtendedInquiryResultEventView& view) { - BT_DEBUG_ASSERT(peer_->address().value() == - DeviceAddressBytes(view.bd_addr())); + PW_DCHECK(peer_->address().value() == DeviceAddressBytes(view.bd_addr())); const BufferView response_view( view.extended_inquiry_response().BackingStorage().data(), view.extended_inquiry_response().SizeInBytes()); @@ -340,7 +337,7 @@ void Peer::BrEdrData::SetInquiryData( Peer::InitializingConnectionToken Peer::BrEdrData::RegisterInitializingConnection() { - BT_ASSERT(!connected()); + PW_CHECK(!connected()); ConnectionState prev_state = connection_state(); initializing_tokens_count_++; @@ -358,10 +355,10 @@ Peer::BrEdrData::RegisterInitializingConnection() { } Peer::ConnectionToken Peer::BrEdrData::RegisterConnection() { - BT_ASSERT_MSG(!connected(), - "attempt to register BR/EDR connection when a connection is " - "already registered (peer: %s)", - bt_str(peer_->identifier())); + PW_CHECK(!connected(), + "attempt to register BR/EDR connection when a connection is " + "already registered (peer: %s)", + bt_str(peer_->identifier())); ConnectionState prev_state = connection_state(); connection_tokens_count_++; @@ -452,7 +449,7 @@ void Peer::BrEdrData::SetInquiryData( } bool Peer::BrEdrData::SetEirData(const ByteBuffer& eir) { - BT_DEBUG_ASSERT(eir.size()); + PW_DCHECK(eir.size()); // TODO(armansito): Validate that the EIR data is not malformed? SupplementDataReader reader(eir); @@ -486,7 +483,7 @@ bool Peer::BrEdrData::SetEirData(const ByteBuffer& eir) { } void Peer::BrEdrData::SetBondData(const sm::LTK& link_key) { - BT_DEBUG_ASSERT(peer_->connectable()); + PW_DCHECK(peer_->connectable()); // Make sure the peer is non-temporary. peer_->TryMakeNonTemporary(); @@ -500,7 +497,7 @@ void Peer::BrEdrData::SetBondData(const sm::LTK& link_key) { } void Peer::BrEdrData::ClearBondData() { - BT_ASSERT(link_key_.has_value()); + PW_CHECK(link_key_.has_value()); link_key_ = std::nullopt; } @@ -557,10 +554,10 @@ Peer::Peer(NotifyListenersCallback notify_listeners_callback, last_updated_(dispatcher.now()), dispatcher_(dispatcher), weak_self_(this) { - BT_DEBUG_ASSERT(notify_listeners_callback_); - BT_DEBUG_ASSERT(update_expiry_callback_); - BT_DEBUG_ASSERT(dual_mode_callback_); - BT_DEBUG_ASSERT(identifier.IsValid()); + PW_DCHECK(notify_listeners_callback_); + PW_DCHECK(update_expiry_callback_); + PW_DCHECK(dual_mode_callback_); + PW_DCHECK(identifier.IsValid()); if (address.type() == DeviceAddress::Type::kBREDR || address.type() == DeviceAddress::Type::kLEPublic) { @@ -717,19 +714,19 @@ bool Peer::TryMakeTemporary() { } void Peer::UpdateExpiry() { - BT_DEBUG_ASSERT(update_expiry_callback_); + PW_DCHECK(update_expiry_callback_); update_expiry_callback_(*this); } void Peer::NotifyListeners(NotifyListenersChange change) { - BT_DEBUG_ASSERT(notify_listeners_callback_); + PW_DCHECK(notify_listeners_callback_); notify_listeners_callback_(*this, change); } void Peer::MakeDualMode() { technology_.Set(TechnologyType::kDualMode); if (bredr_cross_transport_key_) { - BT_ASSERT( + PW_CHECK( bredr_data_); // Should only be hit after BR/EDR is already created. bredr_data_->SetBondData(*bredr_cross_transport_key_); bt_log(DEBUG, @@ -737,7 +734,7 @@ void Peer::MakeDualMode() { "restored cross-transport-generated br/edr link key"); bredr_cross_transport_key_ = std::nullopt; } - BT_DEBUG_ASSERT(dual_mode_callback_); + PW_DCHECK(dual_mode_callback_); dual_mode_callback_(*this); } diff --git a/pw_bluetooth_sapphire/host/gap/peer_cache.cc b/pw_bluetooth_sapphire/host/gap/peer_cache.cc index b546ab4e20..3a71bf42e6 100644 --- a/pw_bluetooth_sapphire/host/gap/peer_cache.cc +++ b/pw_bluetooth_sapphire/host/gap/peer_cache.cc @@ -50,14 +50,14 @@ Peer* PeerCache::NewPeer(const DeviceAddress& address, bool connectable) { } void PeerCache::ForEach(PeerCallback f) { - BT_DEBUG_ASSERT(f); + PW_DCHECK(f); for (const auto& iter : peers_) { f(*iter.second.peer()); } } bool PeerCache::AddBondedPeer(BondingData bd) { - BT_DEBUG_ASSERT(bd.address.type() != DeviceAddress::Type::kLEAnonymous); + PW_DCHECK(bd.address.type() != DeviceAddress::Type::kLEAnonymous); const bool bond_le = bd.le_pairing_data.peer_ltk || bd.le_pairing_data.local_ltk || bd.le_pairing_data.csrk; @@ -100,10 +100,10 @@ bool PeerCache::AddBondedPeer(BondingData bd) { } if (bond_le) { - BT_ASSERT(bd.le_pairing_data.irk.has_value() == - bd.le_pairing_data.identity_address.has_value()); + PW_CHECK(bd.le_pairing_data.irk.has_value() == + bd.le_pairing_data.identity_address.has_value()); peer->MutLe().SetBondData(bd.le_pairing_data); - BT_ASSERT(peer->le()->bonded()); + PW_CHECK(peer->le()->bonded()); // Add the peer to the resolving list if it has an IRK. if (bd.le_pairing_data.irk) { @@ -118,15 +118,15 @@ bool PeerCache::AddBondedPeer(BondingData bd) { } peer->MutBrEdr().SetBondData(*bd.bredr_link_key); - BT_DEBUG_ASSERT(peer->bredr()->bonded()); + PW_DCHECK(peer->bredr()->bonded()); } if (peer->technology() == TechnologyType::kDualMode) { address_map_[GetAliasAddress(bd.address)] = bd.identifier; } - BT_DEBUG_ASSERT(!peer->temporary()); - BT_DEBUG_ASSERT(peer->bonded()); + PW_DCHECK(!peer->temporary()); + PW_DCHECK(peer->bonded()); bt_log(TRACE, "gap", "restored bonded peer: %s, id: %s", @@ -141,8 +141,7 @@ bool PeerCache::AddBondedPeer(BondingData bd) { bool PeerCache::StoreLowEnergyBond(PeerId identifier, const sm::PairingData& bond_data) { - BT_ASSERT(bond_data.irk.has_value() == - bond_data.identity_address.has_value()); + PW_CHECK(bond_data.irk.has_value() == bond_data.identity_address.has_value()); auto log_bond_failure = fit::defer([this] { peer_metrics_.LogLeBondFailureEvent(); }); @@ -190,8 +189,8 @@ bool PeerCache::StoreLowEnergyBond(PeerId identifier, // TODO(fxbug.dev/42072204): Check that we're not downgrading the security // level before overwriting the bond. peer->MutLe().SetBondData(bond_data); - BT_DEBUG_ASSERT(!peer->temporary()); - BT_DEBUG_ASSERT(peer->le()->bonded()); + PW_DCHECK(!peer->temporary()); + PW_DCHECK(peer->le()->bonded()); // Add the peer to the resolving list if it has an IRK. if (peer->identity_known() && bond_data.irk) { @@ -214,7 +213,7 @@ bool PeerCache::StoreLowEnergyBond(PeerId identifier, bool PeerCache::StoreBrEdrBond(const DeviceAddress& address, const sm::LTK& link_key) { - BT_DEBUG_ASSERT(address.type() == DeviceAddress::Type::kBREDR); + PW_DCHECK(address.type() == DeviceAddress::Type::kBREDR); auto* peer = FindByAddress(address); if (!peer) { bt_log(WARN, @@ -227,8 +226,8 @@ bool PeerCache::StoreBrEdrBond(const DeviceAddress& address, // TODO(fxbug.dev/42072204): Check that we're not downgrading the security // level before overwriting the bond. peer->MutBrEdr().SetBondData(link_key); - BT_DEBUG_ASSERT(!peer->temporary()); - BT_DEBUG_ASSERT(peer->bredr()->bonded()); + PW_DCHECK(!peer->temporary()); + PW_DCHECK(peer->bredr()->bonded()); NotifyPeerBonded(*peer); return true; @@ -316,14 +315,14 @@ Peer* PeerCache::FindByAddress(const DeviceAddress& in_address) const { address = in_address; } - BT_DEBUG_ASSERT(address); + PW_DCHECK(address); auto identifier = FindIdByAddress(*address); if (!identifier) { return nullptr; } auto* p = FindById(*identifier); - BT_DEBUG_ASSERT(p); + PW_DCHECK(p); return p; } @@ -345,7 +344,7 @@ PeerCache::CallbackId PeerCache::add_peer_updated_callback( PeerCallback callback) { auto [iter, success] = peer_updated_callbacks_.emplace(next_callback_id_++, std::move(callback)); - BT_ASSERT(success); + PW_CHECK(success); return iter->first; } @@ -404,10 +403,10 @@ Peer* PeerCache::InsertPeerRecord(PeerId identifier, } void PeerCache::NotifyPeerBonded(const Peer& peer) { - BT_DEBUG_ASSERT(peers_.find(peer.identifier()) != peers_.end()); - BT_DEBUG_ASSERT(peers_.at(peer.identifier()).peer() == &peer); - BT_DEBUG_ASSERT_MSG(peer.identity_known(), - "peers not allowed to bond with unknown identity!"); + PW_DCHECK(peers_.find(peer.identifier()) != peers_.end()); + PW_DCHECK(peers_.at(peer.identifier()).peer() == &peer); + PW_DCHECK(peer.identity_known(), + "peers not allowed to bond with unknown identity!"); bt_log(INFO, "gap", "successfully bonded (peer: %s)", bt_str(peer)); if (peer_bonded_callback_) { @@ -417,15 +416,15 @@ void PeerCache::NotifyPeerBonded(const Peer& peer) { void PeerCache::NotifyPeerUpdated(const Peer& peer, Peer::NotifyListenersChange change) { - BT_DEBUG_ASSERT(peers_.find(peer.identifier()) != peers_.end()); - BT_DEBUG_ASSERT(peers_.at(peer.identifier()).peer() == &peer); + PW_DCHECK(peers_.find(peer.identifier()) != peers_.end()); + PW_DCHECK(peers_.at(peer.identifier()).peer() == &peer); for (auto& [_, peer_updated_callback] : peer_updated_callbacks_) { peer_updated_callback(peer); } if (change == Peer::NotifyListenersChange::kBondUpdated) { - BT_ASSERT(peer.bonded()); + PW_CHECK(peer.bonded()); bt_log(INFO, "gap", "peer bond updated %s", bt_str(peer)); if (peer_bonded_callback_) { peer_bonded_callback_(peer); @@ -435,10 +434,10 @@ void PeerCache::NotifyPeerUpdated(const Peer& peer, void PeerCache::UpdateExpiry(const Peer& peer) { auto peer_record_iter = peers_.find(peer.identifier()); - BT_DEBUG_ASSERT(peer_record_iter != peers_.end()); + PW_DCHECK(peer_record_iter != peers_.end()); auto& peer_record = peer_record_iter->second; - BT_DEBUG_ASSERT(peer_record.peer() == &peer); + PW_DCHECK(peer_record.peer() == &peer); peer_record.removal_task()->Cancel(); @@ -450,15 +449,15 @@ void PeerCache::UpdateExpiry(const Peer& peer) { } void PeerCache::MakeDualMode(const Peer& peer) { - BT_ASSERT(address_map_.at(peer.address()) == peer.identifier()); + PW_CHECK(address_map_.at(peer.address()) == peer.identifier()); const auto address_alias = GetAliasAddress(peer.address()); auto [iter, inserted] = address_map_.try_emplace(address_alias, peer.identifier()); - BT_ASSERT_MSG(inserted || iter->second == peer.identifier(), - "%s can't become dual-mode because %s maps to %s", - bt_str(peer.identifier()), - bt_str(address_alias), - bt_str(iter->second)); + PW_CHECK(inserted || iter->second == peer.identifier(), + "%s can't become dual-mode because %s maps to %s", + bt_str(peer.identifier()), + bt_str(address_alias), + bt_str(iter->second)); bt_log(INFO, "gap", "peer became dual mode (peer: %s, address: %s, alias: %s)", @@ -472,11 +471,11 @@ void PeerCache::MakeDualMode(const Peer& peer) { } void PeerCache::RemovePeer(Peer* peer) { - BT_DEBUG_ASSERT(peer); + PW_DCHECK(peer); auto peer_record_it = peers_.find(peer->identifier()); - BT_DEBUG_ASSERT(peer_record_it != peers_.end()); - BT_DEBUG_ASSERT(peer_record_it->second.peer() == peer); + PW_DCHECK(peer_record_it != peers_.end()); + PW_DCHECK(peer_record_it->second.peer() == peer); PeerId id = peer->identifier(); bt_log(DEBUG, "gap", "removing peer %s", bt_str(id)); diff --git a/pw_bluetooth_sapphire/host/gap/peer_test.cc b/pw_bluetooth_sapphire/host/gap/peer_test.cc index c10f18fd43..543cc2f0bf 100644 --- a/pw_bluetooth_sapphire/host/gap/peer_test.cc +++ b/pw_bluetooth_sapphire/host/gap/peer_test.cc @@ -117,7 +117,7 @@ class PeerTest : public pw::async::test::FakeDispatcherFixture { {"peer", "le_data", Peer::LowEnergyData::kInspectConnectionStateName}); - BT_ASSERT(val); + PW_CHECK(val); return *val; } @@ -127,7 +127,7 @@ class PeerTest : public pw::async::test::FakeDispatcherFixture { {"peer", "le_data", Peer::LowEnergyData::kInspectAdvertisingDataParseFailureCountName}); - BT_ASSERT(val); + PW_CHECK(val); return *val; } @@ -138,21 +138,21 @@ class PeerTest : public pw::async::test::FakeDispatcherFixture { {"peer", "le_data", Peer::LowEnergyData::kInspectLastAdvertisingDataParseFailureName}); - BT_ASSERT(val); + PW_CHECK(val); return *val; } uint64_t MetricsLowEnergyConnections() { std::optional val = GetInspectValue( metrics_inspector_, {"metrics", "le", "connection_events"}); - BT_ASSERT(val); + PW_CHECK(val); return *val; } uint64_t MetricsLowEnergyDisconnections() { std::optional val = GetInspectValue( metrics_inspector_, {"metrics", "le", "disconnection_events"}); - BT_ASSERT(val); + PW_CHECK(val); return *val; } @@ -163,21 +163,21 @@ class PeerTest : public pw::async::test::FakeDispatcherFixture { {"peer", "bredr_data", Peer::BrEdrData::kInspectConnectionStateName}); - BT_ASSERT(val); + PW_CHECK(val); return *val; } uint64_t MetricsBrEdrConnections() { std::optional val = GetInspectValue( metrics_inspector_, {"metrics", "bredr", "connection_events"}); - BT_ASSERT(val); + PW_CHECK(val); return *val; } uint64_t MetricsBrEdrDisconnections() { std::optional val = GetInspectValue( metrics_inspector_, {"metrics", "bredr", "disconnection_events"}); - BT_ASSERT(val); + PW_CHECK(val); return *val; } #endif // NINSPECT diff --git a/pw_bluetooth_sapphire/host/gap/secure_simple_pairing_state.cc b/pw_bluetooth_sapphire/host/gap/secure_simple_pairing_state.cc index 5d16f24588..27b6312f28 100644 --- a/pw_bluetooth_sapphire/host/gap/secure_simple_pairing_state.cc +++ b/pw_bluetooth_sapphire/host/gap/secure_simple_pairing_state.cc @@ -50,9 +50,9 @@ SecureSimplePairingState::SecureSimplePairingState( state_(State::kIdle), send_auth_request_callback_(std::move(auth_cb)), status_callback_(std::move(status_cb)) { - BT_ASSERT(link_.is_alive()); - BT_ASSERT(send_auth_request_callback_); - BT_ASSERT(status_callback_); + PW_CHECK(link_.is_alive()); + PW_CHECK(send_auth_request_callback_); + PW_CHECK(status_callback_); link_->set_encryption_change_callback( fit::bind_member<&SecureSimplePairingState::OnEncryptionChange>(this)); cleanup_cb_ = [](SecureSimplePairingState* self) { @@ -83,7 +83,7 @@ void SecureSimplePairingState::InitiatePairing( // TODO(fxbug.dev/42082728): Reject pairing if peer/local device don't support // Secure Connections and SC is required if (state() == State::kIdle) { - BT_ASSERT(!is_pairing()); + PW_CHECK(!is_pairing()); // If the current link key already meets the security requirements, skip // pairing and report success. @@ -122,7 +122,7 @@ void SecureSimplePairingState::InitiatePairing( // ongoing pairing procedure instead of sending their own Authentication // Request. if (is_pairing()) { - BT_ASSERT(state() != State::kIdle); + PW_CHECK(state() != State::kIdle); bt_log(INFO, "gap-bredr", "Already pairing %#.4x (id: %s); blocking callback on completion", @@ -134,14 +134,14 @@ void SecureSimplePairingState::InitiatePairing( } else { // In the error state, we should expect no pairing to be created and cancel // this particular request immediately. - BT_ASSERT(state() == State::kFailed); + PW_CHECK(state() == State::kFailed); status_cb(handle(), ToResult(HostError::kCanceled)); } } void SecureSimplePairingState::InitiateNextPairingRequest() { - BT_ASSERT(state() == State::kIdle); - BT_ASSERT(!is_pairing()); + PW_CHECK(state() == State::kIdle); + PW_CHECK(!is_pairing()); if (request_queue_.empty()) { return; @@ -187,11 +187,11 @@ std::optional SecureSimplePairingState::OnIoCapabilityRequest() { current_pairing_->local_iocap = sm::util::IOCapabilityForHci(pairing_delegate()->io_capability()); if (state() == State::kInitiatorWaitIoCapRequest) { - BT_ASSERT(initiator()); + PW_CHECK(initiator()); state_ = State::kInitiatorWaitIoCapResponse; } else { - BT_ASSERT(is_pairing()); - BT_ASSERT(!initiator()); + PW_CHECK(is_pairing()); + PW_CHECK(!initiator()); current_pairing_->ComputePairingData(); state_ = GetStateForPairingEvent(current_pairing_->expected_event); @@ -205,19 +205,19 @@ void SecureSimplePairingState::OnIoCapabilityResponse(IoCapability peer_iocap) { // they may try to re-pair. Cancel the previous pairing if they try to // restart. if (state() == State::kWaitEncryption) { - BT_ASSERT(is_pairing()); + PW_CHECK(is_pairing()); current_pairing_ = nullptr; state_ = State::kIdle; } if (state() == State::kIdle) { - BT_ASSERT(!is_pairing()); + PW_CHECK(!is_pairing()); current_pairing_ = Pairing::MakeResponder(peer_iocap, outgoing_connection_); // Defer gathering local IO Capability until OnIoCapabilityRequest, where // the pairing can be rejected if there's no pairing delegate. state_ = State::kResponderWaitIoCapRequest; } else if (state() == State::kInitiatorWaitIoCapResponse) { - BT_ASSERT(initiator()); + PW_CHECK(initiator()); current_pairing_->peer_iocap = peer_iocap; current_pairing_->ComputePairingData(); @@ -235,10 +235,10 @@ void SecureSimplePairingState::OnUserConfirmationRequest( cb(false); return; } - BT_ASSERT(is_pairing()); + PW_CHECK(is_pairing()); // TODO(fxbug.dev/42113087): Reject pairing if pairing delegate went away. - BT_ASSERT(pairing_delegate().is_alive()); + PW_CHECK(pairing_delegate().is_alive()); state_ = State::kWaitPairingComplete; if (current_pairing_->action == PairingAction::kAutomatic) { @@ -301,17 +301,17 @@ void SecureSimplePairingState::OnUserPasskeyRequest(UserPasskeyCallback cb) { cb(std::nullopt); return; } - BT_ASSERT(is_pairing()); + PW_CHECK(is_pairing()); // TODO(fxbug.dev/42113087): Reject pairing if pairing delegate went away. - BT_ASSERT(pairing_delegate().is_alive()); + PW_CHECK(pairing_delegate().is_alive()); state_ = State::kWaitPairingComplete; - BT_ASSERT_MSG(current_pairing_->action == PairingAction::kRequestPasskey, - "%#.4x (id: %s): unexpected action %d", - handle(), - bt_str(peer_id()), - static_cast(current_pairing_->action)); + PW_CHECK(current_pairing_->action == PairingAction::kRequestPasskey, + "%#.4x (id: %s): unexpected action %d", + handle(), + bt_str(peer_id()), + static_cast(current_pairing_->action)); auto pairing = current_pairing_->GetWeakPtr(); auto passkey_cb = [this, callback = std::move(cb), pairing](int64_t passkey) mutable { @@ -339,10 +339,10 @@ void SecureSimplePairingState::OnUserPasskeyNotification( FailWithUnexpectedEvent(__func__); return; } - BT_ASSERT(is_pairing()); + PW_CHECK(is_pairing()); // TODO(fxbug.dev/42113087): Reject pairing if pairing delegate went away. - BT_ASSERT(pairing_delegate().is_alive()); + PW_CHECK(pairing_delegate().is_alive()); state_ = State::kWaitPairingComplete; auto pairing = current_pairing_->GetWeakPtr(); @@ -390,7 +390,7 @@ void SecureSimplePairingState::OnSimplePairingComplete( FailWithUnexpectedEvent(__func__); return; } - BT_ASSERT(is_pairing()); + PW_CHECK(is_pairing()); pairing_delegate()->CompletePairing(peer_id(), fit::ok()); state_ = State::kWaitLinkKey; @@ -403,7 +403,7 @@ std::optional SecureSimplePairingState::OnLinkKeyRequest() { return std::nullopt; } - BT_ASSERT(peer_.is_alive()); + PW_CHECK(peer_.is_alive()); std::optional link_key; @@ -418,10 +418,10 @@ std::optional SecureSimplePairingState::OnLinkKeyRequest() { "recalling link key for bonded peer %s", bt_str(peer_->identifier())); - BT_ASSERT(peer_->bredr()->link_key().has_value()); + PW_CHECK(peer_->bredr()->link_key().has_value()); link_key = peer_->bredr()->link_key(); - BT_ASSERT(link_key->security().enc_key_size() == - hci_spec::kBrEdrLinkKeySize); + PW_CHECK(link_key->security().enc_key_size() == + hci_spec::kBrEdrLinkKeySize); const auto link_key_type = link_key->security().GetLinkKeyType(); link_->set_link_key(link_key->key(), link_key_type); @@ -434,7 +434,7 @@ std::optional SecureSimplePairingState::OnLinkKeyRequest() { // the peer initiates the authentication procedure). if (state() == State::kIdle) { if (link_key.has_value()) { - BT_ASSERT(!is_pairing()); + PW_CHECK(!is_pairing()); current_pairing_ = Pairing::MakeResponderForBonded(); state_ = State::kWaitEncryption; return link_key->key(); @@ -442,7 +442,7 @@ std::optional SecureSimplePairingState::OnLinkKeyRequest() { return std::optional(); } - BT_ASSERT(is_pairing()); + PW_CHECK(is_pairing()); if (link_key.has_value() && SecurityPropertiesMeetRequirements( @@ -464,11 +464,11 @@ void SecureSimplePairingState::OnLinkKeyNotification( // TODO(fxbug.dev/42111880): We assume the controller is never in pairing // debug mode because it's a security hazard to pair and bond using Debug // Combination link keys. - BT_ASSERT_MSG(key_type != hci_spec::LinkKeyType::kDebugCombination, - "Pairing on link %#.4x (id: %s) resulted in insecure Debug " - "Combination link key", - handle(), - bt_str(peer_id())); + PW_CHECK(key_type != hci_spec::LinkKeyType::kDebugCombination, + "Pairing on link %#.4x (id: %s) resulted in insecure Debug " + "Combination link key", + handle(), + bt_str(peer_id())); // When not pairing, only connection link key changes are allowed. if (state() == State::kIdle && @@ -503,7 +503,7 @@ void SecureSimplePairingState::OnLinkKeyNotification( // The association model and resulting link security properties are computed // by both the Link Manager (controller) and the host subsystem, so check that // they agree. - BT_ASSERT(is_pairing()); + PW_CHECK(is_pairing()); sm::SecurityProperties sec_props = sm::SecurityProperties(key_type); current_pairing_->security_properties = sec_props; @@ -632,7 +632,7 @@ void SecureSimplePairingState::OnAuthenticationComplete( FailWithUnexpectedEvent(__func__); return; } - BT_ASSERT(initiator()); + PW_CHECK(initiator()); EnableEncryption(); } @@ -724,7 +724,7 @@ void SecureSimplePairingState::Pairing::ComputePairingData() { action = PairingAction::kGetConsent; } expected_event = GetExpectedEvent(local_iocap, peer_iocap); - BT_DEBUG_ASSERT(GetStateForPairingEvent(expected_event) != State::kFailed); + PW_DCHECK(GetStateForPairingEvent(expected_event) != State::kFailed); authenticated = IsPairingAuthenticated(local_iocap, peer_iocap); bt_log(DEBUG, "gap-bredr", @@ -819,7 +819,7 @@ std::vector SecureSimplePairingState::CompletePairingRequests( std::vector callbacks_to_signal; if (!is_pairing()) { - BT_ASSERT(request_queue_.empty()); + PW_CHECK(request_queue_.empty()); return callbacks_to_signal; } @@ -836,8 +836,8 @@ std::vector SecureSimplePairingState::CompletePairingRequests( return callbacks_to_signal; } - BT_ASSERT(state_ == State::kIdle); - BT_ASSERT(link_->ltk_type().has_value()); + PW_CHECK(state_ == State::kIdle); + PW_CHECK(link_->ltk_type().has_value()); auto security_properties = sm::SecurityProperties(link_->ltk_type().value()); diff --git a/pw_bluetooth_sapphire/host/gatt/client.cc b/pw_bluetooth_sapphire/host/gatt/client.cc index 07395b0317..58f578073b 100644 --- a/pw_bluetooth_sapphire/host/gatt/client.cc +++ b/pw_bluetooth_sapphire/host/gatt/client.cc @@ -45,7 +45,7 @@ bool ProcessDescriptorDiscoveryResponse( BufferView entries, Client::DescriptorCallback desc_callback, att::Handle* out_last_handle) { - BT_DEBUG_ASSERT(out_last_handle); + PW_DCHECK(out_last_handle); if (entries.size() % sizeof(EntryType)) { bt_log(DEBUG, "gatt", "malformed information data list"); @@ -96,11 +96,11 @@ class Impl final : public Client { public: explicit Impl(att::Bearer::WeakPtr bearer) : att_(std::move(bearer)), weak_self_(this) { - BT_DEBUG_ASSERT(att_.is_alive()); + PW_DCHECK(att_.is_alive()); auto handler = [this](auto txn_id, const att::PacketReader& pdu) { - BT_DEBUG_ASSERT(pdu.opcode() == att::kNotification || - pdu.opcode() == att::kIndication); + PW_DCHECK(pdu.opcode() == att::kNotification || + pdu.opcode() == att::kIndication); if (pdu.payload_size() < sizeof(att::NotificationParams)) { // Received a malformed notification. Disconnect the link. @@ -177,7 +177,7 @@ class Impl final : public Client { att::Bearer::TransactionResult result) mutable { if (result.is_ok()) { const att::PacketReader& rsp = result.value(); - BT_DEBUG_ASSERT(rsp.opcode() == att::kExchangeMTUResponse); + PW_DCHECK(rsp.opcode() == att::kExchangeMTUResponse); if (rsp.payload_size() != sizeof(att::ExchangeMTUResponseParams)) { // Received a malformed response. Disconnect the link. @@ -235,7 +235,7 @@ class Impl final : public Client { att::Handle range_end, ServiceCallback svc_callback, att::ResultFunction<> status_callback) override { - BT_ASSERT(range_start <= range_end); + PW_CHECK(range_start <= range_end); auto pdu = NewPDU(sizeof(att::ReadByGroupTypeRequestParams16)); if (!pdu) { @@ -277,7 +277,7 @@ class Impl final : public Client { } const att::PacketReader& rsp = result.value(); - BT_DEBUG_ASSERT(rsp.opcode() == att::kReadByGroupTypeResponse); + PW_DCHECK(rsp.opcode() == att::kReadByGroupTypeResponse); TRACE_DURATION("bluetooth", "gatt::Client::DiscoverServicesInRange rsp_cb", "size", @@ -401,8 +401,8 @@ class Impl final : public Client { ServiceCallback svc_callback, att::ResultFunction<> status_callback, std::vector uuids) override { - BT_ASSERT(range_start <= range_end); - BT_ASSERT(!uuids.empty()); + PW_CHECK(range_start <= range_end); + PW_CHECK(!uuids.empty()); UUID uuid = uuids.back(); uuids.pop_back(); @@ -486,7 +486,7 @@ class Impl final : public Client { } const att::PacketReader& rsp = result.value(); - BT_DEBUG_ASSERT(rsp.opcode() == att::kFindByTypeValueResponse); + PW_DCHECK(rsp.opcode() == att::kFindByTypeValueResponse); size_t payload_size = rsp.payload_size(); if (payload_size < 1 || @@ -571,9 +571,9 @@ class Impl final : public Client { att::Handle range_end, CharacteristicCallback chrc_callback, att::ResultFunction<> status_callback) override { - BT_ASSERT(range_start <= range_end); - BT_ASSERT(chrc_callback); - BT_ASSERT(status_callback); + PW_CHECK(range_start <= range_end); + PW_CHECK(chrc_callback); + PW_CHECK(status_callback); if (range_start == range_end) { status_callback(fit::ok()); @@ -606,7 +606,7 @@ class Impl final : public Client { // ReadByTypeRequest() should return an error result if there are no // attributes in a success response. - BT_ASSERT(!attributes.empty()); + PW_CHECK(!attributes.empty()); for (auto& char_attr : attributes) { Properties properties = 0u; @@ -686,9 +686,9 @@ class Impl final : public Client { att::Handle range_end, DescriptorCallback desc_callback, att::ResultFunction<> status_callback) override { - BT_DEBUG_ASSERT(range_start <= range_end); - BT_DEBUG_ASSERT(desc_callback); - BT_DEBUG_ASSERT(status_callback); + PW_DCHECK(range_start <= range_end); + PW_DCHECK(desc_callback); + PW_DCHECK(status_callback); auto pdu = NewPDU(sizeof(att::FindInformationRequestParams)); if (!pdu) { @@ -723,7 +723,7 @@ class Impl final : public Client { return; } const att::PacketReader& rsp = result.value(); - BT_DEBUG_ASSERT(rsp.opcode() == att::kFindInformationResponse); + PW_DCHECK(rsp.opcode() == att::kFindInformationResponse); TRACE_DURATION("bluetooth", "gatt::Client::DiscoverDescriptors rsp_cb", "size", @@ -804,7 +804,7 @@ class Impl final : public Client { att::Bearer::TransactionResult result) { if (result.is_ok()) { const att::PacketReader& rsp = result.value(); - BT_DEBUG_ASSERT(rsp.opcode() == att::kReadResponse); + PW_DCHECK(rsp.opcode() == att::kReadResponse); bool maybe_truncated = (rsp.payload_size() != att::kMaxAttributeValueLength) && (rsp.payload_size() == (mtu() - sizeof(rsp.opcode()))); @@ -828,7 +828,7 @@ class Impl final : public Client { att::Handle end_handle, ReadByTypeCallback callback) override { size_t type_size = type.CompactSize(/*allow_32bit=*/false); - BT_ASSERT(type_size == sizeof(uint16_t) || type_size == sizeof(UInt128)); + PW_CHECK(type_size == sizeof(uint16_t) || type_size == sizeof(UInt128)); auto pdu = NewPDU(type_size == sizeof(uint16_t) ? sizeof(att::ReadByTypeRequestParams16) : sizeof(att::ReadByTypeRequestParams128)); @@ -873,7 +873,7 @@ class Impl final : public Client { return; } const att::PacketReader& rsp = result.value(); - BT_ASSERT(rsp.opcode() == att::kReadByTypeResponse); + PW_CHECK(rsp.opcode() == att::kReadByTypeResponse); if (rsp.payload_size() < sizeof(att::ReadByTypeResponseParams)) { cb(fit::error( ReadByTypeError{Error(HostError::kPacketMalformed), std::nullopt})); @@ -946,7 +946,7 @@ class Impl final : public Client { // Advance list view to next pair (or end of list). attr_list_view = attr_list_view.view(pair_size); } - BT_ASSERT(attr_list_view.size() == 0); + PW_CHECK(attr_list_view.size() == 0); cb(fit::ok(std::move(attributes))); }; @@ -974,7 +974,7 @@ class Impl final : public Client { att::Bearer::TransactionResult result) { if (result.is_ok()) { const att::PacketReader& rsp = result.value(); - BT_DEBUG_ASSERT(rsp.opcode() == att::kReadBlobResponse); + PW_DCHECK(rsp.opcode() == att::kReadBlobResponse); bool maybe_truncated = (static_cast(offset) + rsp.payload_size() != att::kMaxAttributeValueLength) && @@ -1031,7 +1031,7 @@ class Impl final : public Client { return; } const att::PacketReader& rsp = result.value(); - BT_DEBUG_ASSERT(rsp.opcode() == att::kWriteResponse); + PW_DCHECK(rsp.opcode() == att::kWriteResponse); if (rsp.payload_size()) { att_->ShutDown(); @@ -1118,7 +1118,7 @@ class Impl final : public Client { callback(prep_write_status); // Now that this request is complete, remove it from the overall // queue. - BT_DEBUG_ASSERT(!long_write_queue_.empty()); + PW_DCHECK(!long_write_queue_.empty()); long_write_queue_.pop(); if (long_write_queue_.size() > 0) { @@ -1148,7 +1148,7 @@ class Impl final : public Client { callback(status); // Now that this request is complete, remove it from the overall // queue. - BT_DEBUG_ASSERT(!long_write_queue_.empty()); + PW_DCHECK(!long_write_queue_.empty()); long_write_queue_.pop(); // If the super queue still has any long writes left to execute, @@ -1194,7 +1194,7 @@ class Impl final : public Client { [cb = std::move(callback)](att::Bearer::TransactionResult result) { if (result.is_ok()) { const att::PacketReader& rsp = result.value(); - BT_DEBUG_ASSERT(rsp.opcode() == att::kPrepareWriteResponse); + PW_DCHECK(rsp.opcode() == att::kPrepareWriteResponse); cb(fit::ok(), rsp.payload_data()); return; } @@ -1236,7 +1236,7 @@ class Impl final : public Client { att::Bearer::TransactionResult result) { if (result.is_ok()) { const att::PacketReader& rsp = result.value(); - BT_DEBUG_ASSERT(rsp.opcode() == att::kExecuteWriteResponse); + PW_DCHECK(rsp.opcode() == att::kExecuteWriteResponse); if (rsp.payload_size()) { att_->ShutDown(); diff --git a/pw_bluetooth_sapphire/host/gatt/connection.cc b/pw_bluetooth_sapphire/host/gatt/connection.cc index b2a9efe9f3..ba174f3bbe 100644 --- a/pw_bluetooth_sapphire/host/gatt/connection.cc +++ b/pw_bluetooth_sapphire/host/gatt/connection.cc @@ -28,7 +28,7 @@ Connection::Connection(std::unique_ptr client, std::unique_ptr server, RemoteServiceWatcher svc_watcher) : server_(std::move(server)), weak_self_(this) { - BT_ASSERT(svc_watcher); + PW_CHECK(svc_watcher); remote_service_manager_ = std::make_unique(std::move(client)); @@ -37,7 +37,7 @@ Connection::Connection(std::unique_ptr client, void Connection::Initialize(std::vector service_uuids, fit::callback mtu_cb) { - BT_ASSERT(remote_service_manager_); + PW_CHECK(remote_service_manager_); auto uuids_count = service_uuids.size(); // status_cb must not capture att_ in order to prevent reference cycle. diff --git a/pw_bluetooth_sapphire/host/gatt/fake_layer.cc b/pw_bluetooth_sapphire/host/gatt/fake_layer.cc index 73a83ec8d4..e19797a9a3 100644 --- a/pw_bluetooth_sapphire/host/gatt/fake_layer.cc +++ b/pw_bluetooth_sapphire/host/gatt/fake_layer.cc @@ -28,7 +28,7 @@ FakeLayer::AddPeerService(PeerId peer_id, auto [iter, _] = peers_.try_emplace(peer_id, pw_dispatcher_); auto& peer = iter->second; - BT_ASSERT(info.range_start <= info.range_end); + PW_CHECK(info.range_start <= info.range_end); auto service = std::make_unique(info, peer.fake_client.GetWeakPtr()); RemoteService::WeakPtr service_weak = service->GetWeakPtr(); @@ -207,7 +207,7 @@ void FakeLayer::InitializeClient(PeerId peer_id, GATT::RemoteServiceWatcherId FakeLayer::RegisterRemoteServiceWatcherForPeer( PeerId peer_id, RemoteServiceWatcher watcher) { - BT_ASSERT(remote_service_watchers_.count(peer_id) == 0); + PW_CHECK(remote_service_watchers_.count(peer_id) == 0); remote_service_watchers_[peer_id] = std::move(watcher); // Use the PeerId as the watcher ID because FakeLayer only needs to support 1 // watcher per peer. diff --git a/pw_bluetooth_sapphire/host/gatt/gatt.cc b/pw_bluetooth_sapphire/host/gatt/gatt.cc index 8b6d026c9e..81e2c64880 100644 --- a/pw_bluetooth_sapphire/host/gatt/gatt.cc +++ b/pw_bluetooth_sapphire/host/gatt/gatt.cc @@ -234,7 +234,7 @@ class Impl final : public GATT { RemoteServiceWatcherId RegisterRemoteServiceWatcherForPeer( PeerId peer_id, RemoteServiceWatcher watcher) override { - BT_ASSERT(watcher); + PW_CHECK(watcher); RemoteServiceWatcherId id = next_watcher_id_++; peer_remote_service_watchers_.emplace( @@ -258,7 +258,7 @@ class Impl final : public GATT { void ListServices(PeerId peer_id, std::vector uuids, ServiceListCallback callback) override { - BT_ASSERT(callback); + PW_CHECK(callback); auto iter = connections_.find(peer_id); if (iter == connections_.end()) { // Connection not found. diff --git a/pw_bluetooth_sapphire/host/gatt/generic_attribute_service.cc b/pw_bluetooth_sapphire/host/gatt/generic_attribute_service.cc index 36c6644c7e..116ddfec00 100644 --- a/pw_bluetooth_sapphire/host/gatt/generic_attribute_service.cc +++ b/pw_bluetooth_sapphire/host/gatt/generic_attribute_service.cc @@ -26,8 +26,8 @@ GenericAttributeService::GenericAttributeService( SendIndicationCallback send_indication_callback) : local_service_manager_(std::move(local_service_manager)), send_indication_callback_(std::move(send_indication_callback)) { - BT_ASSERT(local_service_manager_.is_alive()); - BT_DEBUG_ASSERT(send_indication_callback_); + PW_CHECK(local_service_manager_.is_alive()); + PW_DCHECK(send_indication_callback_); Register(); } @@ -60,7 +60,7 @@ void GenericAttributeService::Register() { PeerId peer_id, bool notify, bool indicate) { - BT_DEBUG_ASSERT(chrc_id == 0u); + PW_DCHECK(chrc_id == 0u); SetServiceChangedIndicationSubscription(peer_id, indicate); if (persist_service_changed_ccc_callback_) { @@ -92,7 +92,7 @@ void GenericAttributeService::Register() { ReadResponder responder) { // The stack shouldn't send us any read requests other than this id, none of // the other characteristics or descriptors support it. - BT_DEBUG_ASSERT(chrc_id == kServerSupportedFeaturesChrcId); + PW_DCHECK(chrc_id == kServerSupportedFeaturesChrcId); // The only octet is the first octet. The only bit is the EATT supported // bit. @@ -105,7 +105,7 @@ void GenericAttributeService::Register() { std::move(read_handler), NopWriteHandler, std::move(ccc_callback)); - BT_DEBUG_ASSERT(service_id_ != kInvalidId); + PW_DCHECK(service_id_ != kInvalidId); local_service_manager_->set_service_changed_callback( fit::bind_member<&GenericAttributeService::OnServiceChanged>(this)); diff --git a/pw_bluetooth_sapphire/host/gatt/generic_attribute_service_test.cc b/pw_bluetooth_sapphire/host/gatt/generic_attribute_service_test.cc index 0e33e7870a..6cf05fe42f 100644 --- a/pw_bluetooth_sapphire/host/gatt/generic_attribute_service_test.cc +++ b/pw_bluetooth_sapphire/host/gatt/generic_attribute_service_test.cc @@ -37,10 +37,10 @@ class GenericAttributeServiceTest : public ::testing::Test { bool WriteServiceChangedCcc(PeerId peer_id, uint16_t ccc_value, fit::result* out_status) { - BT_ASSERT(out_status); + PW_CHECK(out_status); auto* attr = mgr.database()->FindAttribute(kCCCHandle); - BT_ASSERT(attr); + PW_CHECK(attr); auto result_cb = [&out_status](auto cb_status) { *out_status = cb_status; }; uint16_t value = pw::bytes::ConvertOrderTo(cpp20::endian::little, ccc_value); diff --git a/pw_bluetooth_sapphire/host/gatt/local_service_manager.cc b/pw_bluetooth_sapphire/host/gatt/local_service_manager.cc index 90e7e17a34..14d3de9c87 100644 --- a/pw_bluetooth_sapphire/host/gatt/local_service_manager.cc +++ b/pw_bluetooth_sapphire/host/gatt/local_service_manager.cc @@ -33,10 +33,10 @@ att::Handle InsertCharacteristicAttributes( const Characteristic& chrc, att::Attribute::ReadHandler read_handler, att::Attribute::WriteHandler write_handler) { - BT_DEBUG_ASSERT(grouping); - BT_DEBUG_ASSERT(!grouping->complete()); - BT_DEBUG_ASSERT(read_handler); - BT_DEBUG_ASSERT(write_handler); + PW_DCHECK(grouping); + PW_DCHECK(!grouping->complete()); + PW_DCHECK(read_handler); + PW_DCHECK(write_handler); // Characteristic Declaration (Vol 3, Part G, 3.3.1). auto* decl_attr = grouping->AddAttribute( @@ -45,18 +45,18 @@ att::Handle InsertCharacteristicAttributes( /*authentication=*/false, /*authorization=*/false), // read (no security) att::AccessRequirements()); // write (not allowed) - BT_DEBUG_ASSERT(decl_attr); + PW_DCHECK(decl_attr); // Characteristic Value Declaration (Vol 3, Part G, 3.3.2) auto* value_attr = grouping->AddAttribute( chrc.type(), chrc.read_permissions(), chrc.write_permissions()); - BT_DEBUG_ASSERT(value_attr); + PW_DCHECK(value_attr); value_attr->set_read_handler(std::move(read_handler)); value_attr->set_write_handler(std::move(write_handler)); size_t uuid_size = chrc.type().CompactSize(/*allow_32bit=*/false); - BT_DEBUG_ASSERT(uuid_size == 2 || uuid_size == 16); + PW_DCHECK(uuid_size == 2 || uuid_size == 16); // The characteristic declaration value contains: // 1 octet: properties @@ -81,14 +81,14 @@ void InsertDescriptorAttribute(att::AttributeGrouping* grouping, const att::AccessRequirements& write_reqs, att::Attribute::ReadHandler read_handler, att::Attribute::WriteHandler write_handler) { - BT_DEBUG_ASSERT(grouping); - BT_DEBUG_ASSERT(!grouping->complete()); - BT_DEBUG_ASSERT(read_handler); - BT_DEBUG_ASSERT(write_handler); + PW_DCHECK(grouping); + PW_DCHECK(!grouping->complete()); + PW_DCHECK(read_handler); + PW_DCHECK(write_handler); // There is no special declaration attribute type for descriptors. auto* attr = grouping->AddAttribute(type, read_reqs, write_reqs); - BT_DEBUG_ASSERT(attr); + PW_DCHECK(attr); attr->set_read_handler(std::move(read_handler)); attr->set_write_handler(std::move(write_handler)); @@ -98,7 +98,7 @@ void InsertDescriptorAttribute(att::AttributeGrouping* grouping, // Returns the number of attributes that will be in the service attribute group // (exluding the service declaration) in |out_attrs|. bool ValidateService(const Service& service, size_t* out_attr_count) { - BT_DEBUG_ASSERT(out_attr_count); + PW_DCHECK(out_attr_count); size_t attr_count = 0u; std::unordered_set ids; @@ -168,10 +168,10 @@ class LocalServiceManager::ServiceData final { write_handler_(std::forward(write_handler)), ccc_callback_(std::forward(ccc_callback)), weak_self_(this) { - BT_DEBUG_ASSERT(read_handler_); - BT_DEBUG_ASSERT(write_handler_); - BT_DEBUG_ASSERT(ccc_callback_); - BT_DEBUG_ASSERT(grouping); + PW_DCHECK(read_handler_); + PW_DCHECK(write_handler_); + PW_DCHECK(ccc_callback_); + PW_DCHECK(grouping); start_handle_ = grouping->start_handle(); end_handle_ = grouping->end_handle(); @@ -196,7 +196,7 @@ class LocalServiceManager::ServiceData final { bool GetCharacteristicConfig(IdType chrc_id, PeerId peer_id, ClientCharacteristicConfig* out_config) { - BT_DEBUG_ASSERT(out_config); + PW_DCHECK(out_config); auto iter = chrc_configs_.find(chrc_id); if (iter == chrc_configs_.end()) @@ -394,7 +394,7 @@ class LocalServiceManager::ServiceData final { /*authentication=*/false, /*authorization=*/false), // read (no security) att::AccessRequirements()); // write (not allowed) - BT_DEBUG_ASSERT(decl_attr); + PW_DCHECK(decl_attr); decl_attr->SetValue(StaticByteBuffer( (uint8_t)(ext_props & 0x00FF), (uint8_t)((ext_props & 0xFF00) >> 8))); } @@ -461,7 +461,7 @@ class LocalServiceManager::ServiceData final { void AddCCCDescriptor(att::AttributeGrouping* grouping, const Characteristic& chrc, att::Handle chrc_handle) { - BT_DEBUG_ASSERT(chrc.update_permissions().allowed()); + PW_DCHECK(chrc.update_permissions().allowed()); // Readable with no authentication or authorization (Vol 3, Part G, // 3.3.3.3). We let the service determine the encryption permission. @@ -530,7 +530,7 @@ LocalServiceManager::LocalServiceManager() : WeakSelf(this), db_(std::make_unique()), next_service_id_(1ull) { - BT_DEBUG_ASSERT(db_); + PW_DCHECK(db_); } LocalServiceManager::~LocalServiceManager() = default; @@ -539,10 +539,10 @@ IdType LocalServiceManager::RegisterService(ServicePtr service, ReadHandler read_handler, WriteHandler write_handler, ClientConfigCallback ccc_callback) { - BT_DEBUG_ASSERT(service); - BT_DEBUG_ASSERT(read_handler); - BT_DEBUG_ASSERT(write_handler); - BT_DEBUG_ASSERT(ccc_callback); + PW_DCHECK(service); + PW_DCHECK(read_handler); + PW_DCHECK(write_handler); + PW_DCHECK(ccc_callback); if (services_.find(next_service_id_) != services_.end()) { bt_log(TRACE, "gatt", "server: Ran out of service IDs"); @@ -578,7 +578,7 @@ IdType LocalServiceManager::RegisterService(ServicePtr service, std::move(read_handler), std::move(write_handler), std::move(ccc_callback)); - BT_DEBUG_ASSERT(grouping->complete()); + PW_DCHECK(grouping->complete()); grouping->set_active(true); // TODO(armansito): Handle potential 64-bit unsigned overflow? @@ -614,7 +614,7 @@ bool LocalServiceManager::GetCharacteristicConfig( IdType chrc_id, PeerId peer_id, ClientCharacteristicConfig* out_config) { - BT_DEBUG_ASSERT(out_config); + PW_DCHECK(out_config); auto iter = services_.find(service_id); if (iter == services_.end()) diff --git a/pw_bluetooth_sapphire/host/gatt/local_service_manager_test.cc b/pw_bluetooth_sapphire/host/gatt/local_service_manager_test.cc index 1725879230..2908c3e5e9 100644 --- a/pw_bluetooth_sapphire/host/gatt/local_service_manager_test.cc +++ b/pw_bluetooth_sapphire/host/gatt/local_service_manager_test.cc @@ -1065,9 +1065,9 @@ class LocalClientCharacteristicConfigurationTest : public ::testing::Test { PeerId peer_id, fit::result* out_status, uint16_t* out_value) { - BT_ASSERT(attr); - BT_ASSERT(out_status); - BT_ASSERT(out_value); + PW_CHECK(attr); + PW_CHECK(out_status); + PW_CHECK(out_value); auto result_cb = [&out_status, &out_value](auto cb_status, const auto& value) { @@ -1087,8 +1087,8 @@ class LocalClientCharacteristicConfigurationTest : public ::testing::Test { PeerId peer_id, uint16_t ccc_value, fit::result* out_status) { - BT_ASSERT(attr); - BT_ASSERT(out_status); + PW_CHECK(attr); + PW_CHECK(out_status); auto result_cb = [&out_status](auto cb_status) { *out_status = cb_status; }; uint16_t value = diff --git a/pw_bluetooth_sapphire/host/gatt/remote_characteristic.cc b/pw_bluetooth_sapphire/host/gatt/remote_characteristic.cc index 05b1cc018c..8fa556065e 100644 --- a/pw_bluetooth_sapphire/host/gatt/remote_characteristic.cc +++ b/pw_bluetooth_sapphire/host/gatt/remote_characteristic.cc @@ -29,8 +29,8 @@ RemoteCharacteristic::PendingNotifyRequest::PendingNotifyRequest( ValueCallback value_cb, NotifyStatusCallback status_cb) : value_callback(std::move(value_cb)), status_callback(std::move(status_cb)) { - BT_DEBUG_ASSERT(value_callback); - BT_DEBUG_ASSERT(status_callback); + PW_DCHECK(value_callback); + PW_DCHECK(status_callback); } RemoteCharacteristic::RemoteCharacteristic(Client::WeakPtr client, @@ -42,7 +42,7 @@ RemoteCharacteristic::RemoteCharacteristic(Client::WeakPtr client, next_notify_handler_id_(1u), client_(std::move(client)), weak_self_(this) { - BT_DEBUG_ASSERT(client_.is_alive()); + PW_DCHECK(client_.is_alive()); } RemoteCharacteristic::~RemoteCharacteristic() { @@ -77,9 +77,9 @@ void RemoteCharacteristic::UpdateDataWithExtendedProperties( void RemoteCharacteristic::DiscoverDescriptors( att::Handle range_end, att::ResultFunction<> discover_callback) { - BT_DEBUG_ASSERT(client_.is_alive()); - BT_DEBUG_ASSERT(discover_callback); - BT_DEBUG_ASSERT(range_end >= info().value_handle); + PW_DCHECK(client_.is_alive()); + PW_DCHECK(discover_callback); + PW_DCHECK(range_end >= info().value_handle); discovery_error_ = false; descriptors_.clear(); @@ -127,7 +127,7 @@ void RemoteCharacteristic::DiscoverDescriptors( // succeed auto [_unused, success] = self->descriptors_.try_emplace(DescriptorHandle(desc.handle), desc); - BT_DEBUG_ASSERT(success); + PW_DCHECK(success); }; auto status_cb = [self, discover_cb = std::move(discover_callback)]( @@ -190,9 +190,9 @@ void RemoteCharacteristic::DiscoverDescriptors( void RemoteCharacteristic::EnableNotifications( ValueCallback value_callback, NotifyStatusCallback status_callback) { - BT_DEBUG_ASSERT(client_.is_alive()); - BT_DEBUG_ASSERT(value_callback); - BT_DEBUG_ASSERT(status_callback); + PW_DCHECK(client_.is_alive()); + PW_DCHECK(value_callback); + PW_DCHECK(status_callback); if (!(info().properties & (Property::kNotify | Property::kIndicate))) { bt_log(DEBUG, "gatt", "characteristic does not support notifications"); @@ -202,7 +202,7 @@ void RemoteCharacteristic::EnableNotifications( // If notifications are already enabled then succeed right away. if (!notify_handlers_.empty()) { - BT_DEBUG_ASSERT(pending_notify_reqs_.empty()); + PW_DCHECK(pending_notify_reqs_.empty()); IdType id = next_notify_handler_id_++; notify_handlers_[id] = std::move(value_callback); @@ -251,7 +251,7 @@ void RemoteCharacteristic::EnableNotifications( } bool RemoteCharacteristic::DisableNotifications(IdType handler_id) { - BT_DEBUG_ASSERT(client_.is_alive()); + PW_DCHECK(client_.is_alive()); auto handler_iter = notify_handlers_.find(handler_id); if (handler_iter == notify_handlers_.end()) { @@ -322,7 +322,7 @@ void RemoteCharacteristic::ResolvePendingNotifyRequests(att::Result<> status) { void RemoteCharacteristic::HandleNotification(const ByteBuffer& value, bool maybe_truncated) { - BT_DEBUG_ASSERT(client_.is_alive()); + PW_DCHECK(client_.is_alive()); notifying_handlers_ = true; for (auto& iter : notify_handlers_) { diff --git a/pw_bluetooth_sapphire/host/gatt/remote_service.cc b/pw_bluetooth_sapphire/host/gatt/remote_service.cc index 0d3a2324f6..31ae8a9e99 100644 --- a/pw_bluetooth_sapphire/host/gatt/remote_service.cc +++ b/pw_bluetooth_sapphire/host/gatt/remote_service.cc @@ -60,7 +60,7 @@ RemoteService::RemoteService(const ServiceData& service_data, : service_data_(service_data), client_(std::move(client)), remaining_descriptor_requests_(kSentinel) { - BT_DEBUG_ASSERT(client_.is_alive()); + PW_DCHECK(client_.is_alive()); } RemoteService::~RemoteService() { @@ -151,7 +151,7 @@ void RemoteService::ReadCharacteristic(CharacteristicHandle id, ReadValueCallback callback) { RemoteCharacteristic* chrc; fit::result status = GetCharacteristic(id, &chrc); - BT_DEBUG_ASSERT(chrc || status.is_error()); + PW_DCHECK(chrc || status.is_error()); if (status.is_error()) { ReportReadValueError(status, std::move(callback)); return; @@ -173,7 +173,7 @@ void RemoteService::ReadLongCharacteristic(CharacteristicHandle id, ReadValueCallback callback) { RemoteCharacteristic* chrc; fit::result status = GetCharacteristic(id, &chrc); - BT_DEBUG_ASSERT(chrc || status.is_error()); + PW_DCHECK(chrc || status.is_error()); if (status.is_error()) { ReportReadValueError(status, std::move(callback)); return; @@ -233,7 +233,7 @@ void RemoteService::WriteCharacteristic(CharacteristicHandle id, att::ResultFunction<> cb) { RemoteCharacteristic* chrc; fit::result status = GetCharacteristic(id, &chrc); - BT_DEBUG_ASSERT(chrc || status.is_error()); + PW_DCHECK(chrc || status.is_error()); if (status.is_error()) { cb(status); return; @@ -257,7 +257,7 @@ void RemoteService::WriteLongCharacteristic(CharacteristicHandle id, att::ResultFunction<> callback) { RemoteCharacteristic* chrc; fit::result status = GetCharacteristic(id, &chrc); - BT_DEBUG_ASSERT(chrc || status.is_error()); + PW_DCHECK(chrc || status.is_error()); if (status.is_error()) { callback(status); return; @@ -292,7 +292,7 @@ void RemoteService::WriteCharacteristicWithoutResponse( att::ResultFunction<> cb) { RemoteCharacteristic* chrc; fit::result status = GetCharacteristic(id, &chrc); - BT_DEBUG_ASSERT(chrc || status.is_error()); + PW_DCHECK(chrc || status.is_error()); if (status.is_error()) { cb(status); return; @@ -316,7 +316,7 @@ void RemoteService::ReadDescriptor(DescriptorHandle id, ReadValueCallback callback) { const DescriptorData* desc; fit::result status = GetDescriptor(id, &desc); - BT_DEBUG_ASSERT(desc || status.is_error()); + PW_DCHECK(desc || status.is_error()); if (status.is_error()) { ReportReadValueError(status, std::move(callback)); return; @@ -331,7 +331,7 @@ void RemoteService::ReadLongDescriptor(DescriptorHandle id, ReadValueCallback callback) { const DescriptorData* desc; att::Result<> status = GetDescriptor(id, &desc); - BT_DEBUG_ASSERT(desc || status.is_error()); + PW_DCHECK(desc || status.is_error()); if (status.is_error()) { ReportReadValueError(status, std::move(callback)); return; @@ -364,7 +364,7 @@ void RemoteService::WriteDescriptor(DescriptorHandle id, att::ResultFunction<> callback) { const DescriptorData* desc; fit::result status = GetDescriptor(id, &desc); - BT_DEBUG_ASSERT(desc || status.is_error()); + PW_DCHECK(desc || status.is_error()); if (status.is_error()) { callback(status); return; @@ -388,7 +388,7 @@ void RemoteService::WriteLongDescriptor(DescriptorHandle id, att::ResultFunction<> callback) { const DescriptorData* desc; fit::result status = GetDescriptor(id, &desc); - BT_DEBUG_ASSERT(desc || status.is_error()); + PW_DCHECK(desc || status.is_error()); if (status.is_error()) { callback(status); return; @@ -415,7 +415,7 @@ void RemoteService::EnableNotifications(CharacteristicHandle id, NotifyStatusCallback status_callback) { RemoteCharacteristic* chrc; fit::result status = GetCharacteristic(id, &chrc); - BT_DEBUG_ASSERT(chrc || status.is_error()); + PW_DCHECK(chrc || status.is_error()); if (status.is_error()) { status_callback(status, kInvalidId); return; @@ -430,7 +430,7 @@ void RemoteService::DisableNotifications( att::ResultFunction<> status_callback) { RemoteCharacteristic* chrc; fit::result status = GetCharacteristic(id, &chrc); - BT_DEBUG_ASSERT(chrc || status.is_error()); + PW_DCHECK(chrc || status.is_error()); if (status.is_ok() && !chrc->DisableNotifications(handler_id)) { status = ToResult(HostError::kNotFound); } @@ -438,9 +438,9 @@ void RemoteService::DisableNotifications( } void RemoteService::StartDescriptorDiscovery() { - BT_DEBUG_ASSERT(!pending_discov_reqs_.empty()); + PW_DCHECK(!pending_discov_reqs_.empty()); - BT_ASSERT(!characteristics_.empty()); + PW_CHECK(!characteristics_.empty()); remaining_descriptor_requests_ = characteristics_.size(); auto self = GetWeakPtr(); @@ -468,11 +468,11 @@ void RemoteService::StartDescriptorDiscovery() { } // HasCharacteristics() should return true now. - BT_DEBUG_ASSERT(self->HasCharacteristics()); + PW_DCHECK(self->HasCharacteristics()); // Fall through and notify clients below. } else { - BT_DEBUG_ASSERT(!self->HasCharacteristics()); + PW_DCHECK(!self->HasCharacteristics()); bt_log(DEBUG, "gatt", "descriptor discovery failed %s", bt_str(status)); self->characteristics_.clear(); @@ -498,14 +498,14 @@ void RemoteService::StartDescriptorDiscovery() { end_handle = next->second.info().handle - 1; } - BT_DEBUG_ASSERT(client_.is_alive()); + PW_DCHECK(client_.is_alive()); iter->second.DiscoverDescriptors(end_handle, desc_done_callback); } } fit::result> RemoteService::GetCharacteristic( CharacteristicHandle id, RemoteCharacteristic** out_char) { - BT_DEBUG_ASSERT(out_char); + PW_DCHECK(out_char); if (!HasCharacteristics()) { *out_char = nullptr; @@ -524,7 +524,7 @@ fit::result> RemoteService::GetCharacteristic( fit::result> RemoteService::GetDescriptor( DescriptorHandle id, const DescriptorData** out_desc) { - BT_DEBUG_ASSERT(out_desc); + PW_DCHECK(out_desc); if (!HasCharacteristics()) { *out_desc = nullptr; @@ -551,8 +551,8 @@ fit::result> RemoteService::GetDescriptor( } void RemoteService::CompleteCharacteristicDiscovery(att::Result<> status) { - BT_DEBUG_ASSERT(!pending_discov_reqs_.empty()); - BT_DEBUG_ASSERT(status.is_error() || remaining_descriptor_requests_ == 0u); + PW_DCHECK(!pending_discov_reqs_.empty()); + PW_DCHECK(status.is_error() || remaining_descriptor_requests_ == 0u); // We return a new copy of only the immutable data of our characteristics and // their descriptors. This requires a copy, which *could* be expensive in the @@ -598,8 +598,8 @@ void RemoteService::ReadLongHelper(att::Handle value_handle, MutableByteBufferPtr out_buffer, size_t bytes_read, ReadValueCallback callback) { - BT_DEBUG_ASSERT(callback); - BT_DEBUG_ASSERT(out_buffer); + PW_DCHECK(callback); + PW_DCHECK(out_buffer); auto self = GetWeakPtr(); auto read_cb = [self, @@ -635,7 +635,7 @@ void RemoteService::ReadLongHelper(att::Handle value_handle, // Copy the blob into our |buffer|. |blob| may be truncated depending on the // size of |buffer|. - BT_ASSERT(bytes_read < buffer->size()); + PW_CHECK(bytes_read < buffer->size()); size_t copy_size = std::min(blob.size(), buffer->size() - bytes_read); bool truncated_by_max_bytes = (blob.size() != copy_size); buffer->Write(blob.view(0, copy_size), bytes_read); @@ -643,7 +643,7 @@ void RemoteService::ReadLongHelper(att::Handle value_handle, // We are done if the read was not truncated by the MTU or we have read the // maximum number of bytes requested. - BT_ASSERT(bytes_read <= buffer->size()); + PW_CHECK(bytes_read <= buffer->size()); if (!maybe_truncated_by_mtu || bytes_read == buffer->size()) { cb(fit::ok(), buffer->view(0, bytes_read), @@ -758,7 +758,7 @@ void RemoteService::ReadByTypeHelper( const std::vector& values = result.value(); // Client already checks for invalid response where status is success but no // values are returned. - BT_ASSERT(!values.empty()); + PW_CHECK(!values.empty()); // Convert and accumulate values. for (const auto& val : values) { diff --git a/pw_bluetooth_sapphire/host/gatt/remote_service_manager.cc b/pw_bluetooth_sapphire/host/gatt/remote_service_manager.cc index 9d8c5019f2..83740ce5f4 100644 --- a/pw_bluetooth_sapphire/host/gatt/remote_service_manager.cc +++ b/pw_bluetooth_sapphire/host/gatt/remote_service_manager.cc @@ -25,7 +25,7 @@ namespace bt::gatt::internal { RemoteServiceManager::ServiceListRequest::ServiceListRequest( ServiceListCallback callback, const std::vector& uuids) : callback_(std::move(callback)), uuids_(uuids) { - BT_DEBUG_ASSERT(callback_); + PW_DCHECK(callback_); } void RemoteServiceManager::ServiceListRequest::Complete( @@ -54,7 +54,7 @@ void RemoteServiceManager::ServiceListRequest::Complete( RemoteServiceManager::RemoteServiceManager(std::unique_ptr client) : client_(std::move(client)), initialized_(false), weak_self_(this) { - BT_DEBUG_ASSERT(client_); + PW_DCHECK(client_); client_->SetNotificationHandler( fit::bind_member<&RemoteServiceManager::OnNotification>(this)); @@ -220,7 +220,7 @@ void RemoteServiceManager::ConfigureServiceChangedNotifications( } RemoteService* profile_service = self->GattProfileService(); - BT_ASSERT(profile_service); + PW_CHECK(profile_service); auto svc_changed_char_iter = std::find_if( characteristics.begin(), @@ -293,7 +293,7 @@ void RemoteServiceManager::InitializeGattProfileService( } RemoteService* gatt_svc = self->GattProfileService(); - BT_ASSERT(gatt_svc); + PW_CHECK(gatt_svc); self->ConfigureServiceChangedNotifications( gatt_svc, [self, cb = std::move(callback)](att::Result<> config_status) { @@ -342,7 +342,7 @@ void RemoteServiceManager::DiscoverGattProfileService( UUID uuid = self->services_.begin()->second->uuid(); // The service UUID is filled in by Client based on the service discovery // request, so it should be the same as the requested UUID. - BT_ASSERT(uuid == types::kGenericAttributeService); + PW_CHECK(uuid == types::kGenericAttributeService); cb(fit::ok()); }; @@ -536,7 +536,7 @@ void RemoteServiceManager::OnNotification(bool /*indication*/, // If |value_handle| is within the previous service then we found it. auto& svc = iter->second; - BT_DEBUG_ASSERT(value_handle >= svc->handle()); + PW_DCHECK(value_handle >= svc->handle()); if (svc->info().range_end >= value_handle) { svc->HandleNotification(value_handle, value, maybe_truncated); @@ -618,13 +618,13 @@ void RemoteServiceManager::MaybeHandleNextServiceChangedNotification( auto self = weak_self_.GetWeakPtr(); ServiceCallback svc_cb = [self](const ServiceData& service_data) { if (self.is_alive()) { - BT_ASSERT(self->current_service_change_.has_value()); + PW_CHECK(self->current_service_change_.has_value()); // gatt::Client verifies that service discovery results are in the // requested range. - BT_ASSERT(service_data.range_start >= - self->current_service_change_->value.range_start_handle); - BT_ASSERT(service_data.range_start <= - self->current_service_change_->value.range_end_handle); + PW_CHECK(service_data.range_start >= + self->current_service_change_->value.range_start_handle); + PW_CHECK(service_data.range_start <= + self->current_service_change_->value.range_end_handle); self->current_service_change_->services.emplace(service_data.range_start, service_data); } @@ -640,7 +640,7 @@ void RemoteServiceManager::MaybeHandleNextServiceChangedNotification( WARN, "gatt", "service discovery for service changed notification failed")) { - BT_ASSERT(self->current_service_change_.has_value()); + PW_CHECK(self->current_service_change_.has_value()); self->ProcessServiceChangedDiscoveryResults( self->current_service_change_.value()); } @@ -708,7 +708,7 @@ void RemoteServiceManager::ProcessServiceChangedDiscoveryResults( auto new_service = std::make_unique(new_service_data, client_->GetWeakPtr()); - BT_ASSERT(new_service->handle() == service_iter->first); + PW_CHECK(new_service->handle() == service_iter->first); modified_services.push_back(new_service->GetWeakPtr()); service_iter->second = std::move(new_service); } @@ -721,9 +721,9 @@ void RemoteServiceManager::ProcessServiceChangedDiscoveryResults( added_services.push_back(service->GetWeakPtr()); auto [_, inserted] = services_.try_emplace(service->handle(), std::move(service)); - BT_ASSERT_MSG(inserted, - "service with handle (%#.4x) already exists", - service->handle()); + PW_CHECK(inserted, + "service with handle (%#.4x) already exists", + service->handle()); } // Skip notifying the service watcher callback during initialization as it diff --git a/pw_bluetooth_sapphire/host/gatt/remote_service_manager_test.cc b/pw_bluetooth_sapphire/host/gatt/remote_service_manager_test.cc index fdb0aedb50..99cd01f9c1 100644 --- a/pw_bluetooth_sapphire/host/gatt/remote_service_manager_test.cc +++ b/pw_bluetooth_sapphire/host/gatt/remote_service_manager_test.cc @@ -92,7 +92,7 @@ class RemoteServiceManagerTest : public pw::async::test::FakeDispatcherFixture { RunUntilIdle(); - BT_DEBUG_ASSERT(services.size() == 1u); + PW_DCHECK(services.size() == 1u); return services[0]; } @@ -109,7 +109,7 @@ class RemoteServiceManagerTest : public pw::async::test::FakeDispatcherFixture { RemoteService::WeakPtr service, std::vector fake_chrs, std::vector fake_descrs = std::vector()) { - BT_DEBUG_ASSERT(service.is_alive()); + PW_DCHECK(service.is_alive()); SetCharacteristicsAndDescriptors(std::move(fake_chrs), std::move(fake_descrs)); @@ -152,8 +152,8 @@ class RemoteServiceManagerTest : public pw::async::test::FakeDispatcherFixture { att::Result<>* out_status, IdType* out_id, RemoteService::ValueCallback callback = NopValueCallback) { - BT_DEBUG_ASSERT(out_status); - BT_DEBUG_ASSERT(out_id); + PW_DCHECK(out_status); + PW_DCHECK(out_id); service->EnableNotifications(chr_id, std::move(callback), [&](att::Result<> cb_status, IdType cb_id) { diff --git a/pw_bluetooth_sapphire/host/gatt/server.cc b/pw_bluetooth_sapphire/host/gatt/server.cc index 396d88ab8c..c86f5404fe 100644 --- a/pw_bluetooth_sapphire/host/gatt/server.cc +++ b/pw_bluetooth_sapphire/host/gatt/server.cc @@ -37,8 +37,8 @@ class AttBasedServer final : public Server { local_services_(std::move(local_services)), att_(std::move(bearer)), weak_self_(this) { - BT_ASSERT(local_services_.is_alive()); - BT_DEBUG_ASSERT(att_.is_alive()); + PW_CHECK(local_services_.is_alive()); + PW_DCHECK(att_.is_alive()); exchange_mtu_id_ = att_->RegisterHandler( att::kExchangeMTURequest, @@ -100,7 +100,7 @@ class AttBasedServer final : public Server { IndicationCallback indicate_callback) override { auto buffer = NewBuffer(sizeof(att::Header) + sizeof(att::Handle) + value.size()); - BT_ASSERT(buffer); + PW_CHECK(buffer); LocalServiceManager::ClientCharacteristicConfig config; if (!local_services_->GetCharacteristicConfig( @@ -165,7 +165,7 @@ class AttBasedServer final : public Server { // ATT protocol request handlers: void OnExchangeMTU(att::Bearer::TransactionId tid, const att::PacketReader& packet) { - BT_DEBUG_ASSERT(packet.opcode() == att::kExchangeMTURequest); + PW_DCHECK(packet.opcode() == att::kExchangeMTURequest); if (packet.payload_size() != sizeof(att::ExchangeMTURequestParams)) { att_->ReplyWithError( @@ -180,7 +180,7 @@ class AttBasedServer final : public Server { auto buffer = NewBuffer(sizeof(att::Header) + sizeof(att::ExchangeMTUResponseParams)); - BT_ASSERT(buffer); + PW_CHECK(buffer); att::PacketWriter writer(att::kExchangeMTUResponse, buffer.get()); auto rsp_params = writer.mutable_payload(); @@ -198,7 +198,7 @@ class AttBasedServer final : public Server { void OnFindInformation(att::Bearer::TransactionId tid, const att::PacketReader& packet) { - BT_DEBUG_ASSERT(packet.opcode() == att::kFindInformationRequest); + PW_DCHECK(packet.opcode() == att::kFindInformationRequest); TRACE_DURATION("bluetooth", "gatt::Server::OnFindInformation"); if (packet.payload_size() != sizeof(att::FindInformationRequestParams)) { @@ -216,7 +216,7 @@ class AttBasedServer final : public Server { constexpr size_t kRspStructSize = sizeof(att::FindInformationResponseParams); constexpr size_t kHeaderSize = sizeof(att::Header) + kRspStructSize; - BT_DEBUG_ASSERT(kHeaderSize <= att_->mtu()); + PW_DCHECK(kHeaderSize <= att_->mtu()); if (start == att::kInvalidHandle || start > end) { att_->ReplyWithError(tid, start, att::ErrorCode::kInvalidHandle); @@ -231,7 +231,7 @@ class AttBasedServer final : public Server { std::list results; for (auto it = db()->GetIterator(start, end); !it.AtEnd(); it.Advance()) { const auto* attr = it.get(); - BT_DEBUG_ASSERT(attr); + PW_DCHECK(attr); // GATT does not allow 32-bit UUIDs size_t compact_size = attr->type().CompactSize(/*allow_32bit=*/false); @@ -253,12 +253,12 @@ class AttBasedServer final : public Server { return; } - BT_DEBUG_ASSERT(!results.empty()); + PW_DCHECK(!results.empty()); size_t pdu_size = kHeaderSize + entry_size * results.size(); auto buffer = NewBuffer(pdu_size); - BT_ASSERT(buffer); + PW_CHECK(buffer); att::PacketWriter writer(att::kFindInformationResponse, buffer.get()); auto rsp_params = @@ -285,7 +285,7 @@ class AttBasedServer final : public Server { void OnFindByTypeValueRequest(att::Bearer::TransactionId tid, const att::PacketReader& packet) { - BT_DEBUG_ASSERT(packet.opcode() == att::kFindByTypeValueRequest); + PW_DCHECK(packet.opcode() == att::kFindByTypeValueRequest); if (packet.payload_size() < sizeof(att::FindByTypeValueRequestParams)) { att_->ReplyWithError( @@ -322,7 +322,7 @@ class AttBasedServer final : public Server { // Filter for identical values for (; !iter.AtEnd(); iter.Advance()) { const auto* attr = iter.get(); - BT_DEBUG_ASSERT(attr); + PW_DCHECK(attr); // Only support static values for this Request type if (attr->value()) { @@ -342,7 +342,7 @@ class AttBasedServer final : public Server { constexpr size_t kRspStructSize = sizeof(att::HandlesInformationList); size_t pdu_size = sizeof(att::Header) + kRspStructSize * results.size(); auto buffer = NewBuffer(pdu_size); - BT_ASSERT(buffer); + PW_CHECK(buffer); att::PacketWriter writer(att::kFindByTypeValueResponse, buffer.get()); @@ -368,7 +368,7 @@ class AttBasedServer final : public Server { void OnReadByGroupType(att::Bearer::TransactionId tid, const att::PacketReader& packet) { - BT_DEBUG_ASSERT(packet.opcode() == att::kReadByGroupTypeRequest); + PW_DCHECK(packet.opcode() == att::kReadByGroupTypeRequest); TRACE_DURATION("bluetooth", "gatt::Server::OnReadByGroupType"); att::Handle start, end; @@ -406,7 +406,7 @@ class AttBasedServer final : public Server { constexpr size_t kRspStructSize = sizeof(att::ReadByGroupTypeResponseParams); constexpr size_t kHeaderSize = sizeof(att::Header) + kRspStructSize; - BT_DEBUG_ASSERT(kHeaderSize <= att_->mtu()); + PW_DCHECK(kHeaderSize <= att_->mtu()); size_t value_size; std::list results; @@ -425,19 +425,19 @@ class AttBasedServer final : public Server { return; } - BT_DEBUG_ASSERT(!results.empty()); + PW_DCHECK(!results.empty()); size_t entry_size = value_size + sizeof(att::AttributeGroupDataEntry); size_t pdu_size = kHeaderSize + entry_size * results.size(); - BT_DEBUG_ASSERT(pdu_size <= att_->mtu()); + PW_DCHECK(pdu_size <= att_->mtu()); auto buffer = NewBuffer(pdu_size); - BT_ASSERT(buffer); + PW_CHECK(buffer); att::PacketWriter writer(att::kReadByGroupTypeResponse, buffer.get()); auto params = writer.mutable_payload(); - BT_DEBUG_ASSERT(entry_size <= std::numeric_limits::max()); + PW_DCHECK(entry_size <= std::numeric_limits::max()); params->length = static_cast(entry_size); // Points to the next entry in the target PDU. @@ -461,7 +461,7 @@ class AttBasedServer final : public Server { void OnReadByType(att::Bearer::TransactionId tid, const att::PacketReader& packet) { - BT_DEBUG_ASSERT(packet.opcode() == att::kReadByTypeRequest); + PW_DCHECK(packet.opcode() == att::kReadByTypeRequest); TRACE_DURATION("bluetooth", "gatt::Server::OnReadByType"); att::Handle start, end; @@ -492,7 +492,7 @@ class AttBasedServer final : public Server { constexpr size_t kRspStructSize = sizeof(att::ReadByTypeResponseParams); constexpr size_t kHeaderSize = sizeof(att::Header) + kRspStructSize; - BT_DEBUG_ASSERT(kHeaderSize <= att_->mtu()); + PW_DCHECK(kHeaderSize <= att_->mtu()); size_t out_value_size; std::list results; @@ -511,12 +511,12 @@ class AttBasedServer final : public Server { return; } - BT_DEBUG_ASSERT(!results.empty()); + PW_DCHECK(!results.empty()); // If the value is dynamic, then delegate the read to any registered // handler. if (!results.front()->value()) { - BT_DEBUG_ASSERT(results.size() == 1u); + PW_DCHECK(results.size() == 1u); const size_t kMaxValueSize = std::min(att_->mtu() - kHeaderSize - sizeof(att::AttributeData), @@ -559,13 +559,13 @@ class AttBasedServer final : public Server { } size_t entry_size = sizeof(att::AttributeData) + out_value_size; - BT_DEBUG_ASSERT(entry_size <= std::numeric_limits::max()); + PW_DCHECK(entry_size <= std::numeric_limits::max()); size_t pdu_size = kHeaderSize + entry_size * results.size(); - BT_DEBUG_ASSERT(pdu_size <= att_->mtu()); + PW_DCHECK(pdu_size <= att_->mtu()); auto buffer = NewBuffer(pdu_size); - BT_ASSERT(buffer); + PW_CHECK(buffer); att::PacketWriter writer(att::kReadByTypeResponse, buffer.get()); auto params = writer.mutable_payload(); @@ -590,7 +590,7 @@ class AttBasedServer final : public Server { void OnReadBlobRequest(att::Bearer::TransactionId tid, const att::PacketReader& packet) { - BT_DEBUG_ASSERT(packet.opcode() == att::kReadBlobRequest); + PW_DCHECK(packet.opcode() == att::kReadBlobRequest); if (packet.payload_size() != sizeof(att::ReadBlobRequestParams)) { att_->ReplyWithError( @@ -633,7 +633,7 @@ class AttBasedServer final : public Server { size_t value_size = std::min(value.size(), self->att_->mtu() - kHeaderSize); auto buffer = NewBuffer(value_size + kHeaderSize); - BT_ASSERT(buffer); + PW_CHECK(buffer); att::PacketWriter writer(att::kReadBlobResponse, buffer.get()); writer.mutable_payload_data().Write(value.view(0, value_size)); @@ -661,7 +661,7 @@ class AttBasedServer final : public Server { void OnReadRequest(att::Bearer::TransactionId tid, const att::PacketReader& packet) { - BT_DEBUG_ASSERT(packet.opcode() == att::kReadRequest); + PW_DCHECK(packet.opcode() == att::kReadRequest); if (packet.payload_size() != sizeof(att::ReadRequestParams)) { att_->ReplyWithError( @@ -702,7 +702,7 @@ class AttBasedServer final : public Server { size_t value_size = std::min(value.size(), self->att_->mtu() - kHeaderSize); auto buffer = NewBuffer(value_size + kHeaderSize); - BT_ASSERT(buffer); + PW_CHECK(buffer); att::PacketWriter writer(att::kReadResponse, buffer.get()); writer.mutable_payload_data().Write(value.view(0, value_size)); @@ -723,7 +723,7 @@ class AttBasedServer final : public Server { void OnWriteCommand(att::Bearer::TransactionId tid, const att::PacketReader& packet) { - BT_DEBUG_ASSERT(packet.opcode() == att::kWriteCommand); + PW_DCHECK(packet.opcode() == att::kWriteCommand); if (packet.payload_size() < sizeof(att::WriteRequestParams)) { // Ignore if wrong size, no response allowed @@ -762,7 +762,7 @@ class AttBasedServer final : public Server { void OnWriteRequest(att::Bearer::TransactionId tid, const att::PacketReader& packet) { - BT_DEBUG_ASSERT(packet.opcode() == att::kWriteRequest); + PW_DCHECK(packet.opcode() == att::kWriteRequest); if (packet.payload_size() < sizeof(att::WriteRequestParams)) { att_->ReplyWithError( @@ -822,7 +822,7 @@ class AttBasedServer final : public Server { void OnPrepareWriteRequest(att::Bearer::TransactionId tid, const att::PacketReader& packet) { - BT_DEBUG_ASSERT(packet.opcode() == att::kPrepareWriteRequest); + PW_DCHECK(packet.opcode() == att::kPrepareWriteRequest); if (packet.payload_size() < sizeof(att::PrepareWriteRequestParams)) { att_->ReplyWithError( @@ -870,7 +870,7 @@ class AttBasedServer final : public Server { void OnExecuteWriteRequest(att::Bearer::TransactionId tid, const att::PacketReader& packet) { - BT_DEBUG_ASSERT(packet.opcode() == att::kExecuteWriteRequest); + PW_DCHECK(packet.opcode() == att::kExecuteWriteRequest); if (packet.payload_size() != sizeof(att::ExecuteWriteRequestParams)) { att_->ReplyWithError( @@ -937,8 +937,8 @@ class AttBasedServer final : public Server { size_t entry_prefix_size, size_t* out_value_size, std::list* out_results) { - BT_DEBUG_ASSERT(out_results); - BT_DEBUG_ASSERT(out_value_size); + PW_DCHECK(out_results); + PW_DCHECK(out_value_size); if (start == att::kInvalidHandle || start > end) return fit::error(att::ErrorCode::kInvalidHandle); @@ -956,7 +956,7 @@ class AttBasedServer final : public Server { for (; !iter.AtEnd(); iter.Advance()) { const auto* attr = iter.get(); - BT_DEBUG_ASSERT(attr); + PW_DCHECK(attr); fit::result security_result = att::CheckReadPermissions(attr->read_reqs(), att_->security()); diff --git a/pw_bluetooth_sapphire/host/gatt/server_test.cc b/pw_bluetooth_sapphire/host/gatt/server_test.cc index d8a707925f..e9e0479085 100644 --- a/pw_bluetooth_sapphire/host/gatt/server_test.cc +++ b/pw_bluetooth_sapphire/host/gatt/server_test.cc @@ -149,7 +149,7 @@ class ServerTest : public l2cap::testing::MockChannelTest { state = kSearching; } else if (state == kCorrectChrcUuidFound && attr.type() == types::kClientCharacteristicConfig) { - BT_ASSERT(matching_chrc_value_handle != att::kInvalidHandle); + PW_CHECK(matching_chrc_value_handle != att::kInvalidHandle); DynamicByteBuffer new_ccc(sizeof(ccc_val)); new_ccc.WriteObj(ccc_val); fit::result write_status = diff --git a/pw_bluetooth_sapphire/host/hci/acl_connection.cc b/pw_bluetooth_sapphire/host/hci/acl_connection.cc index bece174eb1..71e75ae0fa 100644 --- a/pw_bluetooth_sapphire/host/hci/acl_connection.cc +++ b/pw_bluetooth_sapphire/host/hci/acl_connection.cc @@ -88,7 +88,7 @@ void AclConnection::OnDisconnectionComplete(hci_spec::ConnectionHandle handle, CommandChannel::EventCallbackResult AclConnection::OnEncryptionChangeEvent( const EmbossEventPacket& event) { - BT_ASSERT(event.event_code() == hci_spec::kEncryptionChangeEventCode); + PW_CHECK(event.event_code() == hci_spec::kEncryptionChangeEventCode); auto params = event diff --git a/pw_bluetooth_sapphire/host/hci/advertising_handle_map.cc b/pw_bluetooth_sapphire/host/hci/advertising_handle_map.cc index 03141f4f92..4be80db91d 100644 --- a/pw_bluetooth_sapphire/host/hci/advertising_handle_map.cc +++ b/pw_bluetooth_sapphire/host/hci/advertising_handle_map.cc @@ -28,7 +28,7 @@ std::optional AdvertisingHandleMap::MapHandle( } std::optional handle = NextHandle(); - BT_ASSERT(handle); + PW_CHECK(handle); addr_to_handle_[{address, extended_pdu}] = handle.value(); handle_to_addr_[handle.value()] = {address, extended_pdu}; @@ -80,12 +80,12 @@ void AdvertisingHandleMap::RemoveAddress(const DeviceAddress& address, } std::size_t AdvertisingHandleMap::Size() const { - BT_ASSERT(addr_to_handle_.size() == handle_to_addr_.size()); + PW_CHECK(addr_to_handle_.size() == handle_to_addr_.size()); return addr_to_handle_.size(); } bool AdvertisingHandleMap::Empty() const { - BT_ASSERT(addr_to_handle_.empty() == handle_to_addr_.empty()); + PW_CHECK(addr_to_handle_.empty() == handle_to_addr_.empty()); return addr_to_handle_.empty(); } diff --git a/pw_bluetooth_sapphire/host/hci/android_extended_low_energy_advertiser.cc b/pw_bluetooth_sapphire/host/hci/android_extended_low_energy_advertiser.cc index e360cd0f87..64ce8def5d 100644 --- a/pw_bluetooth_sapphire/host/hci/android_extended_low_energy_advertiser.cc +++ b/pw_bluetooth_sapphire/host/hci/android_extended_low_energy_advertiser.cc @@ -65,7 +65,7 @@ EmbossCommandPacket AndroidExtendedLowEnergyAdvertiser::BuildEnablePacket( bool extended_pdu) { std::optional handle = advertising_handle_map_.GetHandle(address, extended_pdu); - BT_ASSERT(handle); + PW_CHECK(handle); auto packet = hci::EmbossCommandPacket::New< android_emb::LEMultiAdvtEnableCommandWriter>(android_hci::kLEMultiAdvt); @@ -133,7 +133,7 @@ AndroidExtendedLowEnergyAdvertiser::BuildSetAdvertisingData( std::optional handle = advertising_handle_map_.GetHandle(address, extended_pdu); - BT_ASSERT(handle); + PW_CHECK(handle); uint8_t adv_data_length = static_cast(data.CalculateBlockSize(/*include_flags=*/true)); @@ -167,7 +167,7 @@ AndroidExtendedLowEnergyAdvertiser::BuildUnsetAdvertisingData( const DeviceAddress& address, bool extended_pdu) { std::optional handle = advertising_handle_map_.GetHandle(address, extended_pdu); - BT_ASSERT(handle); + PW_CHECK(handle); size_t packet_size = android_emb::LEMultiAdvtSetAdvtDataCommandWriter::MinSizeInBytes().Read(); @@ -196,7 +196,7 @@ AndroidExtendedLowEnergyAdvertiser::BuildSetScanResponse( std::optional handle = advertising_handle_map_.GetHandle(address, extended_pdu); - BT_ASSERT(handle); + PW_CHECK(handle); uint8_t scan_rsp_length = static_cast(data.CalculateBlockSize()); size_t packet_size = @@ -227,7 +227,7 @@ EmbossCommandPacket AndroidExtendedLowEnergyAdvertiser::BuildUnsetScanResponse( const DeviceAddress& address, bool extended_pdu) { std::optional handle = advertising_handle_map_.GetHandle(address, extended_pdu); - BT_ASSERT(handle); + PW_CHECK(handle); size_t packet_size = android_emb::LEMultiAdvtSetScanRespDataCommandWriter::MinSizeInBytes() @@ -250,7 +250,7 @@ AndroidExtendedLowEnergyAdvertiser::BuildRemoveAdvertisingSet( const DeviceAddress& address, bool extended_pdu) { std::optional handle = advertising_handle_map_.GetHandle(address, extended_pdu); - BT_ASSERT(handle); + PW_CHECK(handle); auto packet = hci::EmbossCommandPacket::New< android_emb::LEMultiAdvtEnableCommandWriter>(android_hci::kLEMultiAdvt); @@ -379,9 +379,9 @@ void AndroidExtendedLowEnergyAdvertiser::OnIncomingConnection( CommandChannel::EventCallbackResult AndroidExtendedLowEnergyAdvertiser::OnAdvertisingStateChangedSubevent( const EmbossEventPacket& event) { - BT_ASSERT(event.event_code() == hci_spec::kVendorDebugEventCode); - BT_ASSERT(event.view().subevent_code().Read() == - android_hci::kLEMultiAdvtStateChangeSubeventCode); + PW_CHECK(event.event_code() == hci_spec::kVendorDebugEventCode); + PW_CHECK(event.view().subevent_code().Read() == + android_hci::kLEMultiAdvtStateChangeSubeventCode); Result<> result = event.ToResult(); if (bt_is_error(result, diff --git a/pw_bluetooth_sapphire/host/hci/bredr_connection.cc b/pw_bluetooth_sapphire/host/hci/bredr_connection.cc index 0a9a8b3924..c288d6e385 100644 --- a/pw_bluetooth_sapphire/host/hci/bredr_connection.cc +++ b/pw_bluetooth_sapphire/host/hci/bredr_connection.cc @@ -25,10 +25,10 @@ BrEdrConnection::BrEdrConnection(hci_spec::ConnectionHandle handle, const Transport::WeakPtr& hci) : AclConnection(handle, local_address, peer_address, role, hci), WeakSelf(this) { - BT_ASSERT(local_address.type() == DeviceAddress::Type::kBREDR); - BT_ASSERT(peer_address.type() == DeviceAddress::Type::kBREDR); - BT_ASSERT(hci.is_alive()); - BT_ASSERT(hci->acl_data_channel()); + PW_CHECK(local_address.type() == DeviceAddress::Type::kBREDR); + PW_CHECK(peer_address.type() == DeviceAddress::Type::kBREDR); + PW_CHECK(hci.is_alive()); + PW_CHECK(hci->acl_data_channel()); } bool BrEdrConnection::StartEncryption() { @@ -37,7 +37,7 @@ bool BrEdrConnection::StartEncryption() { return false; } - BT_ASSERT(ltk().has_value() == ltk_type_.has_value()); + PW_CHECK(ltk().has_value() == ltk_type_.has_value()); if (!ltk().has_value()) { bt_log( DEBUG, @@ -118,7 +118,7 @@ void BrEdrConnection::HandleEncryptionStatusValidated(Result result) { void BrEdrConnection::ValidateEncryptionKeySize( hci::ResultFunction<> key_size_validity_cb) { - BT_ASSERT(state() == Connection::State::kConnected); + PW_CHECK(state() == Connection::State::kConnected); auto cmd = EmbossCommandPacket::New< pw::bluetooth::emboss::ReadEncryptionKeySizeCommandWriter>( diff --git a/pw_bluetooth_sapphire/host/hci/bredr_connection_request.cc b/pw_bluetooth_sapphire/host/hci/bredr_connection_request.cc index c12615694b..c68c3b3549 100644 --- a/pw_bluetooth_sapphire/host/hci/bredr_connection_request.cc +++ b/pw_bluetooth_sapphire/host/hci/bredr_connection_request.cc @@ -66,7 +66,7 @@ void BrEdrConnectionRequest::CreateConnection( page_scan_repetition_mode, pw::chrono::SystemClock::duration timeout, OnCompleteDelegate on_command_fail) { - BT_DEBUG_ASSERT(timeout.count() > 0); + PW_DCHECK(timeout.count() > 0); // HCI Command Status Event will be sent as our completion callback. auto self = weak_self_.GetWeakPtr(); @@ -75,7 +75,7 @@ void BrEdrConnectionRequest::CreateConnection( peer_id = peer_id_, on_command_fail_cb = std::move(on_command_fail)]( auto, const EventPacket& event) { - BT_DEBUG_ASSERT(event.event_code() == hci_spec::kCommandStatusEventCode); + PW_DCHECK(event.event_code() == hci_spec::kCommandStatusEventCode); if (!self.is_alive()) return; @@ -142,7 +142,7 @@ Result<> BrEdrConnectionRequest::CompleteRequest(Result<> status) { void BrEdrConnectionRequest::Timeout() { // If the request was cancelled, this handler will have been removed - BT_ASSERT(state_ == RequestState::kPending); + PW_CHECK(state_ == RequestState::kPending); bt_log(INFO, "hci-bredr", "create connection timed out: canceling request (peer: %s)", diff --git a/pw_bluetooth_sapphire/host/hci/connection.cc b/pw_bluetooth_sapphire/host/hci/connection.cc index 1dfbaed66a..f9a925c49d 100644 --- a/pw_bluetooth_sapphire/host/hci/connection.cc +++ b/pw_bluetooth_sapphire/host/hci/connection.cc @@ -41,7 +41,7 @@ Connection::Connection(hci_spec::ConnectionHandle handle, conn_state_(State::kConnected), hci_(std::move(hci)), weak_self_(this) { - BT_ASSERT(hci_.is_alive()); + PW_CHECK(hci_.is_alive()); auto disconn_complete_handler = [self = weak_self_.GetWeakPtr(), handle, @@ -75,7 +75,7 @@ CommandChannel::EventCallbackResult Connection::OnDisconnectionComplete( hci_spec::ConnectionHandle handle, const EmbossEventPacket& event, fit::callback on_disconnection_complete) { - BT_ASSERT(event.event_code() == hci_spec::kDisconnectionCompleteEventCode); + PW_CHECK(event.event_code() == hci_spec::kDisconnectionCompleteEventCode); auto view = event.view(); @@ -119,13 +119,13 @@ CommandChannel::EventCallbackResult Connection::OnDisconnectionComplete( } void Connection::Disconnect(pw::bluetooth::emboss::StatusCode reason) { - BT_ASSERT(conn_state_ == Connection::State::kConnected); + PW_CHECK(conn_state_ == Connection::State::kConnected); conn_state_ = Connection::State::kWaitingForDisconnectionComplete; // Here we send a HCI_Disconnect command without waiting for it to complete. auto status_cb = [](auto id, const EventPacket& event) { - BT_DEBUG_ASSERT(event.event_code() == hci_spec::kCommandStatusEventCode); + PW_DCHECK(event.event_code() == hci_spec::kCommandStatusEventCode); hci_is_error(event, TRACE, "hci", "ignoring disconnection failure"); }; diff --git a/pw_bluetooth_sapphire/host/hci/extended_low_energy_advertiser.cc b/pw_bluetooth_sapphire/host/hci/extended_low_energy_advertiser.cc index 59ae7d9ed0..f92e840d00 100644 --- a/pw_bluetooth_sapphire/host/hci/extended_low_energy_advertiser.cc +++ b/pw_bluetooth_sapphire/host/hci/extended_low_energy_advertiser.cc @@ -64,7 +64,7 @@ EmbossCommandPacket ExtendedLowEnergyAdvertiser::BuildEnablePacket( std::optional handle = advertising_handle_map_.GetHandle(address, extended_pdu); - BT_ASSERT(handle); + PW_CHECK(handle); view.data()[0].advertising_handle().Write(handle.value()); view.data()[0].duration().Write(hci_spec::kNoAdvertisingDuration); @@ -239,7 +239,7 @@ ExtendedLowEnergyAdvertiser::BuildSetAdvertisingData( std::optional handle = advertising_handle_map_.GetHandle(address, extended_pdu); - BT_ASSERT(handle); + PW_CHECK(handle); size_t block_size = adv_data.CalculateBlockSize(/*include_flags=*/true); DynamicByteBuffer buffer(block_size); @@ -316,7 +316,7 @@ EmbossCommandPacket ExtendedLowEnergyAdvertiser::BuildUnsetAdvertisingData( // advertising handle std::optional handle = advertising_handle_map_.GetHandle(address, extended_pdu); - BT_ASSERT(handle); + PW_CHECK(handle); payload.advertising_handle().Write(handle.value()); payload.operation().Write(pwemb::LESetExtendedAdvDataOp::COMPLETE); @@ -344,7 +344,7 @@ ExtendedLowEnergyAdvertiser::BuildSetScanResponse(const DeviceAddress& address, std::optional handle = advertising_handle_map_.GetHandle(address, extended_pdu); - BT_ASSERT(handle); + PW_CHECK(handle); size_t block_size = scan_rsp.CalculateBlockSize(/*include_flags=*/false); DynamicByteBuffer buffer(block_size); @@ -421,7 +421,7 @@ EmbossCommandPacket ExtendedLowEnergyAdvertiser::BuildUnsetScanResponse( // advertising handle std::optional handle = advertising_handle_map_.GetHandle(address, extended_pdu); - BT_ASSERT(handle); + PW_CHECK(handle); payload.advertising_handle().Write(handle.value()); payload.operation().Write(pwemb::LESetExtendedAdvDataOp::COMPLETE); @@ -436,7 +436,7 @@ EmbossCommandPacket ExtendedLowEnergyAdvertiser::BuildRemoveAdvertisingSet( const DeviceAddress& address, bool extended_pdu) { std::optional handle = advertising_handle_map_.GetHandle(address, extended_pdu); - BT_ASSERT(handle); + PW_CHECK(handle); auto packet = hci::EmbossCommandPacket::New( hci_spec::kLERemoveAdvertisingSet); @@ -449,12 +449,12 @@ EmbossCommandPacket ExtendedLowEnergyAdvertiser::BuildRemoveAdvertisingSet( void ExtendedLowEnergyAdvertiser::OnSetAdvertisingParamsComplete( const EmbossEventPacket& event) { auto event_view = event.view(); - BT_ASSERT(event_view.event_code_enum().Read() == - pw::bluetooth::emboss::EventCode::COMMAND_COMPLETE); + PW_CHECK(event_view.event_code_enum().Read() == + pw::bluetooth::emboss::EventCode::COMMAND_COMPLETE); auto cmd_complete_view = event.view(); - BT_ASSERT( + PW_CHECK( cmd_complete_view.command_opcode_enum().Read() == pw::bluetooth::emboss::OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS_V1); diff --git a/pw_bluetooth_sapphire/host/hci/extended_low_energy_scanner.cc b/pw_bluetooth_sapphire/host/hci/extended_low_energy_scanner.cc index 899271bb5e..f3896224af 100644 --- a/pw_bluetooth_sapphire/host/hci/extended_low_energy_scanner.cc +++ b/pw_bluetooth_sapphire/host/hci/extended_low_energy_scanner.cc @@ -57,10 +57,10 @@ ExtendedLowEnergyScanner::~ExtendedLowEnergyScanner() { bool ExtendedLowEnergyScanner::StartScan(const ScanOptions& options, ScanStatusCallback callback) { - BT_ASSERT(options.interval >= hci_spec::kLEExtendedScanIntervalMin); - BT_ASSERT(options.interval <= hci_spec::kLEExtendedScanIntervalMax); - BT_ASSERT(options.window >= hci_spec::kLEExtendedScanIntervalMin); - BT_ASSERT(options.window <= hci_spec::kLEExtendedScanIntervalMax); + PW_CHECK(options.interval >= hci_spec::kLEExtendedScanIntervalMin); + PW_CHECK(options.interval <= hci_spec::kLEExtendedScanIntervalMax); + PW_CHECK(options.window >= hci_spec::kLEExtendedScanIntervalMin); + PW_CHECK(options.window <= hci_spec::kLEExtendedScanIntervalMax); return LowEnergyScanner::StartScan(options, std::move(callback)); } @@ -135,9 +135,9 @@ EmbossCommandPacket ExtendedLowEnergyScanner::BuildEnablePacket( std::vector ExtendedLowEnergyScanner::ParseAdvertisingReports( const EmbossEventPacket& event) { - BT_DEBUG_ASSERT(event.event_code() == hci_spec::kLEMetaEventCode); - BT_DEBUG_ASSERT(event.view().subevent_code().Read() == - hci_spec::kLEExtendedAdvertisingReportSubeventCode); + PW_DCHECK(event.event_code() == hci_spec::kLEMetaEventCode); + PW_DCHECK(event.view().subevent_code().Read() == + hci_spec::kLEExtendedAdvertisingReportSubeventCode); size_t reports_size = event.size() - pw::bluetooth::emboss::LEExtendedAdvertisingReportSubeventView:: @@ -186,7 +186,7 @@ static std::tuple BuildDeviceAddress( LEExtendedAddressType report_type, BdAddrView address_view) { std::optional address_type = DeviceAddress::LeAddrToDeviceAddr(report_type); - BT_DEBUG_ASSERT(address_type); + PW_DCHECK(address_type); bool resolved = false; switch (report_type) { diff --git a/pw_bluetooth_sapphire/host/hci/fake_bredr_connection.cc b/pw_bluetooth_sapphire/host/hci/fake_bredr_connection.cc index 7a828c52d5..dbce7860f2 100644 --- a/pw_bluetooth_sapphire/host/hci/fake_bredr_connection.cc +++ b/pw_bluetooth_sapphire/host/hci/fake_bredr_connection.cc @@ -26,7 +26,7 @@ FakeBrEdrConnection::FakeBrEdrConnection( void FakeBrEdrConnection::TriggerEncryptionChangeCallback( hci::Result result) { - BT_ASSERT(encryption_change_callback()); + PW_CHECK(encryption_change_callback()); encryption_change_callback()(result); } diff --git a/pw_bluetooth_sapphire/host/hci/fake_local_address_delegate.cc b/pw_bluetooth_sapphire/host/hci/fake_local_address_delegate.cc index a987112bc4..ef12e2ff57 100644 --- a/pw_bluetooth_sapphire/host/hci/fake_local_address_delegate.cc +++ b/pw_bluetooth_sapphire/host/hci/fake_local_address_delegate.cc @@ -17,7 +17,7 @@ namespace bt::hci { void FakeLocalAddressDelegate::EnsureLocalAddress(AddressCallback callback) { - BT_DEBUG_ASSERT(callback); + PW_DCHECK(callback); if (!async_) { callback(local_address_); return; diff --git a/pw_bluetooth_sapphire/host/hci/fake_low_energy_connection.cc b/pw_bluetooth_sapphire/host/hci/fake_low_energy_connection.cc index fcea994e03..f8944ed1c7 100644 --- a/pw_bluetooth_sapphire/host/hci/fake_low_energy_connection.cc +++ b/pw_bluetooth_sapphire/host/hci/fake_low_energy_connection.cc @@ -31,7 +31,7 @@ FakeLowEnergyConnection::FakeLowEnergyConnection( void FakeLowEnergyConnection::TriggerEncryptionChangeCallback( hci::Result result) { - BT_ASSERT(encryption_change_callback()); + PW_CHECK(encryption_change_callback()); encryption_change_callback()(result); } diff --git a/pw_bluetooth_sapphire/host/hci/legacy_low_energy_advertiser.cc b/pw_bluetooth_sapphire/host/hci/legacy_low_energy_advertiser.cc index acb87c26ee..bdef67156c 100644 --- a/pw_bluetooth_sapphire/host/hci/legacy_low_energy_advertiser.cc +++ b/pw_bluetooth_sapphire/host/hci/legacy_low_energy_advertiser.cc @@ -245,7 +245,7 @@ void LegacyLowEnergyAdvertiser::StartAdvertising( // |starting_| was reset or the |result_callback| was moved), return early. if (options.include_tx_power_level) { auto power_cb = [this](auto, const hci::EmbossEventPacket& event) mutable { - BT_ASSERT(staged_params_.has_value()); + PW_CHECK(staged_params_.has_value()); if (!starting_ || !staged_params_.value().result_callback) { bt_log( INFO, "hci-le", "Advertising canceled during TX Power Level read."); diff --git a/pw_bluetooth_sapphire/host/hci/legacy_low_energy_scanner.cc b/pw_bluetooth_sapphire/host/hci/legacy_low_energy_scanner.cc index d9f7f59fbe..a2eb67a82a 100644 --- a/pw_bluetooth_sapphire/host/hci/legacy_low_energy_scanner.cc +++ b/pw_bluetooth_sapphire/host/hci/legacy_low_energy_scanner.cc @@ -54,10 +54,10 @@ LegacyLowEnergyScanner::~LegacyLowEnergyScanner() { bool LegacyLowEnergyScanner::StartScan(const ScanOptions& options, ScanStatusCallback callback) { - BT_ASSERT(options.interval >= hci_spec::kLEScanIntervalMin); - BT_ASSERT(options.interval <= hci_spec::kLEScanIntervalMax); - BT_ASSERT(options.window >= hci_spec::kLEScanIntervalMin); - BT_ASSERT(options.window <= hci_spec::kLEScanIntervalMax); + PW_CHECK(options.interval >= hci_spec::kLEScanIntervalMin); + PW_CHECK(options.interval <= hci_spec::kLEScanIntervalMax); + PW_CHECK(options.window >= hci_spec::kLEScanIntervalMin); + PW_CHECK(options.window <= hci_spec::kLEScanIntervalMax); return LowEnergyScanner::StartScan(options, std::move(callback)); } @@ -117,7 +117,7 @@ void LegacyLowEnergyScanner::HandleScanResponse(const DeviceAddress& address, return; } - BT_DEBUG_ASSERT(address == pending->result().address()); + PW_DCHECK(address == pending->result().address()); pending->result().AppendData(data); pending->result().set_resolved(resolved); pending->result().set_rssi(rssi); @@ -133,10 +133,10 @@ void LegacyLowEnergyScanner::HandleScanResponse(const DeviceAddress& address, std::vector LegacyLowEnergyScanner::ParseAdvertisingReports( const EmbossEventPacket& event) { - BT_DEBUG_ASSERT(event.event_code() == hci_spec::kLEMetaEventCode); - BT_DEBUG_ASSERT(event.view() - .subevent_code() - .Read() == hci_spec::kLEAdvertisingReportSubeventCode); + PW_DCHECK(event.event_code() == hci_spec::kLEMetaEventCode); + PW_DCHECK(event.view() + .subevent_code() + .Read() == hci_spec::kLEAdvertisingReportSubeventCode); auto params = event.view(); @@ -183,7 +183,7 @@ static std::tuple BuildDeviceAddress( pw::bluetooth::emboss::BdAddrView address_view) { std::optional address_type = DeviceAddress::LeAddrToDeviceAddr(report_type); - BT_DEBUG_ASSERT(address_type); + PW_DCHECK(address_type); bool resolved = false; switch (report_type) { diff --git a/pw_bluetooth_sapphire/host/hci/low_energy_advertiser.cc b/pw_bluetooth_sapphire/host/hci/low_energy_advertiser.cc index 7e94f9e706..c4750f71cb 100644 --- a/pw_bluetooth_sapphire/host/hci/low_energy_advertiser.cc +++ b/pw_bluetooth_sapphire/host/hci/low_energy_advertiser.cc @@ -59,7 +59,7 @@ fit::result LowEnergyAdvertiser::CanStartAdvertising( const AdvertisingData& scan_rsp, const AdvertisingOptions& options, const ConnectionCallback& connect_callback) const { - BT_ASSERT(address.type() != DeviceAddress::Type::kBREDR); + PW_CHECK(address.type() != DeviceAddress::Type::kBREDR); if (options.anonymous) { bt_log(WARN, "hci-le", "anonymous advertising not supported"); diff --git a/pw_bluetooth_sapphire/host/hci/low_energy_connection.cc b/pw_bluetooth_sapphire/host/hci/low_energy_connection.cc index 606f26197b..595884314b 100644 --- a/pw_bluetooth_sapphire/host/hci/low_energy_connection.cc +++ b/pw_bluetooth_sapphire/host/hci/low_energy_connection.cc @@ -32,9 +32,9 @@ LowEnergyConnection::LowEnergyConnection( : AclConnection(handle, local_address, peer_address, role, hci), WeakSelf(this), parameters_(params) { - BT_ASSERT(local_address.type() != DeviceAddress::Type::kBREDR); - BT_ASSERT(peer_address.type() != DeviceAddress::Type::kBREDR); - BT_ASSERT(hci.is_alive()); + PW_CHECK(local_address.type() != DeviceAddress::Type::kBREDR); + PW_CHECK(peer_address.type() != DeviceAddress::Type::kBREDR); + PW_CHECK(hci.is_alive()); le_ltk_request_id_ = hci->command_channel()->AddLEMetaEventHandler( hci_spec::kLELongTermKeyRequestSubeventCode, diff --git a/pw_bluetooth_sapphire/host/hci/low_energy_connector.cc b/pw_bluetooth_sapphire/host/hci/low_energy_connector.cc index c366236299..459f81500f 100644 --- a/pw_bluetooth_sapphire/host/hci/low_energy_connector.cc +++ b/pw_bluetooth_sapphire/host/hci/low_energy_connector.cc @@ -99,14 +99,14 @@ bool LowEnergyConnector::CreateConnection( const hci_spec::LEPreferredConnectionParameters& initial_parameters, StatusCallback status_callback, pw::chrono::SystemClock::duration timeout) { - BT_DEBUG_ASSERT(status_callback); - BT_DEBUG_ASSERT(timeout.count() > 0); + PW_DCHECK(status_callback); + PW_DCHECK(timeout.count() > 0); if (request_pending()) { return false; } - BT_DEBUG_ASSERT(!request_timeout_task_.is_pending()); + PW_DCHECK(!request_timeout_task_.is_pending()); pending_request_ = PendingRequest(peer_address, std::move(status_callback)); if (use_local_identity_address_) { @@ -176,7 +176,7 @@ void LowEnergyConnector::CreateConnectionInternal( return; } - BT_DEBUG_ASSERT(!pending_request_->initiating); + PW_DCHECK(!pending_request_->initiating); pending_request_->initiating = true; pending_request_->local_address = local_address; @@ -184,7 +184,7 @@ void LowEnergyConnector::CreateConnectionInternal( // HCI Command Status Event will be sent as our completion callback. auto self = weak_self_.GetWeakPtr(); auto complete_cb = [self, timeout](auto id, const EventPacket& event) { - BT_DEBUG_ASSERT(event.event_code() == hci_spec::kCommandStatusEventCode); + PW_DCHECK(event.event_code() == hci_spec::kCommandStatusEventCode); if (!self.is_alive()) { return; @@ -344,7 +344,7 @@ EmbossCommandPacket LowEnergyConnector::BuildCreateConnectionPacket( } void LowEnergyConnector::CancelInternal(bool timed_out) { - BT_DEBUG_ASSERT(request_pending()); + PW_DCHECK(request_pending()); if (pending_request_->canceled) { bt_log(WARN, "hci-le", "connection attempt already canceled!"); @@ -463,7 +463,7 @@ void LowEnergyConnector::OnConnectionCompleteEvent( void LowEnergyConnector::OnCreateConnectionComplete( Result<> result, std::unique_ptr link) { - BT_DEBUG_ASSERT(pending_request_); + PW_DCHECK(pending_request_); bt_log(DEBUG, "hci-le", "connection complete - status: %s", bt_str(result)); request_timeout_task_.Cancel(); @@ -475,7 +475,7 @@ void LowEnergyConnector::OnCreateConnectionComplete( } void LowEnergyConnector::OnCreateConnectionTimeout() { - BT_DEBUG_ASSERT(pending_request_); + PW_DCHECK(pending_request_); bt_log(INFO, "hci-le", "create connection timed out: canceling request"); // TODO(armansito): This should cancel the connection attempt only if the diff --git a/pw_bluetooth_sapphire/host/hci/low_energy_scanner.cc b/pw_bluetooth_sapphire/host/hci/low_energy_scanner.cc index de8f0e8dea..6ad58805dc 100644 --- a/pw_bluetooth_sapphire/host/hci/low_energy_scanner.cc +++ b/pw_bluetooth_sapphire/host/hci/low_energy_scanner.cc @@ -85,8 +85,8 @@ LowEnergyScanner::LowEnergyScanner(LocalAddressDelegate* local_addr_delegate, scan_timeout_task_(pw_dispatcher_), local_addr_delegate_(local_addr_delegate), hci_(std::move(hci)) { - BT_DEBUG_ASSERT(local_addr_delegate_); - BT_DEBUG_ASSERT(hci_.is_alive()); + PW_DCHECK(local_addr_delegate_); + PW_DCHECK(hci_.is_alive()); hci_cmd_runner_ = std::make_unique( hci_->command_channel()->AsWeakPtr()); @@ -124,8 +124,8 @@ LowEnergyScanner::RemovePendingResult(const DeviceAddress& address) { bool LowEnergyScanner::StartScan(const ScanOptions& options, ScanStatusCallback callback) { - BT_ASSERT(callback); - BT_ASSERT(options.window < options.interval); + PW_CHECK(callback); + PW_CHECK(options.window < options.interval); if (state_ != State::kIdle) { bt_log(ERROR, @@ -178,8 +178,8 @@ void LowEnergyScanner::StartScanInternal(const DeviceAddress& local_address, hci_cmd_runner_->RunCommands([this, active = options.active, period = options.period](Result<> status) { - BT_DEBUG_ASSERT(scan_cb_); - BT_DEBUG_ASSERT(state_ == State::kInitiating); + PW_DCHECK(scan_cb_); + PW_DCHECK(state_ == State::kInitiating); if (status.is_error()) { if (status == ToResult(HostError::kCanceled)) { @@ -231,7 +231,7 @@ bool LowEnergyScanner::StopScan() { } void LowEnergyScanner::StopScanInternal(bool stopped_by_user) { - BT_DEBUG_ASSERT(scan_cb_); + PW_DCHECK(scan_cb_); scan_timeout_task_.Cancel(); state_ = State::kStopping; @@ -247,7 +247,7 @@ void LowEnergyScanner::StopScanInternal(bool stopped_by_user) { // Either way clear all results from the previous scan period. pending_results_.clear(); - BT_DEBUG_ASSERT(hci_cmd_runner_->IsReady()); + PW_DCHECK(hci_cmd_runner_->IsReady()); // Tell the controller to stop scanning. ScanOptions options; @@ -256,8 +256,8 @@ void LowEnergyScanner::StopScanInternal(bool stopped_by_user) { hci_cmd_runner_->QueueCommand(std::move(command)); hci_cmd_runner_->RunCommands([this, stopped_by_user](Result<> status) { - BT_DEBUG_ASSERT(scan_cb_); - BT_DEBUG_ASSERT(state_ == State::kStopping); + PW_DCHECK(scan_cb_); + PW_DCHECK(state_ == State::kStopping); state_ = State::kIdle; // Something went wrong but there isn't really a meaningful way to recover, diff --git a/pw_bluetooth_sapphire/host/hci/sequential_command_runner.cc b/pw_bluetooth_sapphire/host/hci/sequential_command_runner.cc index eade4786e7..af71d1ed23 100644 --- a/pw_bluetooth_sapphire/host/hci/sequential_command_runner.cc +++ b/pw_bluetooth_sapphire/host/hci/sequential_command_runner.cc @@ -25,7 +25,7 @@ SequentialCommandRunner::SequentialCommandRunner( sequence_number_(0u), running_commands_(0u), weak_ptr_factory_(this) { - BT_DEBUG_ASSERT(cmd_.is_alive()); + PW_DCHECK(cmd_.is_alive()); } void SequentialCommandRunner::QueueCommand( @@ -66,9 +66,9 @@ void SequentialCommandRunner::QueueLeAsyncCommand( } void SequentialCommandRunner::RunCommands(ResultFunction<> status_callback) { - BT_DEBUG_ASSERT(!status_callback_); - BT_DEBUG_ASSERT(status_callback); - BT_DEBUG_ASSERT(!command_queue_.empty()); + PW_DCHECK(!status_callback_); + PW_DCHECK(status_callback); + PW_DCHECK(!command_queue_.empty()); status_callback_ = std::move(status_callback); sequence_number_++; @@ -87,7 +87,7 @@ bool SequentialCommandRunner::HasQueuedCommands() const { } void SequentialCommandRunner::TryRunNextQueuedCommand(Result<> status) { - BT_DEBUG_ASSERT(status_callback_); + PW_DCHECK(status_callback_); // If an error occurred or we're done, reset. if (status.is_error() || (command_queue_.empty() && running_commands_ == 0)) { @@ -170,7 +170,7 @@ void SequentialCommandRunner::TryRunNextQueuedCommand(Result<> status) { return; } - BT_DEBUG_ASSERT(self->running_commands_ > 0); + PW_DCHECK(self->running_commands_ > 0); self->running_commands_--; self->TryRunNextQueuedCommand(event_result); }; @@ -211,7 +211,7 @@ void SequentialCommandRunner::Reset() { } void SequentialCommandRunner::NotifyStatusAndReset(Result<> status) { - BT_DEBUG_ASSERT(status_callback_); + PW_DCHECK(status_callback_); auto status_cb = std::move(status_callback_); Reset(); status_cb(status); diff --git a/pw_bluetooth_sapphire/host/iso/iso_stream.cc b/pw_bluetooth_sapphire/host/iso/iso_stream.cc index c22d7dadd3..e4fbcd3260 100644 --- a/pw_bluetooth_sapphire/host/iso/iso_stream.cc +++ b/pw_bluetooth_sapphire/host/iso/iso_stream.cc @@ -99,7 +99,7 @@ IsoStreamImpl::IsoStreamImpl(uint8_t cig_id, on_closed_cb_(std::move(on_closed_cb)), cmd_(std::move(cmd)), weak_self_(this) { - BT_ASSERT(cmd_.is_alive()); + PW_CHECK(cmd_.is_alive()); auto weak_self = weak_self_.GetWeakPtr(); cis_established_handler_ = cmd_->AddLEMetaEventHandler( @@ -114,14 +114,14 @@ IsoStreamImpl::IsoStreamImpl(uint8_t cig_id, } return hci::CommandChannel::EventCallbackResult::kContinue; }); - BT_ASSERT(cis_established_handler_ != 0u); + PW_CHECK(cis_established_handler_ != 0u); } bool IsoStreamImpl::OnCisEstablished(const hci::EmbossEventPacket& event) { - BT_ASSERT(event.event_code() == hci_spec::kLEMetaEventCode); - BT_ASSERT(event.view() - .subevent_code() - .Read() == hci_spec::kLECISEstablishedSubeventCode); + PW_CHECK(event.event_code() == hci_spec::kLEMetaEventCode); + PW_CHECK(event.view() + .subevent_code() + .Read() == hci_spec::kLECISEstablishedSubeventCode); auto view = event.view(); // Ignore any events intended for another CIS diff --git a/pw_bluetooth_sapphire/host/iso/iso_stream_manager.cc b/pw_bluetooth_sapphire/host/iso/iso_stream_manager.cc index bdef8777ad..092ff2b4c4 100644 --- a/pw_bluetooth_sapphire/host/iso/iso_stream_manager.cc +++ b/pw_bluetooth_sapphire/host/iso/iso_stream_manager.cc @@ -19,9 +19,9 @@ namespace bt::iso { IsoStreamManager::IsoStreamManager(hci_spec::ConnectionHandle handle, hci::Transport::WeakPtr hci) : acl_handle_(handle), hci_(std::move(hci)), weak_self_(this) { - BT_ASSERT(hci_.is_alive()); + PW_CHECK(hci_.is_alive()); cmd_ = hci_->command_channel()->AsWeakPtr(); - BT_ASSERT(cmd_.is_alive()); + PW_CHECK(cmd_.is_alive()); auto weak_self = GetWeakPtr(); cis_request_handler_ = cmd_->AddLEMetaEventHandler( @@ -76,12 +76,12 @@ AcceptCisStatus IsoStreamManager::AcceptCis(CigCisIdentifier id, } void IsoStreamManager::OnCisRequest(const hci::EmbossEventPacket& event) { - BT_ASSERT(event.event_code() == hci_spec::kLEMetaEventCode); + PW_CHECK(event.event_code() == hci_spec::kLEMetaEventCode); auto event_view = event.view(); - BT_ASSERT(event_view.le_meta_event().subevent_code().Read() == - hci_spec::kLECISRequestSubeventCode); + PW_CHECK(event_view.le_meta_event().subevent_code().Read() == + hci_spec::kLECISRequestSubeventCode); hci_spec::ConnectionHandle request_handle = event_view.acl_connection_handle().Read(); @@ -117,8 +117,7 @@ void IsoStreamManager::OnCisRequest(const hci::EmbossEventPacket& event) { // We should not already have an established stream using this same CIG/CIS // permutation. - BT_ASSERT_MSG( - streams_.count(id) == 0, "(cig = %u, cis = %u)", cig_id, cis_id); + PW_CHECK(streams_.count(id) == 0, "(cig = %u, cis = %u)", cig_id, cis_id); CisEstablishedCallback cb = std::move(accept_handlers_[id]); accept_handlers_.erase(id); AcceptCisRequest(event_view, std::move(cb)); @@ -134,7 +133,7 @@ void IsoStreamManager::AcceptCisRequest( hci_spec::ConnectionHandle cis_handle = event_view.cis_connection_handle().Read(); - BT_ASSERT(streams_.count(id) == 0); + PW_CHECK(streams_.count(id) == 0); auto on_closed_cb = [this, id, cis_handle]() { if (hci_.is_alive()) { diff --git a/pw_bluetooth_sapphire/host/l2cap/a2dp_offload_manager.cc b/pw_bluetooth_sapphire/host/l2cap/a2dp_offload_manager.cc index a260245ac3..2affee35d5 100644 --- a/pw_bluetooth_sapphire/host/l2cap/a2dp_offload_manager.cc +++ b/pw_bluetooth_sapphire/host/l2cap/a2dp_offload_manager.cc @@ -40,7 +40,7 @@ void A2dpOffloadManager::StartA2dpOffload( hci_spec::ConnectionHandle link_handle, uint16_t max_tx_sdu_size, hci::ResultCallback<> callback) { - BT_DEBUG_ASSERT(cmd_channel_.is_alive()); + PW_DCHECK(cmd_channel_.is_alive()); switch (a2dp_offload_status_) { case A2dpOffloadStatus::kStarted: { @@ -175,7 +175,7 @@ void A2dpOffloadManager::RequestStopA2dpOffload( ChannelId local_id, hci_spec::ConnectionHandle link_handle, hci::ResultCallback<> callback) { - BT_DEBUG_ASSERT(cmd_channel_.is_alive()); + PW_DCHECK(cmd_channel_.is_alive()); switch (a2dp_offload_status_) { case A2dpOffloadStatus::kStopped: { diff --git a/pw_bluetooth_sapphire/host/l2cap/basic_mode_rx_engine.cc b/pw_bluetooth_sapphire/host/l2cap/basic_mode_rx_engine.cc index d423d4e21a..441b4bc179 100644 --- a/pw_bluetooth_sapphire/host/l2cap/basic_mode_rx_engine.cc +++ b/pw_bluetooth_sapphire/host/l2cap/basic_mode_rx_engine.cc @@ -19,7 +19,7 @@ namespace bt::l2cap::internal { ByteBufferPtr BasicModeRxEngine::ProcessPdu(PDU pdu) { - BT_ASSERT(pdu.is_valid()); + PW_CHECK(pdu.is_valid()); auto sdu = std::make_unique(pdu.length()); pdu.Copy(sdu.get()); return sdu; diff --git a/pw_bluetooth_sapphire/host/l2cap/basic_mode_tx_engine.cc b/pw_bluetooth_sapphire/host/l2cap/basic_mode_tx_engine.cc index 6f0b165a79..353e3cb06e 100644 --- a/pw_bluetooth_sapphire/host/l2cap/basic_mode_tx_engine.cc +++ b/pw_bluetooth_sapphire/host/l2cap/basic_mode_tx_engine.cc @@ -22,8 +22,8 @@ namespace bt::l2cap::internal { void BasicModeTxEngine::NotifySduQueued() { std::optional sdu = channel().GetNextQueuedSdu(); - BT_ASSERT(sdu); - BT_ASSERT(*sdu); + PW_CHECK(sdu); + PW_CHECK(*sdu); if ((*sdu)->size() > max_tx_sdu_size()) { bt_log(INFO, diff --git a/pw_bluetooth_sapphire/host/l2cap/bredr_command_handler_test.cc b/pw_bluetooth_sapphire/host/l2cap/bredr_command_handler_test.cc index 222045323d..75e853a7f1 100644 --- a/pw_bluetooth_sapphire/host/l2cap/bredr_command_handler_test.cc +++ b/pw_bluetooth_sapphire/host/l2cap/bredr_command_handler_test.cc @@ -63,7 +63,7 @@ class BrEdrCommandHandlerTest : public pw::async::test::FakeDispatcherFixture { size_t failed_requests() const { return failed_requests_; } void set_request_fail_callback(fit::closure request_fail_callback) { - BT_ASSERT(!request_fail_callback_); + PW_CHECK(!request_fail_callback_); request_fail_callback_ = std::move(request_fail_callback); } diff --git a/pw_bluetooth_sapphire/host/l2cap/bredr_dynamic_channel.cc b/pw_bluetooth_sapphire/host/l2cap/bredr_dynamic_channel.cc index 05dd004022..4f35e4dfe9 100644 --- a/pw_bluetooth_sapphire/host/l2cap/bredr_dynamic_channel.cc +++ b/pw_bluetooth_sapphire/host/l2cap/bredr_dynamic_channel.cc @@ -49,7 +49,7 @@ BrEdrDynamicChannelRegistry::BrEdrDynamicChannelRegistry( random_channel_ids), state_(0u), sig_(sig) { - BT_DEBUG_ASSERT(sig_); + PW_DCHECK(sig_); BrEdrCommandHandler cmd_handler(sig_); cmd_handler.ServeConnectionRequest( fit::bind_member<&BrEdrDynamicChannelRegistry::OnRxConnReq>(this)); @@ -404,7 +404,7 @@ void BrEdrDynamicChannel::Open(fit::closure open_result_cb) { } void BrEdrDynamicChannel::Disconnect(DisconnectDoneCallback done_cb) { - BT_ASSERT(done_cb); + PW_CHECK(done_cb); if (!IsConnected()) { done_cb(); return; @@ -489,8 +489,8 @@ bool BrEdrDynamicChannel::IsOpen() const { } ChannelInfo BrEdrDynamicChannel::info() const { - BT_ASSERT(local_config().retransmission_flow_control_option().has_value()); - BT_ASSERT(local_config().mtu_option().has_value()); + PW_CHECK(local_config().retransmission_flow_control_option().has_value()); + PW_CHECK(local_config().mtu_option().has_value()); const auto max_rx_sdu_size = local_config().mtu_option()->mtu(); const auto peer_mtu = remote_config().mtu_option()->mtu(); @@ -832,8 +832,8 @@ BrEdrDynamicChannel::BrEdrDynamicChannel( state_(0u), peer_supports_ertm_(peer_supports_ertm), weak_self_(this) { - BT_DEBUG_ASSERT(signaling_channel_); - BT_DEBUG_ASSERT(local_cid != kInvalidChannelId); + PW_DCHECK(signaling_channel_); + PW_DCHECK(local_cid != kInvalidChannelId); UpdateLocalConfigForErtm(); } @@ -851,7 +851,7 @@ void BrEdrDynamicChannel::PassOpenResult() { // client. The channel may still be connected, in case it's useful to perform // channel configuration at this point. void BrEdrDynamicChannel::PassOpenError() { - BT_ASSERT(!IsOpen()); + PW_CHECK(!IsOpen()); PassOpenResult(); } @@ -927,7 +927,7 @@ void BrEdrDynamicChannel::TrySendLocalConfig() { return; } - BT_ASSERT(!IsWaitingForPeerErtmSupport()); + PW_CHECK(!IsWaitingForPeerErtmSupport()); SendLocalConfig(); } @@ -990,7 +990,7 @@ bool BrEdrDynamicChannel::BothConfigsAccepted() const { } bool BrEdrDynamicChannel::AcceptedChannelModesAreConsistent() const { - BT_ASSERT(BothConfigsAccepted()); + PW_CHECK(BothConfigsAccepted()); auto local_mode = local_config_.retransmission_flow_control_option()->mode(); auto remote_mode = remote_config_.retransmission_flow_control_option()->mode(); @@ -1096,10 +1096,10 @@ ChannelConfiguration BrEdrDynamicChannel::CheckForUnacceptableConfigReqOptions( std::optional BrEdrDynamicChannel::CheckForUnacceptableErtmOptions( const ChannelConfiguration& config) const { - BT_ASSERT(config.retransmission_flow_control_option()->mode() == - RetransmissionAndFlowControlMode::kEnhancedRetransmission); - BT_ASSERT(local_config().retransmission_flow_control_option()->mode() == - RetransmissionAndFlowControlMode::kEnhancedRetransmission); + PW_CHECK(config.retransmission_flow_control_option()->mode() == + RetransmissionAndFlowControlMode::kEnhancedRetransmission); + PW_CHECK(local_config().retransmission_flow_control_option()->mode() == + RetransmissionAndFlowControlMode::kEnhancedRetransmission); std::optional unacceptable_rfc_option; diff --git a/pw_bluetooth_sapphire/host/l2cap/bredr_signaling_channel.cc b/pw_bluetooth_sapphire/host/l2cap/bredr_signaling_channel.cc index a3c896ef4a..9b6a19c868 100644 --- a/pw_bluetooth_sapphire/host/l2cap/bredr_signaling_channel.cc +++ b/pw_bluetooth_sapphire/host/l2cap/bredr_signaling_channel.cc @@ -53,7 +53,7 @@ void BrEdrSignalingChannel::DecodeRxUnit(ByteBufferPtr sdu, const SignalingPacketHandler& cb) { // "Multiple commands may be sent in a single C-frame over Fixed Channel CID // 0x0001 (ACL-U) (v5.0, Vol 3, Part A, Section 4)" - BT_DEBUG_ASSERT(sdu); + PW_DCHECK(sdu); if (sdu->size() < sizeof(CommandHeader)) { bt_log(DEBUG, "l2cap-bredr", "sig: dropped malformed ACL signaling packet"); return; diff --git a/pw_bluetooth_sapphire/host/l2cap/channel.cc b/pw_bluetooth_sapphire/host/l2cap/channel.cc index b7bb833e6d..3240ffa00b 100644 --- a/pw_bluetooth_sapphire/host/l2cap/channel.cc +++ b/pw_bluetooth_sapphire/host/l2cap/channel.cc @@ -51,9 +51,9 @@ Channel::Channel(ChannelId id, info_(info), max_tx_queued_(max_tx_queued), requested_acl_priority_(AclPriority::kNormal) { - BT_DEBUG_ASSERT(id_); - BT_DEBUG_ASSERT(link_type_ == bt::LinkType::kLE || - link_type_ == bt::LinkType::kACL); + PW_DCHECK(id_); + PW_DCHECK(link_type_ == bt::LinkType::kLE || + link_type_ == bt::LinkType::kACL); } namespace internal { @@ -133,8 +133,8 @@ ChannelImpl::ChannelImpl(pw::async::Dispatcher& dispatcher, fragmenter_(link->handle(), max_acl_payload_size), a2dp_offload_manager_(a2dp_offload_manager), weak_self_(this) { - BT_ASSERT(link_.is_alive()); - BT_ASSERT_MSG( + PW_CHECK(link_.is_alive()); + PW_CHECK( info_.mode == RetransmissionAndFlowControlMode::kBasic || info_.mode == RetransmissionAndFlowControlMode::kEnhancedRetransmission || @@ -154,7 +154,7 @@ ChannelImpl::ChannelImpl(pw::async::Dispatcher& dispatcher, tx_engine_ = std::make_unique(id, max_tx_sdu_size(), *this); } else if (std::holds_alternative(info_.mode)) { - BT_ASSERT(info_.remote_initial_credits.has_value()); + PW_CHECK(info_.remote_initial_credits.has_value()); auto mode = std::get(info_.mode); rx_engine_ = std::make_unique( std::move(connection_failure_cb)); @@ -200,15 +200,15 @@ const sm::SecurityProperties ChannelImpl::security() { bool ChannelImpl::Activate(RxCallback rx_callback, ClosedCallback closed_callback) { - BT_ASSERT(rx_callback); - BT_ASSERT(closed_callback); + PW_CHECK(rx_callback); + PW_CHECK(closed_callback); // Activating on a closed link has no effect. We also clear this on // deactivation to prevent a channel from being activated more than once. if (!link_.is_alive()) return false; - BT_ASSERT(!active_); + PW_CHECK(!active_); active_ = true; rx_cb_ = std::move(rx_callback); closed_cb_ = std::move(closed_callback); @@ -262,7 +262,7 @@ void ChannelImpl::SignalLinkError() { } bool ChannelImpl::Send(ByteBufferPtr sdu) { - BT_DEBUG_ASSERT(sdu); + PW_DCHECK(sdu); TRACE_DURATION( "bluetooth", "l2cap:send", "handle", link_->handle(), "id", id()); @@ -317,7 +317,7 @@ std::unique_ptr ChannelImpl::GetNextOutboundPacket() { void ChannelImpl::UpgradeSecurity(sm::SecurityLevel level, sm::ResultFunction<> callback) { - BT_ASSERT(callback); + PW_CHECK(callback); if (!link_.is_alive() || !active_) { bt_log(DEBUG, "l2cap", "Ignoring security request on inactive channel"); @@ -353,7 +353,7 @@ void ChannelImpl::RequestAclPriority( void ChannelImpl::SetBrEdrAutomaticFlushTimeout( pw::chrono::SystemClock::duration flush_timeout, hci::ResultCallback<> callback) { - BT_ASSERT(link_type_ == bt::LinkType::kACL); + PW_CHECK(link_type_ == bt::LinkType::kACL); // Channel may be inactive if this method is called before activation. if (!link_.is_alive()) { @@ -428,7 +428,7 @@ void ChannelImpl::OnClosed() { return; } - BT_ASSERT(closed_cb_); + PW_CHECK(closed_cb_); auto closed_cb = std::move(closed_cb_); CleanUp(); @@ -451,7 +451,7 @@ void ChannelImpl::HandleRxPdu(PDU&& pdu) { return; } - BT_ASSERT(rx_engine_); + PW_CHECK(rx_engine_); ByteBufferPtr sdu = rx_engine_->ProcessPdu(std::move(pdu)); if (!sdu) { @@ -476,7 +476,7 @@ void ChannelImpl::HandleRxPdu(PDU&& pdu) { return; } - BT_ASSERT(rx_cb_); + PW_CHECK(rx_cb_); { TRACE_DURATION("bluetooth", "ChannelImpl::HandleRxPdu callback"); rx_cb_(std::move(sdu)); diff --git a/pw_bluetooth_sapphire/host/l2cap/channel_manager.cc b/pw_bluetooth_sapphire/host/l2cap/channel_manager.cc index ea6d96dce4..a9bf1b9e12 100644 --- a/pw_bluetooth_sapphire/host/l2cap/channel_manager.cc +++ b/pw_bluetooth_sapphire/host/l2cap/channel_manager.cc @@ -166,7 +166,7 @@ ChannelManagerImpl::ChannelManagerImpl(hci::AclDataChannel* acl_data_channel, std::make_unique(cmd_channel_->AsWeakPtr())), random_channel_ids_(random_channel_ids), weak_self_(this) { - BT_ASSERT(acl_data_channel_); + PW_CHECK(acl_data_channel_); max_acl_payload_size_ = acl_data_channel_->GetBufferInfo().max_data_length(); max_le_payload_size_ = acl_data_channel_->GetLeBufferInfo().max_data_length(); acl_data_channel_->SetDataRxHandler(MakeInboundDataHandler()); @@ -205,7 +205,7 @@ ChannelManagerImpl::BrEdrFixedChannels ChannelManagerImpl::AddACLConnection( ll->set_security_upgrade_callback(std::move(security_cb)); Channel::WeakPtr smp = OpenFixedChannel(handle, kSMPChannelId); - BT_ASSERT(smp.is_alive()); + PW_CHECK(smp.is_alive()); return BrEdrFixedChannels{.smp = std::move(smp)}; } @@ -225,8 +225,8 @@ ChannelManagerImpl::LEFixedChannels ChannelManagerImpl::AddLEConnection( Channel::WeakPtr att = OpenFixedChannel(handle, kATTChannelId); Channel::WeakPtr smp = OpenFixedChannel(handle, kLESMPChannelId); - BT_ASSERT(att.is_alive()); - BT_ASSERT(smp.is_alive()); + PW_CHECK(att.is_alive()); + PW_CHECK(smp.is_alive()); return LEFixedChannels{.att = std::move(att), .smp = std::move(smp)}; } @@ -412,9 +412,9 @@ internal::LogicalLink* ChannelManagerImpl::RegisterInternal( // TODO(armansito): Return nullptr instead of asserting. Callers shouldn't // assume this will succeed. auto iter = ll_map_.find(handle); - BT_DEBUG_ASSERT_MSG(iter == ll_map_.end(), - "connection handle re-used! (handle=%#.4x)", - handle); + PW_DCHECK(iter == ll_map_.end(), + "connection handle re-used! (handle=%#.4x)", + handle); auto ll = std::make_unique( handle, diff --git a/pw_bluetooth_sapphire/host/l2cap/channel_manager_test.cc b/pw_bluetooth_sapphire/host/l2cap/channel_manager_test.cc index 3f22894f5b..f48b87de29 100644 --- a/pw_bluetooth_sapphire/host/l2cap/channel_manager_test.cc +++ b/pw_bluetooth_sapphire/host/l2cap/channel_manager_test.cc @@ -725,7 +725,7 @@ class ChannelManagerMockAclChannelTest : public TestingBase { void ReceiveAclDataPacket(const ByteBuffer& packet) { const size_t payload_size = packet.size() - sizeof(hci_spec::ACLDataHeader); - BT_ASSERT(payload_size <= std::numeric_limits::max()); + PW_CHECK(payload_size <= std::numeric_limits::max()); hci::ACLDataPacketPtr acl_packet = hci::ACLDataPacket::New(static_cast(payload_size)); auto mutable_acl_packet_data = acl_packet->mutable_view()->mutable_data(); @@ -1035,13 +1035,13 @@ TEST_F(ChannelManagerMockAclChannelTest, ReceiveData) { // quit the message loop std::vector sdus; auto att_rx_cb = [&sdus](ByteBufferPtr sdu) { - BT_DEBUG_ASSERT(sdu); + PW_DCHECK(sdu); sdus.push_back(sdu->ToString()); }; bool smp_cb_called = false; auto smp_rx_cb = [&smp_cb_called](ByteBufferPtr sdu) { - BT_DEBUG_ASSERT(sdu); + PW_DCHECK(sdu); EXPECT_EQ(0u, sdu->size()); smp_cb_called = true; }; @@ -1132,7 +1132,7 @@ TEST_F(ChannelManagerMockAclChannelTest, ReceiveDataBeforeRegisteringLink) { bool smp_cb_called = false; auto smp_rx_cb = [&smp_cb_called](ByteBufferPtr sdu) { - BT_DEBUG_ASSERT(sdu); + PW_DCHECK(sdu); EXPECT_EQ(0u, sdu->size()); smp_cb_called = true; }; @@ -1235,7 +1235,7 @@ TEST_F(ChannelManagerRealAclChannelTest, ReceiveDataBeforeSettingRxHandler) { bool smp_cb_called = false; auto smp_rx_cb = [&smp_cb_called](ByteBufferPtr sdu) { - BT_DEBUG_ASSERT(sdu); + PW_DCHECK(sdu); EXPECT_EQ(0u, sdu->size()); smp_cb_called = true; }; @@ -1360,7 +1360,7 @@ TEST_F(ChannelManagerRealAclChannelTest, RemovingLinkInvalidatesChannelPointer) { LEFixedChannels fixed_channels = QueueLEConnection( kTestHandle1, pw::bluetooth::emboss::ConnectionRole::CENTRAL); - BT_ASSERT(fixed_channels.att->Activate(NopRxCallback, DoNothing)); + PW_CHECK(fixed_channels.att->Activate(NopRxCallback, DoNothing)); chanmgr()->RemoveConnection(kTestHandle1); EXPECT_FALSE(fixed_channels.att.is_alive()); } @@ -1368,7 +1368,7 @@ TEST_F(ChannelManagerRealAclChannelTest, TEST_F(ChannelManagerRealAclChannelTest, SendBasicSDU) { LEFixedChannels fixed_channels = QueueLEConnection( kTestHandle1, pw::bluetooth::emboss::ConnectionRole::CENTRAL); - BT_ASSERT(fixed_channels.att->Activate(NopRxCallback, DoNothing)); + PW_CHECK(fixed_channels.att->Activate(NopRxCallback, DoNothing)); EXPECT_ACL_PACKET_OUT(test_device(), StaticByteBuffer( diff --git a/pw_bluetooth_sapphire/host/l2cap/command_handler.cc b/pw_bluetooth_sapphire/host/l2cap/command_handler.cc index df29a84108..04a0e2453f 100644 --- a/pw_bluetooth_sapphire/host/l2cap/command_handler.cc +++ b/pw_bluetooth_sapphire/host/l2cap/command_handler.cc @@ -123,7 +123,7 @@ void CommandHandler::ServeDisconnectionRequest( CommandHandler::CommandHandler(SignalingChannelInterface* sig, fit::closure request_fail_callback) : sig_(sig), request_fail_callback_(std::move(request_fail_callback)) { - BT_ASSERT(sig_); + PW_CHECK(sig_); } } // namespace bt::l2cap::internal diff --git a/pw_bluetooth_sapphire/host/l2cap/command_handler_test.cc b/pw_bluetooth_sapphire/host/l2cap/command_handler_test.cc index 0772331e7d..122ca54613 100644 --- a/pw_bluetooth_sapphire/host/l2cap/command_handler_test.cc +++ b/pw_bluetooth_sapphire/host/l2cap/command_handler_test.cc @@ -85,7 +85,7 @@ class CommandHandlerTest : public pw::async::test::FakeDispatcherFixture { size_t failed_requests() const { return failed_requests_; } void set_request_fail_callback(fit::closure request_fail_callback) { - BT_ASSERT(!request_fail_callback_); + PW_CHECK(!request_fail_callback_); request_fail_callback_ = std::move(request_fail_callback); } diff --git a/pw_bluetooth_sapphire/host/l2cap/credit_based_flow_control_tx_engine.cc b/pw_bluetooth_sapphire/host/l2cap/credit_based_flow_control_tx_engine.cc index 2cafa003a6..4e2c941145 100644 --- a/pw_bluetooth_sapphire/host/l2cap/credit_based_flow_control_tx_engine.cc +++ b/pw_bluetooth_sapphire/host/l2cap/credit_based_flow_control_tx_engine.cc @@ -44,7 +44,7 @@ constexpr typename std::underlying_type::type EnumValue(const Enum& e) { // Returns the payload size of the next PDU needed to transmit the maximal // amount of the remaining |total_payload_size| bytes. uint16_t NextPduPayloadSize(size_t total_payload_size, uint16_t max_pdu_size) { - BT_DEBUG_ASSERT(max_pdu_size > kPduHeaderSize); + PW_DCHECK(max_pdu_size > kPduHeaderSize); // Factor in the header size. uint16_t max_payload_size = max_pdu_size - kPduHeaderSize; // There is no risk of overflow in this static cast as any value of @@ -83,15 +83,15 @@ CreditBasedFlowControlTxEngine::CreditBasedFlowControlTxEngine( max_tx_pdu_size_(max_tx_pdu_size), credits_(initial_credits) { // The enhanced flow control mode is not yet supported. - BT_ASSERT_MSG(mode_ == kLeCreditBasedFlowControlMode, - "Credit based flow control mode unsupported: 0x%.2ux", - EnumValue(mode)); + PW_CHECK(mode_ == kLeCreditBasedFlowControlMode, + "Credit based flow control mode unsupported: 0x%.2ux", + EnumValue(mode)); - BT_DEBUG_ASSERT_MSG( + PW_DCHECK( mode != kLeCreditBasedFlowControlMode || max_tx_sdu_size > kMinimumLeMtu, "Invalid MTU for LE mode: %d", max_tx_sdu_size); - BT_DEBUG_ASSERT_MSG( + PW_DCHECK( mode != kLeCreditBasedFlowControlMode || max_tx_pdu_size > kMinimumLeMps, "Invalid MPS for LE mode: %d", max_tx_pdu_size); @@ -133,7 +133,7 @@ void CreditBasedFlowControlTxEngine::SegmentSdu(ByteBufferPtr sdu) { MutableBufferView payload; std::tie(frame, payload) = CreateFrame( NextPduPayloadSize(payload_remaining, max_tx_pdu_size_), channel_id()); - BT_DEBUG_ASSERT(payload.size() <= payload_remaining); + PW_DCHECK(payload.size() <= payload_remaining); if (payload_remaining > sdu->size()) { // First frame of the SDU, write the SDU header. @@ -143,7 +143,7 @@ void CreditBasedFlowControlTxEngine::SegmentSdu(ByteBufferPtr sdu) { payload = payload.mutable_view(kSduHeaderSize); payload_remaining -= kSduHeaderSize; - BT_DEBUG_ASSERT(payload_remaining == sdu->size()); + PW_DCHECK(payload_remaining == sdu->size()); } sdu->Copy(&payload, sdu->size() - payload_remaining, payload.size()); @@ -168,7 +168,7 @@ void CreditBasedFlowControlTxEngine::ProcessSdus() { if (!sdu) break; - BT_ASSERT(*sdu); + PW_CHECK(*sdu); if ((*sdu)->size() > max_tx_sdu_size()) { bt_log(INFO, diff --git a/pw_bluetooth_sapphire/host/l2cap/dynamic_channel.cc b/pw_bluetooth_sapphire/host/l2cap/dynamic_channel.cc index d9d6aa2e4b..e718993454 100644 --- a/pw_bluetooth_sapphire/host/l2cap/dynamic_channel.cc +++ b/pw_bluetooth_sapphire/host/l2cap/dynamic_channel.cc @@ -31,7 +31,7 @@ DynamicChannel::DynamicChannel(DynamicChannelRegistry* registry, local_cid_(local_cid), remote_cid_(remote_cid), opened_(false) { - BT_DEBUG_ASSERT(registry_); + PW_DCHECK(registry_); } bool DynamicChannel::SetRemoteChannelId(ChannelId remote_cid) { diff --git a/pw_bluetooth_sapphire/host/l2cap/dynamic_channel_registry.cc b/pw_bluetooth_sapphire/host/l2cap/dynamic_channel_registry.cc index a164506fb9..90452a6306 100644 --- a/pw_bluetooth_sapphire/host/l2cap/dynamic_channel_registry.cc +++ b/pw_bluetooth_sapphire/host/l2cap/dynamic_channel_registry.cc @@ -43,7 +43,7 @@ void DynamicChannelRegistry::CloseChannel(ChannelId local_cid, return; } - BT_DEBUG_ASSERT(channel->IsConnected()); + PW_DCHECK(channel->IsConnected()); auto disconn_done_cb = [self = GetWeakPtr(), close_cb = std::move(close_callback), channel] { if (!self.is_alive()) { @@ -66,16 +66,16 @@ DynamicChannelRegistry::DynamicChannelRegistry( close_cb_(std::move(close_cb)), service_request_cb_(std::move(service_request_cb)), random_channel_ids_(random_channel_ids) { - BT_DEBUG_ASSERT(max_num_channels > 0); - BT_DEBUG_ASSERT(max_num_channels < 65473); - BT_DEBUG_ASSERT(close_cb_); - BT_DEBUG_ASSERT(service_request_cb_); + PW_DCHECK(max_num_channels > 0); + PW_DCHECK(max_num_channels < 65473); + PW_DCHECK(close_cb_); + PW_DCHECK(service_request_cb_); } DynamicChannel* DynamicChannelRegistry::RequestService(Psm psm, ChannelId local_cid, ChannelId remote_cid) { - BT_DEBUG_ASSERT(local_cid != kInvalidChannelId); + PW_DCHECK(local_cid != kInvalidChannelId); auto service_info = service_request_cb_(psm); if (!service_info) { @@ -204,8 +204,8 @@ void DynamicChannelRegistry::OnChannelDisconnected(DynamicChannel* channel) { } void DynamicChannelRegistry::RemoveChannel(DynamicChannel* channel) { - BT_DEBUG_ASSERT(channel); - BT_DEBUG_ASSERT(!channel->IsConnected()); + PW_DCHECK(channel); + PW_DCHECK(!channel->IsConnected()); auto iter = channels_.find(channel->local_cid()); if (iter == channels_.end()) { diff --git a/pw_bluetooth_sapphire/host/l2cap/enhanced_retransmission_mode_tx_engine.cc b/pw_bluetooth_sapphire/host/l2cap/enhanced_retransmission_mode_tx_engine.cc index 2fee11fc82..c831ceb3af 100644 --- a/pw_bluetooth_sapphire/host/l2cap/enhanced_retransmission_mode_tx_engine.cc +++ b/pw_bluetooth_sapphire/host/l2cap/enhanced_retransmission_mode_tx_engine.cc @@ -57,7 +57,7 @@ Engine::EnhancedRetransmissionModeTxEngine( retransmitted_range_during_poll_(false), n_receiver_ready_polls_sent_(0), remote_is_busy_(false) { - BT_DEBUG_ASSERT(n_frames_in_tx_window_); + PW_DCHECK(n_frames_in_tx_window_); receiver_ready_poll_task_.set_function( [this](pw::async::Context /*ctx*/, pw::Status status) { if (!status.ok()) { @@ -83,12 +83,12 @@ Engine::EnhancedRetransmissionModeTxEngine( void Engine::NotifySduQueued() { std::optional sdu = channel().GetNextQueuedSdu(); - BT_ASSERT(sdu); + PW_CHECK(sdu); ProcessSdu(std::move(*sdu)); } void Engine::ProcessSdu(ByteBufferPtr sdu) { - BT_ASSERT(sdu); + PW_CHECK(sdu); // TODO(fxbug.dev/42054330): Add support for segmentation if (sdu->size() > max_tx_sdu_size()) { bt_log(INFO, @@ -113,13 +113,13 @@ void Engine::ProcessSdu(ByteBufferPtr sdu) { void Engine::UpdateAckSeq(uint8_t new_seq, bool is_poll_response) { // TODO(quiche): Reconsider this assertion if we allow reconfiguration of the // TX window. - BT_DEBUG_ASSERT_MSG(NumUnackedFrames() <= n_frames_in_tx_window_, - "(NumUnackedFrames() = %u, n_frames_in_tx_window_ = %u, " - "expected_ack_seq_ = %u, last_tx_seq_ = %u)", - NumUnackedFrames(), - n_frames_in_tx_window_, - expected_ack_seq_, - last_tx_seq_); + PW_DCHECK(NumUnackedFrames() <= n_frames_in_tx_window_, + "(NumUnackedFrames() = %u, n_frames_in_tx_window_ = %u, " + "expected_ack_seq_ = %u, last_tx_seq_ = %u)", + NumUnackedFrames(), + n_frames_in_tx_window_, + expected_ack_seq_, + last_tx_seq_); const auto n_frames_acked = NumFramesBetween(expected_ack_seq_, new_seq); if (n_frames_acked > NumUnackedFrames()) { @@ -143,7 +143,7 @@ void Engine::UpdateAckSeq(uint8_t new_seq, bool is_poll_response) { monitor_task_.Cancel(); } - BT_ASSERT(!(range_request_.has_value() && single_request_.has_value())); + PW_CHECK(!(range_request_.has_value() && single_request_.has_value())); if (ProcessSingleRetransmitRequest(new_seq, is_poll_response) == UpdateAckSeqAction::kConsumeAckSeq) { return; @@ -151,7 +151,7 @@ void Engine::UpdateAckSeq(uint8_t new_seq, bool is_poll_response) { auto n_frames_to_discard = n_frames_acked; while (n_frames_to_discard) { - BT_DEBUG_ASSERT(!pending_pdus_.empty()); + PW_DCHECK(!pending_pdus_.empty()); pending_pdus_.pop_front(); --n_frames_to_discard; } @@ -166,7 +166,7 @@ void Engine::UpdateAckSeq(uint8_t new_seq, bool is_poll_response) { // RemoteBusy is cleared as the first action to take when receiving a REJ per // Core Spec v5.0 Vol 3, Part A, Sec 8.6.5.9–11, so their corresponding member // variables shouldn't be both set. - BT_ASSERT(!(range_request.has_value() && remote_is_busy_)); + PW_CHECK(!(range_request.has_value() && remote_is_busy_)); bool should_retransmit = range_request.has_value(); // This implements the logic for RejActioned in the Recv {I,RR,REJ} (F=1) @@ -222,15 +222,15 @@ void Engine::SetRemoteBusy() { } void Engine::SetSingleRetransmit(bool is_poll_request) { - BT_ASSERT(!single_request_.has_value()); - BT_ASSERT(!range_request_.has_value()); + PW_CHECK(!single_request_.has_value()); + PW_CHECK(!range_request_.has_value()); // Store SREJ state for UpdateAckSeq to handle. single_request_ = SingleRetransmitRequest{.is_poll_request = is_poll_request}; } void Engine::SetRangeRetransmit(bool is_poll_request) { - BT_ASSERT(!single_request_.has_value()); - BT_ASSERT(!range_request_.has_value()); + PW_CHECK(!single_request_.has_value()); + PW_CHECK(!range_request_.has_value()); // Store REJ state for UpdateAckSeq to handle. range_request_ = RangeRetransmitRequest{.is_poll_request = is_poll_request}; } @@ -255,7 +255,7 @@ void Engine::MaybeSendQueuedData() { while (it != pending_pdus_.end() && NumUnackedFrames() < n_frames_in_tx_window_) { - BT_DEBUG_ASSERT(it->tx_count == 0); + PW_DCHECK(it->tx_count == 0); SendPdu(&*it); last_tx_seq_ = it->buf.To().tx_seq(); ++it; @@ -265,7 +265,7 @@ void Engine::MaybeSendQueuedData() { Engine::UpdateAckSeqAction Engine::ProcessSingleRetransmitRequest( uint8_t new_seq, bool is_poll_response) { const auto single_request = std::exchange(single_request_, std::nullopt); - BT_ASSERT(!(single_request.has_value() && remote_is_busy_)); + PW_CHECK(!(single_request.has_value() && remote_is_busy_)); if (!single_request.has_value()) { return UpdateAckSeqAction::kDiscardAcknowledged; } @@ -308,14 +308,14 @@ Engine::UpdateAckSeqAction Engine::ProcessSingleRetransmitRequest( } void Engine::StartReceiverReadyPollTimer() { - BT_DEBUG_ASSERT(!monitor_task_.is_pending()); + PW_DCHECK(!monitor_task_.is_pending()); n_receiver_ready_polls_sent_ = 0; receiver_ready_poll_task_.Cancel(); receiver_ready_poll_task_.PostAfter(kErtmReceiverReadyPollTimerDuration); } void Engine::StartMonitorTimer() { - BT_DEBUG_ASSERT(!receiver_ready_poll_task_.is_pending()); + PW_DCHECK(!receiver_ready_poll_task_.is_pending()); monitor_task_.Cancel(); monitor_task_.PostAfter(kErtmMonitorTimerDuration); } @@ -325,12 +325,12 @@ void Engine::SendReceiverReadyPoll() { frame.set_receive_seq_num(req_seqnum_); frame.set_is_poll_request(); ++n_receiver_ready_polls_sent_; - BT_ASSERT_MSG(max_transmissions_ == 0 || - n_receiver_ready_polls_sent_ <= max_transmissions_, - "(n_receiver_ready_polls_sent_ = %u, " - "max_transmissions = %u)", - n_receiver_ready_polls_sent_, - max_transmissions_); + PW_CHECK(max_transmissions_ == 0 || + n_receiver_ready_polls_sent_ <= max_transmissions_, + "(n_receiver_ready_polls_sent_ = %u, " + "max_transmissions = %u)", + n_receiver_ready_polls_sent_, + max_transmissions_); channel().SendFrame( std::make_unique(BufferView(&frame, sizeof(frame)))); } @@ -364,7 +364,7 @@ uint8_t Engine::NumUnackedFrames() { } void Engine::SendPdu(PendingPdu* pdu) { - BT_DEBUG_ASSERT(pdu); + PW_DCHECK(pdu); pdu->buf.AsMutable()->set_receive_seq_num( req_seqnum_); @@ -385,7 +385,7 @@ bool Engine::RetransmitUnackedData(std::optional only_with_seq, // calling any method that would cause us (the transmit engine) to retransmit // unacked data. See, e.g., Core Spec v5.0, Volume 3, Part A, Table 8.6, row // "Recv REJ (F=0)". - BT_DEBUG_ASSERT(!remote_is_busy_); + PW_DCHECK(!remote_is_busy_); // Any peer actions that cause retransmission indicate the peer is alive. This // is in conflict with Core Spec v5.0, Vol 3, Part A, Sec 8.6.5.8, which only @@ -399,13 +399,13 @@ bool Engine::RetransmitUnackedData(std::optional only_with_seq, monitor_task_.Cancel(); const auto n_to_send = NumUnackedFrames(); - BT_ASSERT(n_to_send <= n_frames_in_tx_window_); - BT_DEBUG_ASSERT(n_to_send <= pending_pdus_.size()); + PW_CHECK(n_to_send <= n_frames_in_tx_window_); + PW_DCHECK(n_to_send <= pending_pdus_.size()); auto cur_frame = pending_pdus_.begin(); auto last_frame = std::next(cur_frame, n_to_send); for (; cur_frame != last_frame; cur_frame++) { - BT_DEBUG_ASSERT(cur_frame != pending_pdus_.end()); + PW_DCHECK(cur_frame != pending_pdus_.end()); const auto control_field = cur_frame->buf.To(); @@ -416,10 +416,10 @@ bool Engine::RetransmitUnackedData(std::optional only_with_seq, // Core Spec v5.0, Vol 3, Part A, Sec 5.4: "In Enhanced Retransmission mode // a value of zero for MaxTransmit means infinite retransmissions." if (max_transmissions_ != 0 && cur_frame->tx_count >= max_transmissions_) { - BT_ASSERT_MSG(cur_frame->tx_count == max_transmissions_, - "%hhu != %hhu", - cur_frame->tx_count, - max_transmissions_); + PW_CHECK(cur_frame->tx_count == max_transmissions_, + "%hhu != %hhu", + cur_frame->tx_count, + max_transmissions_); connection_failure_callback_(); return false; } diff --git a/pw_bluetooth_sapphire/host/l2cap/fake_channel.cc b/pw_bluetooth_sapphire/host/l2cap/fake_channel.cc index c994db5dcb..dcff91c77d 100644 --- a/pw_bluetooth_sapphire/host/l2cap/fake_channel.cc +++ b/pw_bluetooth_sapphire/host/l2cap/fake_channel.cc @@ -73,10 +73,10 @@ void FakeChannel::Close() { bool FakeChannel::Activate(RxCallback rx_callback, ClosedCallback closed_callback) { - BT_DEBUG_ASSERT(rx_callback); - BT_DEBUG_ASSERT(closed_callback); - BT_DEBUG_ASSERT(!rx_cb_); - BT_DEBUG_ASSERT(!closed_cb_); + PW_DCHECK(rx_callback); + PW_DCHECK(closed_callback); + PW_DCHECK(!rx_cb_); + PW_DCHECK(!closed_cb_); if (activate_fails_) return false; @@ -109,7 +109,7 @@ void FakeChannel::SignalLinkError() { } bool FakeChannel::Send(ByteBufferPtr sdu) { - BT_DEBUG_ASSERT(sdu); + PW_DCHECK(sdu); if (!send_cb_) return false; @@ -140,7 +140,7 @@ bool FakeChannel::Send(ByteBufferPtr sdu) { void FakeChannel::UpgradeSecurity(sm::SecurityLevel level, sm::ResultFunction<> callback) { - BT_ASSERT(security_dispatcher_); + PW_CHECK(security_dispatcher_); (void)security_dispatcher_->Post( [cb = std::move(callback), f = security_cb_.share(), diff --git a/pw_bluetooth_sapphire/host/l2cap/fake_l2cap.cc b/pw_bluetooth_sapphire/host/l2cap/fake_l2cap.cc index f84e4b217f..bc00b1d5e6 100644 --- a/pw_bluetooth_sapphire/host/l2cap/fake_l2cap.cc +++ b/pw_bluetooth_sapphire/host/l2cap/fake_l2cap.cc @@ -177,10 +177,10 @@ void FakeL2cap::OpenL2capChannel(hci_spec::ConnectionHandle handle, LinkData& link_data = ConnectedLinkData(handle); auto psm_it = link_data.expected_outbound_conns.find(psm); - BT_DEBUG_ASSERT_MSG(psm_it != link_data.expected_outbound_conns.end() && - !psm_it->second.empty(), - "Unexpected outgoing L2CAP connection (PSM %#.4x)", - psm); + PW_DCHECK(psm_it != link_data.expected_outbound_conns.end() && + !psm_it->second.empty(), + "Unexpected outgoing L2CAP connection (PSM %#.4x)", + psm); auto chan_data = psm_it->second.front(); psm_it->second.pop(); @@ -189,11 +189,11 @@ void FakeL2cap::OpenL2capChannel(hci_spec::ConnectionHandle handle, params.mode.value_or(l2cap::RetransmissionAndFlowControlMode::kBasic); auto max_rx_sdu_size = params.max_rx_sdu_size.value_or(l2cap::kMaxMTU); - BT_ASSERT_MSG(chan_data.params == params, - "Didn't receive expected L2CAP channel parameters (expected: " - "%s, found: %s)", - bt_str(chan_data.params), - bt_str(params)); + PW_CHECK(chan_data.params == params, + "Didn't receive expected L2CAP channel parameters (expected: " + "%s, found: %s)", + bt_str(chan_data.params), + bt_str(params)); auto channel_info = l2cap::ChannelInfo::MakeBasicMode(max_rx_sdu_size, l2cap::kDefaultMTU); @@ -235,7 +235,7 @@ void FakeL2cap::OpenL2capChannel(hci_spec::ConnectionHandle handle, bool FakeL2cap::RegisterService(l2cap::Psm psm, l2cap::ChannelParameters params, l2cap::ChannelCallback channel_callback) { - BT_DEBUG_ASSERT(registered_services_.count(psm) == 0); + PW_DCHECK(registered_services_.count(psm) == 0); registered_services_.emplace( psm, ServiceInfo(params, std::move(channel_callback))); return true; @@ -248,9 +248,9 @@ void FakeL2cap::UnregisterService(l2cap::Psm psm) { FakeL2cap::~FakeL2cap() { for (auto& link_it : links_) { for (auto& psm_it : link_it.second.expected_outbound_conns) { - BT_DEBUG_ASSERT_MSG(psm_it.second.empty(), - "didn't receive expected connection on PSM %#.4x", - psm_it.first); + PW_DCHECK(psm_it.second.empty(), + "didn't receive expected connection on PSM %#.4x", + psm_it.first); } } } @@ -261,7 +261,7 @@ FakeL2cap::LinkData* FakeL2cap::RegisterInternal( bt::LinkType link_type, l2cap::LinkErrorCallback link_error_cb) { auto& data = GetLinkData(handle); - BT_DEBUG_ASSERT_MSG( + PW_DCHECK( !data.connected, "connection handle re-used (handle: %#.4x)", handle); data.connected = true; @@ -311,11 +311,11 @@ FakeL2cap::LinkData& FakeL2cap::GetLinkData(hci_spec::ConnectionHandle handle) { FakeL2cap::LinkData& FakeL2cap::ConnectedLinkData( hci_spec::ConnectionHandle handle) { auto link_iter = links_.find(handle); - BT_DEBUG_ASSERT_MSG( + PW_DCHECK( link_iter != links_.end(), "fake link not found (handle: %#.4x)", handle); - BT_DEBUG_ASSERT_MSG(link_iter->second.connected, - "fake link not connected yet (handle: %#.4x)", - handle); + PW_DCHECK(link_iter->second.connected, + "fake link not connected yet (handle: %#.4x)", + handle); return link_iter->second; } diff --git a/pw_bluetooth_sapphire/host/l2cap/fragmenter.cc b/pw_bluetooth_sapphire/host/l2cap/fragmenter.cc index e32143026e..e0b289dfc3 100644 --- a/pw_bluetooth_sapphire/host/l2cap/fragmenter.cc +++ b/pw_bluetooth_sapphire/host/l2cap/fragmenter.cc @@ -66,7 +66,7 @@ void OutboundFrame::WriteToFragment(MutableBufferView fragment_payload, size()}; static_assert(pages.size() == offsets.size()); - BT_ASSERT(offset <= size()); + PW_CHECK(offset <= size()); size_t output_offset = 0; // Find the last page whose offset is not greater than the current offset. @@ -85,16 +85,16 @@ void OutboundFrame::WriteToFragment(MutableBufferView fragment_payload, offset += bytes_copied; output_offset += bytes_copied; } - BT_ASSERT(output_offset <= fragment_payload.size()); + PW_CHECK(output_offset <= fragment_payload.size()); } OutboundFrame::BasicHeaderBuffer OutboundFrame::MakeBasicHeader() const { // Length is "the length of the entire L2CAP PDU in octets, excluding the // Length and CID field" (v5.0 Vol 3, Part A, Section 3.3.1) const size_t pdu_content_length = size() - sizeof(BasicHeader); - BT_ASSERT_MSG(pdu_content_length <= - std::numeric_limits::max(), - "PDU payload is too large to be encoded"); + PW_CHECK(pdu_content_length <= + std::numeric_limits::max(), + "PDU payload is too large to be encoded"); BasicHeader header = {}; header.length = pw::bytes::ConvertOrderTo( cpp20::endian::little, static_cast(pdu_content_length)); @@ -106,7 +106,7 @@ OutboundFrame::BasicHeaderBuffer OutboundFrame::MakeBasicHeader() const { } OutboundFrame::FrameCheckSequenceBuffer OutboundFrame::MakeFcs() const { - BT_ASSERT(include_fcs()); + PW_CHECK(include_fcs()); const BasicHeaderBuffer header = MakeBasicHeader(); const FrameCheckSequence header_fcs = l2cap::ComputeFcs(header.view()); const FrameCheckSequence whole_fcs = @@ -121,9 +121,9 @@ Fragmenter::Fragmenter(hci_spec::ConnectionHandle connection_handle, uint16_t max_acl_payload_size) : connection_handle_(connection_handle), max_acl_payload_size_(max_acl_payload_size) { - BT_ASSERT(connection_handle_ <= hci_spec::kConnectionHandleMax); - BT_ASSERT(max_acl_payload_size_); - BT_ASSERT(max_acl_payload_size_ >= sizeof(BasicHeader)); + PW_CHECK(connection_handle_ <= hci_spec::kConnectionHandleMax); + PW_CHECK(max_acl_payload_size_); + PW_CHECK(max_acl_payload_size_ >= sizeof(BasicHeader)); } // NOTE(armansito): The following method copies the contents of |data| into ACL @@ -155,8 +155,8 @@ PDU Fragmenter::BuildFrame(ChannelId channel_id, const ByteBuffer& data, FrameCheckSequenceOption fcs_option, bool flushable) const { - BT_DEBUG_ASSERT(data.size() <= kMaxBasicFramePayloadSize); - BT_DEBUG_ASSERT(channel_id); + PW_DCHECK(data.size() <= kMaxBasicFramePayloadSize); + PW_DCHECK(channel_id); OutboundFrame frame(channel_id, data, fcs_option); const size_t frame_size = frame.size(); @@ -166,7 +166,7 @@ PDU Fragmenter::BuildFrame(ChannelId channel_id, PDU pdu; size_t processed = 0; for (size_t i = 0; i < num_fragments; i++) { - BT_DEBUG_ASSERT(frame_size > processed); + PW_DCHECK(frame_size > processed); const size_t fragment_size = std::min( frame_size - processed, static_cast(max_acl_payload_size_)); @@ -182,7 +182,7 @@ PDU Fragmenter::BuildFrame(ChannelId channel_id, pbf, hci_spec::ACLBroadcastFlag::kPointToPoint, static_cast(fragment_size)); - BT_DEBUG_ASSERT(acl_packet); + PW_DCHECK(acl_packet); frame.WriteToFragment(acl_packet->mutable_view()->mutable_payload_data(), processed); @@ -192,7 +192,7 @@ PDU Fragmenter::BuildFrame(ChannelId channel_id, } // The PDU should have been completely processed if we got here. - BT_DEBUG_ASSERT(processed == frame_size); + PW_DCHECK(processed == frame_size); return pdu; } diff --git a/pw_bluetooth_sapphire/host/l2cap/fragmenter_test.cc b/pw_bluetooth_sapphire/host/l2cap/fragmenter_test.cc index 9b6111e715..0e037c3894 100644 --- a/pw_bluetooth_sapphire/host/l2cap/fragmenter_test.cc +++ b/pw_bluetooth_sapphire/host/l2cap/fragmenter_test.cc @@ -382,7 +382,7 @@ TEST(FragmenterTest, TwoFragmentsOffByOne) { TEST(FragmenterTest, TwoFragmentsExact) { StaticByteBuffer payload('T', 'e', 's', 't'); const bool payload_size_is_even = payload.size() % 2 == 0; - BT_DEBUG_ASSERT_MSG(payload_size_is_even, "test payload size should be even"); + PW_DCHECK(payload_size_is_even, "test payload size should be even"); StaticByteBuffer expected_fragment0( // ACL data header diff --git a/pw_bluetooth_sapphire/host/l2cap/l2cap_fuzztest.cc b/pw_bluetooth_sapphire/host/l2cap/l2cap_fuzztest.cc index e8b1b2c495..8032098d6f 100644 --- a/pw_bluetooth_sapphire/host/l2cap/l2cap_fuzztest.cc +++ b/pw_bluetooth_sapphire/host/l2cap/l2cap_fuzztest.cc @@ -134,7 +134,7 @@ class DataFuzzTest : public TestingBase { packet_view.AsMutable()->handle_and_flags = handle_and_flags; - BT_ASSERT(test_device()->SendACLDataChannelPacket(packet_view)); + PW_CHECK(test_device()->SendACLDataChannelPacket(packet_view)); return true; } diff --git a/pw_bluetooth_sapphire/host/l2cap/le_dynamic_channel.cc b/pw_bluetooth_sapphire/host/l2cap/le_dynamic_channel.cc index ddbefdb718..ec568bb8e2 100644 --- a/pw_bluetooth_sapphire/host/l2cap/le_dynamic_channel.cc +++ b/pw_bluetooth_sapphire/host/l2cap/le_dynamic_channel.cc @@ -37,7 +37,7 @@ LeDynamicChannel::State InitialState(bool has_remote_channel) { CreditBasedFlowControlMode ConvertMode(AnyChannelMode mode) { // LE dynamic channels only support credit-based flow control modes. - BT_ASSERT(std::holds_alternative(mode)); + PW_CHECK(std::holds_alternative(mode)); return std::get(mode); } @@ -53,7 +53,7 @@ LeDynamicChannelRegistry::LeDynamicChannelRegistry( std::move(service_request_cb), random_channel_ids), sig_(sig) { - BT_DEBUG_ASSERT(sig_); + PW_DCHECK(sig_); LowEnergyCommandHandler cmd_handler(sig_); cmd_handler.ServeLeCreditBasedConnectionRequest( fit::bind_member< @@ -206,7 +206,7 @@ void LeDynamicChannel::TriggerOpenCallback() { } void LeDynamicChannel::Open(fit::closure open_cb) { - BT_ASSERT_MSG(!open_result_cb_, "open callback already set"); + PW_CHECK(!open_result_cb_, "open callback already set"); open_result_cb_ = std::move(open_cb); if (!is_outbound_) { @@ -258,7 +258,7 @@ void LeDynamicChannel::Open(fit::closure open_cb) { } void LeDynamicChannel::Disconnect(DisconnectDoneCallback done_cb) { - BT_ASSERT(done_cb); + PW_CHECK(done_cb); if (!IsConnected()) { done_cb(); return; @@ -337,7 +337,7 @@ bool LeDynamicChannel::IsOpen() const { } ChannelInfo LeDynamicChannel::info() const { - BT_ASSERT(remote_config_.has_value()); + PW_CHECK(remote_config_.has_value()); return ChannelInfo::MakeCreditBasedFlowControlMode( flow_control_mode_, local_config_.mtu, diff --git a/pw_bluetooth_sapphire/host/l2cap/le_signaling_channel.cc b/pw_bluetooth_sapphire/host/l2cap/le_signaling_channel.cc index aa57abd51c..e03a48f21f 100644 --- a/pw_bluetooth_sapphire/host/l2cap/le_signaling_channel.cc +++ b/pw_bluetooth_sapphire/host/l2cap/le_signaling_channel.cc @@ -33,7 +33,7 @@ void LESignalingChannel::DecodeRxUnit(ByteBufferPtr sdu, const SignalingPacketHandler& cb) { // "[O]nly one command per C-frame shall be sent over [the LE] Fixed Channel" // (v5.0, Vol 3, Part A, Section 4). - BT_DEBUG_ASSERT(sdu); + PW_DCHECK(sdu); if (sdu->size() < sizeof(CommandHeader)) { bt_log(DEBUG, "l2cap-le", "sig: dropped malformed LE signaling packet"); return; diff --git a/pw_bluetooth_sapphire/host/l2cap/logical_link.cc b/pw_bluetooth_sapphire/host/l2cap/logical_link.cc index fd053c0f8a..1edf9f097e 100644 --- a/pw_bluetooth_sapphire/host/l2cap/logical_link.cc +++ b/pw_bluetooth_sapphire/host/l2cap/logical_link.cc @@ -99,10 +99,10 @@ LogicalLink::LogicalLink(hci_spec::ConnectionHandle handle, a2dp_offload_manager_(a2dp_offload_manager), weak_conn_interface_(this), weak_self_(this) { - BT_ASSERT(type_ == bt::LinkType::kLE || type_ == bt::LinkType::kACL); - BT_ASSERT(acl_data_channel_); - BT_ASSERT(cmd_channel_); - BT_ASSERT(query_service_cb_); + PW_CHECK(type_ == bt::LinkType::kLE || type_ == bt::LinkType::kACL); + PW_CHECK(acl_data_channel_); + PW_CHECK(cmd_channel_); + PW_CHECK(query_service_cb_); // Allow packets to be sent on this link immediately. acl_data_channel_->RegisterConnection(weak_conn_interface_.GetWeakPtr()); @@ -133,11 +133,11 @@ LogicalLink::LogicalLink(hci_spec::ConnectionHandle handle, LogicalLink::~LogicalLink() { bt_log(DEBUG, "l2cap", "LogicalLink destroyed (handle: %#.4x)", handle_); - BT_ASSERT(closed_); + PW_CHECK(closed_); } Channel::WeakPtr LogicalLink::OpenFixedChannel(ChannelId id) { - BT_DEBUG_ASSERT(!closed_); + PW_DCHECK(!closed_); TRACE_DURATION("bluetooth", "LogicalLink::OpenFixedChannel", @@ -197,8 +197,8 @@ Channel::WeakPtr LogicalLink::OpenFixedChannel(ChannelId id) { void LogicalLink::OpenChannel(Psm psm, ChannelParameters params, ChannelCallback callback) { - BT_DEBUG_ASSERT(!closed_); - BT_DEBUG_ASSERT(dynamic_registry_); + PW_DCHECK(!closed_); + PW_DCHECK(dynamic_registry_); auto create_channel = [this, cb = std::move(callback)](const DynamicChannel* dyn_chan) mutable { @@ -211,8 +211,8 @@ void LogicalLink::OpenChannel(Psm psm, } void LogicalLink::HandleRxPacket(hci::ACLDataPacketPtr packet) { - BT_DEBUG_ASSERT(packet); - BT_DEBUG_ASSERT(!closed_); + PW_DCHECK(packet); + PW_DCHECK(!closed_); TRACE_DURATION("bluetooth", "LogicalLink::HandleRxPacket", "handle", handle_); @@ -236,7 +236,7 @@ void LogicalLink::HandleRxPacket(hci::ACLDataPacketPtr packet) { return; } - BT_DEBUG_ASSERT(result.pdu->is_valid()); + PW_DCHECK(result.pdu->is_valid()); uint16_t channel_id = result.pdu->channel_id(); auto iter = channels_.find(channel_id); @@ -290,7 +290,7 @@ void LogicalLink::HandleRxPacket(hci::ACLDataPacketPtr packet) { void LogicalLink::UpgradeSecurity(sm::SecurityLevel level, sm::ResultFunction<> callback) { - BT_DEBUG_ASSERT(security_callback_); + PW_DCHECK(security_callback_); if (closed_) { bt_log(DEBUG, "l2cap", "Ignoring security request on closed link"); @@ -400,7 +400,7 @@ bool LogicalLink::AllowsFixedChannel(ChannelId id) { } void LogicalLink::RemoveChannel(Channel* chan, fit::closure removed_cb) { - BT_DEBUG_ASSERT(chan); + PW_DCHECK(chan); if (closed_) { bt_log(DEBUG, "l2cap", "Ignore RemoveChannel() on closed link"); @@ -454,8 +454,8 @@ void LogicalLink::SignalError() { size_t num_channels_to_close = channels_.size(); if (signaling_channel_) { - BT_ASSERT(channels_.count(kSignalingChannelId) || - channels_.count(kLESignalingChannelId)); + PW_CHECK(channels_.count(kSignalingChannelId) || + channels_.count(kLESignalingChannelId)); // There is no need to close the signaling channel. num_channels_to_close--; } @@ -500,7 +500,7 @@ void LogicalLink::SignalError() { } void LogicalLink::Close() { - BT_DEBUG_ASSERT(!closed_); + PW_DCHECK(!closed_); closed_ = true; @@ -515,7 +515,7 @@ void LogicalLink::Close() { std::optional LogicalLink::OnServiceRequest(Psm psm) { - BT_DEBUG_ASSERT(!closed_); + PW_DCHECK(!closed_); // Query upper layer for a service handler attached to this PSM. auto result = query_service_cb_(handle_, psm); @@ -532,8 +532,8 @@ LogicalLink::OnServiceRequest(Psm psm) { } void LogicalLink::OnChannelDisconnectRequest(const DynamicChannel* dyn_chan) { - BT_DEBUG_ASSERT(dyn_chan); - BT_DEBUG_ASSERT(!closed_); + PW_DCHECK(dyn_chan); + PW_DCHECK(!closed_); auto iter = channels_.find(dyn_chan->local_cid()); if (iter == channels_.end()) { @@ -545,7 +545,7 @@ void LogicalLink::OnChannelDisconnectRequest(const DynamicChannel* dyn_chan) { } ChannelImpl* channel = iter->second.get(); - BT_DEBUG_ASSERT(channel->remote_id() == dyn_chan->remote_cid()); + PW_DCHECK(channel->remote_id() == dyn_chan->remote_cid()); // Signal closure because this is a remote disconnection. channel->OnClosed(); @@ -557,7 +557,7 @@ void LogicalLink::OnChannelDisconnectRequest(const DynamicChannel* dyn_chan) { void LogicalLink::CompleteDynamicOpen(const DynamicChannel* dyn_chan, ChannelCallback open_cb) { - BT_DEBUG_ASSERT(!closed_); + PW_DCHECK(!closed_); if (!dyn_chan) { open_cb(Channel::WeakPtr()); @@ -614,7 +614,7 @@ void LogicalLink::CompleteDynamicOpen(const DynamicChannel* dyn_chan, } void LogicalLink::SendFixedChannelsSupportedInformationRequest() { - BT_ASSERT(signaling_channel_); + PW_CHECK(signaling_channel_); BrEdrCommandHandler cmd_handler(signaling_channel_.get()); if (!cmd_handler.SendInformationRequest( @@ -680,9 +680,9 @@ void LogicalLink::OnRxFixedChannelsSupportedInfoRsp( void LogicalLink::SendConnectionParameterUpdateRequest( hci_spec::LEPreferredConnectionParameters params, ConnectionParameterUpdateRequestCallback request_cb) { - BT_ASSERT(signaling_channel_); - BT_ASSERT(type_ == bt::LinkType::kLE); - BT_ASSERT(role_ == pw::bluetooth::emboss::ConnectionRole::PERIPHERAL); + PW_CHECK(signaling_channel_); + PW_CHECK(type_ == bt::LinkType::kLE); + PW_CHECK(role_ == pw::bluetooth::emboss::ConnectionRole::PERIPHERAL); LowEnergyCommandHandler cmd_handler(signaling_channel_.get()); cmd_handler.SendConnectionParameterUpdateRequest( @@ -712,9 +712,9 @@ void LogicalLink::RequestAclPriority( Channel::WeakPtr channel, AclPriority priority, fit::callback)> callback) { - BT_ASSERT(channel.is_alive()); + PW_CHECK(channel.is_alive()); auto iter = channels_.find(channel->id()); - BT_ASSERT(iter != channels_.end()); + PW_CHECK(iter != channels_.end()); pending_acl_requests_.push( PendingAclRequest{std::move(channel), priority, std::move(callback)}); if (pending_acl_requests_.size() == 1) { @@ -763,9 +763,9 @@ void LogicalLink::SetBrEdrAutomaticFlushTimeout( std::chrono::duration_cast(flush_timeout) .count()) * hci_spec::kFlushTimeoutMsToCommandParameterConversionFactor); - BT_ASSERT(converted_flush_timeout != 0); - BT_ASSERT(converted_flush_timeout <= - hci_spec::kMaxAutomaticFlushTimeoutCommandParameterValue); + PW_CHECK(converted_flush_timeout != 0); + PW_CHECK(converted_flush_timeout <= + hci_spec::kMaxAutomaticFlushTimeoutCommandParameterValue); } auto write_timeout = hci::EmbossCommandPacket::New< @@ -829,7 +829,7 @@ void LogicalLink::HandleNextAclPriorityRequest() { } auto& request = pending_acl_requests_.front(); - BT_ASSERT(request.callback); + PW_CHECK(request.callback); // Prevent closed channels with queued requests from upgrading channel // priority. Allow closed channels to downgrade priority so that they can @@ -901,8 +901,8 @@ void LogicalLink::HandleNextAclPriorityRequest() { } void LogicalLink::ServeConnectionParameterUpdateRequest() { - BT_ASSERT(signaling_channel_); - BT_ASSERT(type_ == bt::LinkType::kLE); + PW_CHECK(signaling_channel_); + PW_CHECK(type_ == bt::LinkType::kLE); LowEnergyCommandHandler cmd_handler(signaling_channel_.get()); cmd_handler.ServeConnectionParameterUpdateRequest( diff --git a/pw_bluetooth_sapphire/host/l2cap/low_energy_command_handler_test.cc b/pw_bluetooth_sapphire/host/l2cap/low_energy_command_handler_test.cc index a5c8f08819..68ed4aad20 100644 --- a/pw_bluetooth_sapphire/host/l2cap/low_energy_command_handler_test.cc +++ b/pw_bluetooth_sapphire/host/l2cap/low_energy_command_handler_test.cc @@ -56,7 +56,7 @@ class LowEnergyCommandHandlerTest size_t failed_requests() const { return failed_requests_; } void set_request_fail_callback(fit::closure request_fail_callback) { - BT_ASSERT(!request_fail_callback_); + PW_CHECK(!request_fail_callback_); request_fail_callback_ = std::move(request_fail_callback); } diff --git a/pw_bluetooth_sapphire/host/l2cap/pdu.cc b/pw_bluetooth_sapphire/host/l2cap/pdu.cc index 695e410e1d..4d570f22e9 100644 --- a/pw_bluetooth_sapphire/host/l2cap/pdu.cc +++ b/pw_bluetooth_sapphire/host/l2cap/pdu.cc @@ -31,12 +31,12 @@ PDU& PDU::operator=(PDU&& other) { } size_t PDU::Copy(MutableByteBuffer* out_buffer, size_t pos, size_t size) const { - BT_DEBUG_ASSERT(out_buffer); - BT_DEBUG_ASSERT(pos <= length()); - BT_DEBUG_ASSERT(is_valid()); + PW_DCHECK(out_buffer); + PW_DCHECK(pos <= length()); + PW_DCHECK(is_valid()); size_t remaining = std::min(size, length() - pos); - BT_DEBUG_ASSERT(out_buffer->size() >= remaining); + PW_DCHECK(out_buffer->size() >= remaining); if (!remaining) { return 0; } @@ -85,23 +85,23 @@ size_t PDU::Copy(MutableByteBuffer* out_buffer, size_t pos, size_t size) const { PDU::FragmentList PDU::ReleaseFragments() { auto out_list = std::move(fragments_); - BT_DEBUG_ASSERT(!is_valid()); + PW_DCHECK(!is_valid()); return out_list; } const BasicHeader& PDU::basic_header() const { - BT_DEBUG_ASSERT(!fragments_.empty()); + PW_DCHECK(!fragments_.empty()); const auto& fragment = *fragments_.begin(); - BT_DEBUG_ASSERT(fragment->packet_boundary_flag() != - hci_spec::ACLPacketBoundaryFlag::kContinuingFragment); + PW_DCHECK(fragment->packet_boundary_flag() != + hci_spec::ACLPacketBoundaryFlag::kContinuingFragment); return fragment->view().payload(); } void PDU::AppendFragment(hci::ACLDataPacketPtr fragment) { - BT_DEBUG_ASSERT(fragment); - BT_DEBUG_ASSERT(!is_valid() || (*fragments_.begin())->connection_handle() == - fragment->connection_handle()); + PW_DCHECK(fragment); + PW_DCHECK(!is_valid() || (*fragments_.begin())->connection_handle() == + fragment->connection_handle()); fragments_.push_back(std::move(fragment)); } diff --git a/pw_bluetooth_sapphire/host/l2cap/pdu_test.cc b/pw_bluetooth_sapphire/host/l2cap/pdu_test.cc index 90d56ee910..9c6e687ec7 100644 --- a/pw_bluetooth_sapphire/host/l2cap/pdu_test.cc +++ b/pw_bluetooth_sapphire/host/l2cap/pdu_test.cc @@ -27,7 +27,7 @@ namespace { template hci::ACLDataPacketPtr PacketFromBytes(T... data) { StaticByteBuffer bytes(std::forward(data)...); - BT_DEBUG_ASSERT(bytes.size() >= sizeof(hci_spec::ACLDataHeader)); + PW_DCHECK(bytes.size() >= sizeof(hci_spec::ACLDataHeader)); auto packet = hci::ACLDataPacket::New( static_cast(bytes.size() - sizeof(hci_spec::ACLDataHeader))); diff --git a/pw_bluetooth_sapphire/host/l2cap/recombiner.cc b/pw_bluetooth_sapphire/host/l2cap/recombiner.cc index 61f32cc2b7..a6d7567f05 100644 --- a/pw_bluetooth_sapphire/host/l2cap/recombiner.cc +++ b/pw_bluetooth_sapphire/host/l2cap/recombiner.cc @@ -23,8 +23,8 @@ namespace bt::l2cap { namespace { const BasicHeader& GetBasicHeader(const hci::ACLDataPacket& fragment) { - BT_DEBUG_ASSERT(fragment.packet_boundary_flag() != - hci_spec::ACLPacketBoundaryFlag::kContinuingFragment); + PW_DCHECK(fragment.packet_boundary_flag() != + hci_spec::ACLPacketBoundaryFlag::kContinuingFragment); return fragment.view().payload(); } @@ -33,8 +33,8 @@ const BasicHeader& GetBasicHeader(const hci::ACLDataPacket& fragment) { Recombiner::Recombiner(hci_spec::ConnectionHandle handle) : handle_(handle) {} Recombiner::Result Recombiner::ConsumeFragment(hci::ACLDataPacketPtr fragment) { - BT_DEBUG_ASSERT(fragment); - BT_DEBUG_ASSERT(fragment->connection_handle() == handle_); + PW_DCHECK(fragment); + PW_DCHECK(fragment->connection_handle() == handle_); TRACE_DURATION("bluetooth", "Recombiner::AddFragment"); if (!recombination_) { @@ -86,8 +86,8 @@ Recombiner::Result Recombiner::ConsumeFragment(hci::ACLDataPacketPtr fragment) { Recombiner::Result Recombiner::ProcessFirstFragment( hci::ACLDataPacketPtr fragment) { - BT_DEBUG_ASSERT(fragment); - BT_DEBUG_ASSERT(!recombination_); + PW_DCHECK(fragment); + PW_DCHECK(!recombination_); // The first fragment needs to at least contain the Basic L2CAP header and // should not be a continuation fragment. @@ -137,7 +137,7 @@ Recombiner::Result Recombiner::ProcessFirstFragment( } void Recombiner::ClearRecombination() { - BT_DEBUG_ASSERT(recombination_); + PW_DCHECK(recombination_); if (recombination_->pdu.is_valid()) { bt_log(DEBUG, "l2cap", diff --git a/pw_bluetooth_sapphire/host/l2cap/recombiner_test.cc b/pw_bluetooth_sapphire/host/l2cap/recombiner_test.cc index fb8318a190..2cbb1ba06d 100644 --- a/pw_bluetooth_sapphire/host/l2cap/recombiner_test.cc +++ b/pw_bluetooth_sapphire/host/l2cap/recombiner_test.cc @@ -32,7 +32,7 @@ constexpr ChannelId kTestChannelId = 0xFFFF; template hci::ACLDataPacketPtr PacketFromBytes(T... data) { StaticByteBuffer bytes(std::forward(data)...); - BT_DEBUG_ASSERT(bytes.size() >= sizeof(hci_spec::ACLDataHeader)); + PW_DCHECK(bytes.size() >= sizeof(hci_spec::ACLDataHeader)); auto packet = hci::ACLDataPacket::New( static_cast(bytes.size() - sizeof(hci_spec::ACLDataHeader))); diff --git a/pw_bluetooth_sapphire/host/l2cap/signaling_channel.cc b/pw_bluetooth_sapphire/host/l2cap/signaling_channel.cc index fa4aa6d308..c0caee88cb 100644 --- a/pw_bluetooth_sapphire/host/l2cap/signaling_channel.cc +++ b/pw_bluetooth_sapphire/host/l2cap/signaling_channel.cc @@ -33,9 +33,9 @@ SignalingChannel::SignalingChannel(Channel::WeakPtr chan, role_(role), next_cmd_id_(0x01), weak_self_(this) { - BT_DEBUG_ASSERT(chan_); - BT_DEBUG_ASSERT(chan_->id() == kSignalingChannelId || - chan_->id() == kLESignalingChannelId); + PW_DCHECK(chan_); + PW_DCHECK(chan_->id() == kSignalingChannelId || + chan_->id() == kLESignalingChannelId); // Note: No need to guard against out-of-thread access as these callbacks are // called on the L2CAP thread. @@ -54,7 +54,7 @@ SignalingChannel::SignalingChannel(Channel::WeakPtr chan, bool SignalingChannel::SendRequest(CommandCode req_code, const ByteBuffer& payload, ResponseHandler cb) { - BT_ASSERT(cb); + PW_CHECK(cb); // Command identifiers for pending requests are assumed to be unique across // all types of requests and reused by order of least recent use. See v5.0 @@ -89,8 +89,8 @@ bool SignalingChannel::SendRequest(CommandCode req_code, } void SignalingChannel::ServeRequest(CommandCode req_code, RequestDelegate cb) { - BT_ASSERT(!IsSupportedResponse(req_code)); - BT_ASSERT(cb); + PW_CHECK(!IsSupportedResponse(req_code)); + PW_CHECK(cb); inbound_handlers_[req_code] = std::move(cb); } @@ -98,11 +98,11 @@ void SignalingChannel::EnqueueResponse(const ByteBuffer& request_packet, CommandId id, CommandCode response_command_code, ResponseHandler cb) { - BT_ASSERT(IsSupportedResponse(response_command_code)); + PW_CHECK(IsSupportedResponse(response_command_code)); const auto [iter, inserted] = pending_commands_.try_emplace( id, request_packet, response_command_code, std::move(cb), pw_dispatcher_); - BT_ASSERT(inserted); + PW_CHECK(inserted); // Start the RTX timer per Core Spec v5.0, Volume 3, Part A, Sec 6.2.1 which // will call OnResponseTimeout when it expires. This timer is canceled if the @@ -127,7 +127,7 @@ SignalingChannel::ResponderImpl::ResponderImpl(SignalingChannel* sig, CommandCode code, CommandId id) : sig_(sig), code_(code), id_(id) { - BT_DEBUG_ASSERT(sig_); + PW_DCHECK(sig_); } void SignalingChannel::ResponderImpl::Send(const ByteBuffer& rsp_payload) { @@ -232,7 +232,7 @@ void SignalingChannel::OnRxResponse(const SignalingPacket& packet) { void SignalingChannel::OnResponseTimeout(CommandId id, bool retransmit) { auto iter = pending_commands_.find(id); - BT_ASSERT(iter != pending_commands_.end()); + PW_CHECK(iter != pending_commands_.end()); if (!retransmit || iter->second.transmit_count == kMaxSignalingChannelTransmissions) { @@ -246,8 +246,8 @@ void SignalingChannel::OnResponseTimeout(CommandId id, bool retransmit) { } bool SignalingChannel::Send(ByteBufferPtr packet) { - BT_DEBUG_ASSERT(packet); - BT_DEBUG_ASSERT(packet->size() >= sizeof(CommandHeader)); + PW_DCHECK(packet); + PW_DCHECK(packet->size() >= sizeof(CommandHeader)); if (!is_open()) return false; @@ -258,11 +258,11 @@ bool SignalingChannel::Send(ByteBufferPtr packet) { // response rather than assert and crash. [[maybe_unused]] SignalingPacket reply( packet.get(), packet->size() - sizeof(CommandHeader)); - BT_DEBUG_ASSERT(reply.header().code); - BT_DEBUG_ASSERT(reply.payload_size() == - pw::bytes::ConvertOrderFrom(cpp20::endian::little, - reply.header().length)); - BT_DEBUG_ASSERT(chan_); + PW_DCHECK(reply.header().code); + PW_DCHECK(reply.payload_size() == + pw::bytes::ConvertOrderFrom(cpp20::endian::little, + reply.header().length)); + PW_DCHECK(chan_); return chan_->Send(std::move(packet)); } @@ -270,10 +270,10 @@ bool SignalingChannel::Send(ByteBufferPtr packet) { ByteBufferPtr SignalingChannel::BuildPacket(CommandCode code, uint8_t identifier, const ByteBuffer& data) { - BT_DEBUG_ASSERT(data.size() <= std::numeric_limits::max()); + PW_DCHECK(data.size() <= std::numeric_limits::max()); auto buffer = NewBuffer(sizeof(CommandHeader) + data.size()); - BT_ASSERT(buffer); + PW_CHECK(buffer); MutableSignalingPacket packet(buffer.get(), data.size()); packet.mutable_header()->code = code; @@ -288,7 +288,7 @@ ByteBufferPtr SignalingChannel::BuildPacket(CommandCode code, bool SignalingChannel::SendCommandReject(uint8_t identifier, RejectReason reason, const ByteBuffer& data) { - BT_DEBUG_ASSERT(data.size() <= kCommandRejectMaxDataLength); + PW_DCHECK(data.size() <= kCommandRejectMaxDataLength); constexpr size_t kMaxPayloadLength = sizeof(CommandRejectPayload) + kCommandRejectMaxDataLength; @@ -314,7 +314,7 @@ CommandId SignalingChannel::GetNextCommandId() { } void SignalingChannel::OnChannelClosed() { - BT_DEBUG_ASSERT(is_open()); + PW_DCHECK(is_open()); is_open_ = false; } diff --git a/pw_bluetooth_sapphire/host/l2cap/signaling_channel_test.cc b/pw_bluetooth_sapphire/host/l2cap/signaling_channel_test.cc index c56b3ea92a..a55d7d67ad 100644 --- a/pw_bluetooth_sapphire/host/l2cap/signaling_channel_test.cc +++ b/pw_bluetooth_sapphire/host/l2cap/signaling_channel_test.cc @@ -62,7 +62,7 @@ class TestSignalingChannel : public SignalingChannel { // SignalingChannel overrides void DecodeRxUnit(ByteBufferPtr sdu, const SignalingPacketHandler& cb) override { - BT_ASSERT(sdu); + PW_CHECK(sdu); if (sdu->size()) { cb(SignalingPacket(sdu.get(), sdu->size() - sizeof(CommandHeader))); } else { diff --git a/pw_bluetooth_sapphire/host/l2cap/test_packets.cc b/pw_bluetooth_sapphire/host/l2cap/test_packets.cc index 666b886069..25bb8a4183 100644 --- a/pw_bluetooth_sapphire/host/l2cap/test_packets.cc +++ b/pw_bluetooth_sapphire/host/l2cap/test_packets.cc @@ -205,7 +205,7 @@ DynamicByteBuffer AclConfigReq(l2cap::CommandId id, params.mode.value_or(l2cap::RetransmissionAndFlowControlMode::kBasic); const auto mtu = params.max_rx_sdu_size.value_or(l2cap::kMaxMTU); - BT_ASSERT_MSG( + PW_CHECK( std::holds_alternative(any_mode), "Channel mode is unsupported for configuration request."); const auto mode = std::get(any_mode); @@ -278,7 +278,7 @@ DynamicByteBuffer AclConfigReq(l2cap::CommandId id, case l2cap::RetransmissionAndFlowControlMode::kRetransmission: case l2cap::RetransmissionAndFlowControlMode::kFlowControl: case l2cap::RetransmissionAndFlowControlMode::kStreaming: - BT_ASSERT_MSG(false, "unsupported mode"); + PW_CHECK(false, "unsupported mode"); } } @@ -290,7 +290,7 @@ DynamicByteBuffer AclConfigRsp(l2cap::CommandId id, params.mode.value_or(l2cap::RetransmissionAndFlowControlMode::kBasic); const auto mtu = params.max_rx_sdu_size.value_or(l2cap::kMaxMTU); - BT_ASSERT_MSG( + PW_CHECK( std::holds_alternative(any_mode), "Channel mode is unsupported for configuration response."); const auto mode = std::get(any_mode); @@ -374,7 +374,7 @@ DynamicByteBuffer AclConfigRsp(l2cap::CommandId id, case l2cap::RetransmissionAndFlowControlMode::kRetransmission: case l2cap::RetransmissionAndFlowControlMode::kFlowControl: case l2cap::RetransmissionAndFlowControlMode::kStreaming: - BT_ASSERT_MSG(false, "unsupported mode"); + PW_CHECK(false, "unsupported mode"); } } diff --git a/pw_bluetooth_sapphire/host/l2cap/types.cc b/pw_bluetooth_sapphire/host/l2cap/types.cc index d5b8ce1d88..fff64eb324 100644 --- a/pw_bluetooth_sapphire/host/l2cap/types.cc +++ b/pw_bluetooth_sapphire/host/l2cap/types.cc @@ -62,7 +62,7 @@ bool operator!=(CreditBasedFlowControlMode mode, const AnyChannelMode& any) { std::string AnyChannelModeToString(const AnyChannelMode& mode) { std::string buffer(kAnyChannelModeMaxStringSize, 0); pw::StatusWithSize result = pw::ToString(mode, buffer); - BT_ASSERT(result.ok()); + PW_CHECK(result.ok()); buffer.resize(result.size()); return buffer; } diff --git a/pw_bluetooth_sapphire/host/sco/sco_connection.cc b/pw_bluetooth_sapphire/host/sco/sco_connection.cc index 262f39cf1a..ca09a35e62 100644 --- a/pw_bluetooth_sapphire/host/sco/sco_connection.cc +++ b/pw_bluetooth_sapphire/host/sco/sco_connection.cc @@ -29,9 +29,9 @@ ScoConnection::ScoConnection( channel_(channel), parameters_(std::move(parameters)), weak_self_(this) { - BT_ASSERT(connection_); - BT_ASSERT(!channel_ || channel_->max_data_length() <= - hci_spec::kMaxSynchronousDataPacketPayloadSize); + PW_CHECK(connection_); + PW_CHECK(!channel_ || channel_->max_data_length() <= + hci_spec::kMaxSynchronousDataPacketPayloadSize); handle_ = connection_->handle(); @@ -59,7 +59,7 @@ void ScoConnection::Close() { return; } - BT_ASSERT(activator_closed_cb_); + PW_CHECK(activator_closed_cb_); // Move cb out of this, since cb may destroy this. auto cb = std::move(activator_closed_cb_); cb(); @@ -69,9 +69,9 @@ bool ScoConnection::Activate(fit::closure rx_callback, fit::closure closed_callback) { // TODO(fxbug.dev/42136417): Handle Activate() called on a connection that has // been closed already. - BT_ASSERT(closed_callback); - BT_ASSERT(!active_); - BT_ASSERT(rx_callback); + PW_CHECK(closed_callback); + PW_CHECK(!active_); + PW_CHECK(rx_callback); activator_closed_cb_ = std::move(closed_callback); rx_callback_ = std::move(rx_callback); active_ = true; @@ -172,7 +172,7 @@ std::unique_ptr ScoConnection::GetNextOutboundPacket() { void ScoConnection::ReceiveInboundPacket( std::unique_ptr packet) { - BT_ASSERT(packet->connection_handle() == handle_); + PW_CHECK(packet->connection_handle() == handle_); if (!active_ || !rx_callback_) { bt_log(TRACE, "gap-sco", "dropping inbound SCO packet"); diff --git a/pw_bluetooth_sapphire/host/sco/sco_connection_manager.cc b/pw_bluetooth_sapphire/host/sco/sco_connection_manager.cc index 08d43c946a..4f09a22b46 100644 --- a/pw_bluetooth_sapphire/host/sco/sco_connection_manager.cc +++ b/pw_bluetooth_sapphire/host/sco/sco_connection_manager.cc @@ -53,7 +53,7 @@ ScoConnectionManager::ScoConnectionManager( acl_handle_(acl_handle), transport_(std::move(transport)), weak_ptr_factory_(this) { - BT_ASSERT(transport_.is_alive()); + PW_CHECK(transport_.is_alive()); AddEventHandler( hci_spec::kSynchronousConnectionCompleteEventCode, @@ -160,7 +160,7 @@ hci::CommandChannel::EventHandlerId ScoConnectionManager::AddEventHandler( } }, std::move(event_cb_variant)); - BT_ASSERT(event_id); + PW_CHECK(event_id); event_handler_ids_.push_back(event_id); return event_id; } @@ -216,7 +216,7 @@ ScoConnectionManager::OnSynchronousConnectionComplete( } fit::closure deactivated_cb = [this, connection_handle] { - BT_ASSERT(connections_.erase(connection_handle)); + PW_CHECK(connections_.erase(connection_handle)); }; bt::StaticPacket conn_params = in_progress_request_ @@ -229,10 +229,10 @@ ScoConnectionManager::OnSynchronousConnectionComplete( auto [_, success] = connections_.try_emplace(connection_handle, std::move(conn)); - BT_ASSERT_MSG(success, - "SCO connection already exists with handle %#.4x (peer: %s)", - connection_handle, - bt_str(peer_id_)); + PW_CHECK(success, + "SCO connection already exists with handle %#.4x (peer: %s)", + connection_handle, + bt_str(peer_id_)); CompleteRequest(fit::ok(std::make_pair( std::move(conn_weak), in_progress_request_->current_param_index))); @@ -242,7 +242,7 @@ ScoConnectionManager::OnSynchronousConnectionComplete( hci::CommandChannel::EventCallbackResult ScoConnectionManager::OnConnectionRequest(const hci::EmbossEventPacket& event) { - BT_ASSERT(event.event_code() == hci_spec::kConnectionRequestEventCode); + PW_CHECK(event.event_code() == hci_spec::kConnectionRequestEventCode); auto params = event.view(); // Ignore requests for other link types. @@ -333,7 +333,7 @@ ScoConnectionManager::OnConnectionRequest(const hci::EmbossEventPacket& event) { } bool ScoConnectionManager::FindNextParametersThatSupportSco() { - BT_ASSERT(in_progress_request_); + PW_CHECK(in_progress_request_); while (in_progress_request_->current_param_index < in_progress_request_->parameters.size()) { bt::StaticPacket< @@ -349,7 +349,7 @@ bool ScoConnectionManager::FindNextParametersThatSupportSco() { } bool ScoConnectionManager::FindNextParametersThatSupportEsco() { - BT_ASSERT(in_progress_request_); + PW_CHECK(in_progress_request_); while (in_progress_request_->current_param_index < in_progress_request_->parameters.size()) { bt::StaticPacket< @@ -369,7 +369,7 @@ ScoConnectionManager::RequestHandle ScoConnectionManager::QueueRequest( std::vector> params, ConnectionCallback cb) { - BT_ASSERT(cb); + PW_CHECK(cb); if (params.empty()) { cb(fit::error(HostError::kInvalidParameters)); @@ -441,7 +441,7 @@ void ScoConnectionManager::TryCreateNextConnection() { void ScoConnectionManager::CompleteRequestOrTryNextParameters( ConnectionResult result) { - BT_ASSERT(in_progress_request_); + PW_CHECK(in_progress_request_); // Multiple parameter attempts are not supported for initiator requests. if (result.is_ok() || in_progress_request_->initiator) { @@ -471,7 +471,7 @@ void ScoConnectionManager::CompleteRequestOrTryNextParameters( } void ScoConnectionManager::CompleteRequest(ConnectionResult result) { - BT_ASSERT(in_progress_request_); + PW_CHECK(in_progress_request_); bt_log(INFO, "gap-sco", "Completing SCO connection request (initiator: %d, success: %d, peer: " @@ -505,7 +505,7 @@ void ScoConnectionManager::SendRejectConnectionCommand( DeviceAddressBytes addr, pw::bluetooth::emboss::StatusCode reason) { // The reject command has a small range of allowed reasons (the controller // sends "Invalid HCI Command Parameters" for other reasons). - BT_ASSERT_MSG( + PW_CHECK( reason == pw::bluetooth::emboss::StatusCode:: CONNECTION_REJECTED_LIMITED_RESOURCES || reason == diff --git a/pw_bluetooth_sapphire/host/sdp/client.cc b/pw_bluetooth_sapphire/host/sdp/client.cc index ac4d5cb0f0..7520198fd5 100644 --- a/pw_bluetooth_sapphire/host/sdp/client.cc +++ b/pw_bluetooth_sapphire/host/sdp/client.cc @@ -183,21 +183,20 @@ void Impl::ServiceSearchAttributes( auto [iter, placed] = pending_.try_emplace(next, next, std::move(req), std::move(result_cb)); - BT_DEBUG_ASSERT_MSG(placed, "Should not have repeat transaction ID %u", next); + PW_DCHECK(placed, "Should not have repeat transaction ID %u", next); TrySendNextTransaction(); } void Impl::Finish(TransactionId id) { auto node = pending_.extract(id); - BT_DEBUG_ASSERT(node); + PW_DCHECK(node); auto& state = node.mapped(); pending_timeout_.reset(); if (!state.callback) { return; } - BT_DEBUG_ASSERT_MSG(state.response.complete(), - "Finished without complete response"); + PW_DCHECK(state.response.complete(), "Finished without complete response"); auto self = weak_self_.GetWeakPtr(); @@ -209,7 +208,7 @@ void Impl::Finish(TransactionId id) { } // |count| and |idx| are at most std::numeric_limits::max() + 1, // which is caught by the above if statement. - BT_DEBUG_ASSERT(idx <= std::numeric_limits::max()); + PW_DCHECK(idx <= std::numeric_limits::max()); if (!state.callback(fit::ok(std::cref( state.response.attributes(static_cast(idx)))))) { break; @@ -303,7 +302,7 @@ void Impl::OnChannelClosed() { TransactionId Impl::GetNextId() { TransactionId next = next_tid_++; - BT_DEBUG_ASSERT(pending_.size() < std::numeric_limits::max()); + PW_DCHECK(pending_.size() < std::numeric_limits::max()); while (pending_.count(next)) { next = next_tid_++; // Note: overflow is fine } @@ -314,7 +313,7 @@ TransactionId Impl::GetNextId() { std::unique_ptr Client::Create(l2cap::Channel::WeakPtr channel, pw::async::Dispatcher& dispatcher) { - BT_DEBUG_ASSERT(channel.is_alive()); + PW_DCHECK(channel.is_alive()); return std::make_unique(std::move(channel), dispatcher); } diff --git a/pw_bluetooth_sapphire/host/sdp/data_element.cc b/pw_bluetooth_sapphire/host/sdp/data_element.cc index febb0f637e..0db3d1b62d 100644 --- a/pw_bluetooth_sapphire/host/sdp/data_element.cc +++ b/pw_bluetooth_sapphire/host/sdp/data_element.cc @@ -532,7 +532,7 @@ size_t DataElement::Read(DataElement* elem, const ByteBuffer& buffer) { } BufferView sequence_buf = cursor.view(0, data_bytes); size_t remaining = data_bytes; - BT_DEBUG_ASSERT(sequence_buf.size() == data_bytes); + PW_DCHECK(sequence_buf.size() == data_bytes); std::vector seq; while (remaining > 0) { @@ -544,7 +544,7 @@ size_t DataElement::Read(DataElement* elem, const ByteBuffer& buffer) { seq.push_back(std::move(next)); remaining -= used; } - BT_DEBUG_ASSERT(remaining == 0); + PW_DCHECK(remaining == 0); if (type_desc == Type::kAlternative) { elem->SetAlternative(std::move(seq)); } else { @@ -655,7 +655,7 @@ size_t DataElement::Write(MutableByteBuffer* buffer) const { } case Type::kUuid: { size_t written = uuid_.ToBytes(&cursor); - BT_DEBUG_ASSERT(written); + PW_DCHECK(written); // SDP is big-endian, so reverse. std::reverse(cursor.mutable_data(), cursor.mutable_data() + written); pos += written; @@ -664,7 +664,7 @@ size_t DataElement::Write(MutableByteBuffer* buffer) const { case Type::kString: case Type::kUrl: { size_t used = WriteLength(&cursor, bytes_.size()); - BT_DEBUG_ASSERT(used); + PW_DCHECK(used); pos += used; cursor.Write(bytes_.data(), bytes_.size(), used); pos += bytes_.size(); @@ -673,12 +673,12 @@ size_t DataElement::Write(MutableByteBuffer* buffer) const { case Type::kSequence: case Type::kAlternative: { size_t used = WriteLength(&cursor, AggregateSize(aggregate_)); - BT_DEBUG_ASSERT(used); + PW_DCHECK(used); pos += used; cursor = cursor.mutable_view(used); for (const auto& elem : aggregate_) { used = elem.Write(&cursor); - BT_DEBUG_ASSERT(used); + PW_DCHECK(used); pos += used; cursor = cursor.mutable_view(used); } diff --git a/pw_bluetooth_sapphire/host/sdp/pdu.cc b/pw_bluetooth_sapphire/host/sdp/pdu.cc index 8ff647bcad..becd74750e 100644 --- a/pw_bluetooth_sapphire/host/sdp/pdu.cc +++ b/pw_bluetooth_sapphire/host/sdp/pdu.cc @@ -46,7 +46,7 @@ constexpr size_t kMaxSupportedAttributeListBytes = 655360; // Returns true if the continuation state is valid here, false otherwise. // Sets |out| to point to it if present and valid. bool ValidContinuationState(const ByteBuffer& buf, BufferView* out) { - BT_DEBUG_ASSERT(out); + PW_DCHECK(out); if (buf.size() == 0) { return false; } @@ -173,7 +173,7 @@ void AddToAttributeRanges(std::list* ranges, Request::Request() { cont_state_.Fill(0); } void Request::SetContinuationState(const ByteBuffer& buf) { - BT_DEBUG_ASSERT(buf.size() < kMaxContStateLength); + PW_DCHECK(buf.size() < kMaxContStateLength); cont_state_[0] = static_cast(buf.size()); if (cont_state_[0] == 0) { return; @@ -192,7 +192,7 @@ bool Request::ParseContinuationState(const ByteBuffer& buf) { } size_t Request::WriteContinuationState(MutableByteBuffer* buf) const { - BT_DEBUG_ASSERT(buf->size() > cont_info_size()); + PW_DCHECK(buf->size() > cont_info_size()); size_t written_size = sizeof(uint8_t) + cont_info_size(); buf->Write(cont_state_.view(0, written_size)); return written_size; @@ -274,7 +274,7 @@ ServiceSearchRequest::ServiceSearchRequest(const ByteBuffer& params) service_search_pattern_.clear(); return; } - BT_DEBUG_ASSERT(valid()); + PW_DCHECK(valid()); } bool ServiceSearchRequest::valid() const { @@ -318,7 +318,7 @@ ByteBufferPtr ServiceSearchRequest::GetPDU(TransactionId tid) const { write_view = buf->mutable_view(written); written += WriteContinuationState(&write_view); - BT_DEBUG_ASSERT(written == sizeof(Header) + size); + PW_DCHECK(written == sizeof(Header) + size); return buf; } @@ -474,7 +474,7 @@ MutableByteBufferPtr ServiceSearchResponse::GetPDU( if (!buf) { return buf; } - BT_ASSERT(buf->size() <= max_size); + PW_CHECK(buf->size() <= max_size); size_t written = sizeof(Header); buf->WriteObj( @@ -504,7 +504,7 @@ MutableByteBufferPtr ServiceSearchResponse::GetPDU( written); written += sizeof(uint16_t); } - BT_DEBUG_ASSERT(written == sizeof(Header) + size); + PW_DCHECK(written == sizeof(Header) + size); return buf; } @@ -545,7 +545,7 @@ ServiceAttributeRequest::ServiceAttributeRequest(const ByteBuffer& params) { attribute_ranges_.clear(); return; } - BT_DEBUG_ASSERT(valid()); + PW_DCHECK(valid()); } bool ServiceAttributeRequest::valid() const { @@ -580,7 +580,7 @@ ByteBufferPtr ServiceAttributeRequest::GetPDU(TransactionId tid) const { // valid() ensures that |size| can't overflow due to too many attribute // ranges. - BT_DEBUG_ASSERT(size <= std::numeric_limits::max()); + PW_DCHECK(size <= std::numeric_limits::max()); auto buf = BuildNewPdu(kServiceAttributeRequest, tid, static_cast(size)); @@ -601,7 +601,7 @@ ByteBufferPtr ServiceAttributeRequest::GetPDU(TransactionId tid) const { mut_view = buf->mutable_view(written); written += WriteContinuationState(&mut_view); - BT_DEBUG_ASSERT(written == sizeof(Header) + size); + PW_DCHECK(written == sizeof(Header) + size); return buf; } @@ -843,7 +843,7 @@ MutableByteBufferPtr ServiceAttributeResponse::GetPDU( written); written += sizeof(uint32_t); } - BT_DEBUG_ASSERT(written == sizeof(Header) + size); + PW_DCHECK(written == sizeof(Header) + size); return buf; } @@ -919,7 +919,7 @@ ServiceSearchAttributeRequest::ServiceSearchAttributeRequest( max_attribute_byte_count_, attribute_ranges_.size()); - BT_DEBUG_ASSERT(valid()); + PW_DCHECK(valid()); } bool ServiceSearchAttributeRequest::valid() const { @@ -982,7 +982,7 @@ ByteBufferPtr ServiceSearchAttributeRequest::GetPDU(TransactionId tid) const { mut_view = buf->mutable_view(written); written += WriteContinuationState(&mut_view); - BT_DEBUG_ASSERT(written == sizeof(Header) + size); + PW_DCHECK(written == sizeof(Header) + size); return buf; } @@ -1013,7 +1013,7 @@ fit::result> ServiceSearchAttributeResponse::Parse( if (complete() && attribute_lists_.size() != 0) { // This response was previously complete and non-empty bt_log(TRACE, "sdp", "can't parse into a complete response"); - BT_DEBUG_ASSERT(!partial_response_); + PW_DCHECK(!partial_response_); return ToResult(HostError::kNotReady); } @@ -1259,15 +1259,15 @@ MutableByteBufferPtr ServiceSearchAttributeResponse::GetPDU( // Safe to cast because the value is constrained by the number of local // attributes, which will be much less than UINT32_MAX. bytes_skipped (an // untrusted value) is checked for out-of-range above. - BT_DEBUG_ASSERT(bytes_skipped + attribute_lists_byte_count < - std::numeric_limits::max()); + PW_DCHECK(bytes_skipped + attribute_lists_byte_count < + std::numeric_limits::max()); bytes_skipped = static_cast(bytes_skipped + attribute_lists_byte_count); buf->WriteObj(pw::bytes::ConvertOrderTo(cpp20::endian::big, bytes_skipped), written); written += sizeof(uint32_t); } - BT_DEBUG_ASSERT(written == sizeof(Header) + size); + PW_DCHECK(written == sizeof(Header) + size); return buf; } diff --git a/pw_bluetooth_sapphire/host/sdp/server.cc b/pw_bluetooth_sapphire/host/sdp/server.cc index d82db0b167..558339c9e6 100644 --- a/pw_bluetooth_sapphire/host/sdp/server.cc +++ b/pw_bluetooth_sapphire/host/sdp/server.cc @@ -139,7 +139,7 @@ l2cap::Psm FindProtocolListPsm(const DataElement& protocol_list) { "Trying to find PSM from %s", protocol_list.ToString().c_str()); const auto* l2cap_protocol = protocol_list.At(0); - BT_DEBUG_ASSERT(l2cap_protocol); + PW_DCHECK(l2cap_protocol); const auto* prot_uuid = l2cap_protocol->At(0); if (!prot_uuid || prot_uuid->type() != DataElement::Type::kUuid || *prot_uuid->Get() != protocol::kL2CAP) { @@ -249,7 +249,7 @@ Server::Server(l2cap::ChannelManager* l2cap) next_handle_(kFirstUnreservedHandle), db_state_(0), weak_ptr_factory_(this) { - BT_ASSERT(l2cap_); + PW_CHECK(l2cap_); records_.emplace(kSDPHandle, Server::MakeServiceDiscoveryService()); @@ -282,7 +282,7 @@ void Server::AttachInspect(inspect::Node& parent, std::string name) { } bool Server::AddConnection(l2cap::Channel::WeakPtr channel) { - BT_ASSERT(channel.is_alive()); + PW_CHECK(channel.is_alive()); hci_spec::ConnectionHandle handle = channel->link_handle(); bt_log(DEBUG, "sdp", "add connection handle %#.4x", handle); @@ -513,7 +513,7 @@ RegistrationHandle Server::RegisterService(std::vector records, assigned_handles.emplace(next); } - BT_ASSERT(assigned_handles.size() == records.size()); + PW_CHECK(assigned_handles.size() == records.size()); // The RegistrationHandle is the smallest ServiceHandle that was assigned. RegistrationHandle reg_handle = *assigned_handles.begin(); @@ -554,7 +554,7 @@ RegistrationHandle Server::RegisterService(std::vector records, // Store the complete records. for (auto& record : records) { auto [it, success] = records_.emplace(record.handle(), std::move(record)); - BT_DEBUG_ASSERT(success); + PW_DCHECK(success); const ServiceRecord& placed_record = it->second; if (placed_record.IsProtocolOnly()) { bt_log(TRACE, @@ -592,8 +592,8 @@ bool Server::UnregisterService(RegistrationHandle handle) { } for (const auto& svc_h : handles_it.mapped()) { - BT_ASSERT(svc_h != kSDPHandle); - BT_ASSERT(records_.find(svc_h) != records_.end()); + PW_CHECK(svc_h != kSDPHandle); + PW_CHECK(records_.find(svc_h) != records_.end()); bt_log(DEBUG, "sdp", "unregistering service (handle: %#.8x)", svc_h); // Unregister any service callbacks from L2CAP @@ -719,7 +719,7 @@ void Server::OnChannelClosed(l2cap::Channel::UniqueId channel_id) { std::optional Server::HandleRequest(ByteBufferPtr sdu, uint16_t max_tx_sdu_size) { - BT_DEBUG_ASSERT(sdu); + PW_DCHECK(sdu); TRACE_DURATION("bluetooth", "sdp::Server::HandleRequest"); if (sdu->size() < sizeof(Header)) { bt_log(DEBUG, "sdp", "PDU too short; dropping"); diff --git a/pw_bluetooth_sapphire/host/sdp/service_discoverer.cc b/pw_bluetooth_sapphire/host/sdp/service_discoverer.cc index 0b19feab13..a7c6e699c3 100644 --- a/pw_bluetooth_sapphire/host/sdp/service_discoverer.cc +++ b/pw_bluetooth_sapphire/host/sdp/service_discoverer.cc @@ -29,11 +29,10 @@ ServiceDiscoverer::SearchId ServiceDiscoverer::AddSearch( s.uuid = uuid; s.attributes = std::move(attributes); s.callback = std::move(callback); - BT_DEBUG_ASSERT(next_id_ < - std::numeric_limits::max()); + PW_DCHECK(next_id_ < std::numeric_limits::max()); ServiceDiscoverer::SearchId id = next_id_++; auto [it, placed] = searches_.emplace(id, std::move(s)); - BT_DEBUG_ASSERT_MSG(placed, "Should always be able to place new search"); + PW_DCHECK(placed, "Should always be able to place new search"); return id; } @@ -66,10 +65,10 @@ void ServiceDiscoverer::SingleSearch(SearchId search_id, DiscoverySession session; session.client = std::move(client); auto placed = sessions_.emplace(peer_id, std::move(session)); - BT_DEBUG_ASSERT(placed.second); + PW_DCHECK(placed.second); session_iter = placed.first; } - BT_DEBUG_ASSERT(session_iter != sessions_.end()); + PW_DCHECK(session_iter != sessions_.end()); auto search_it = searches_.find(search_id); if (search_it == searches_.end()) { bt_log(INFO, "sdp", "Couldn't find search with id %" PRIu64, search_id); diff --git a/pw_bluetooth_sapphire/host/sdp/service_record.cc b/pw_bluetooth_sapphire/host/sdp/service_record.cc index afa22e9810..f9c0158557 100644 --- a/pw_bluetooth_sapphire/host/sdp/service_record.cc +++ b/pw_bluetooth_sapphire/host/sdp/service_record.cc @@ -68,7 +68,7 @@ void ServiceRecord::SetAttribute(AttributeId id, DataElement value) { const DataElement& ServiceRecord::GetAttribute(AttributeId id) const { auto it = attributes_.find(id); - BT_DEBUG_ASSERT_MSG(it != attributes_.end(), "attribute %#.4x not set!", id); + PW_DCHECK(it != attributes_.end(), "attribute %#.4x not set!", id); return it->second; } @@ -267,7 +267,7 @@ bool ServiceRecord::AddInfo(const std::string& language_code, // "%" can't be in pw_assert statements. const size_t list_size_mod_3 = base_attr_list.size() % 3; - BT_DEBUG_ASSERT(list_size_mod_3 == 0); + PW_DCHECK(list_size_mod_3 == 0); // 0x0100 is guaranteed to be taken, start counting from higher. base_attrid = 0x9000; @@ -326,7 +326,7 @@ std::vector ServiceRecord::GetInfo() const { std::vector out; const auto& base_id_seq = base_id_list.Get>(); const size_t list_size_mod_3 = base_id_seq->size() % 3; - BT_DEBUG_ASSERT(list_size_mod_3 == 0); + PW_DCHECK(list_size_mod_3 == 0); for (size_t i = 0; i + 2 < base_id_seq->size(); i += 3) { // Each entry is a triplet of uint16_t (language_code, encoding format, base diff --git a/pw_bluetooth_sapphire/host/sm/ecdh_key.cc b/pw_bluetooth_sapphire/host/sm/ecdh_key.cc index c7fccee8f2..6a802cb85e 100644 --- a/pw_bluetooth_sapphire/host/sm/ecdh_key.cc +++ b/pw_bluetooth_sapphire/host/sm/ecdh_key.cc @@ -43,8 +43,8 @@ std::optional EcdhKey::ParseFromPublicKey( BN_init(&y); // Assert on le2bn output. le2bn "returns NULL on allocation failure", but // allocation should never fail on Fuchsia per overcommit semantics. - BT_ASSERT(BN_le2bn(pub_key.x, sizeof(pub_key.x), &x)); - BT_ASSERT(BN_le2bn(pub_key.y, sizeof(pub_key.y), &y)); + PW_CHECK(BN_le2bn(pub_key.x, sizeof(pub_key.x), &x)); + PW_CHECK(BN_le2bn(pub_key.y, sizeof(pub_key.y), &y)); // One potential cause of failure is if pub_key is not a valid ECDH key on the // P-256 curve. @@ -73,13 +73,13 @@ sm::PairingPublicKeyParams EcdhKey::GetSerializedPublicKey() const { BIGNUM x, y; BN_init(&x); BN_init(&y); - BT_ASSERT(EC_POINT_get_affine_coordinates_GFp(EC_KEY_get0_group(key_), - EC_KEY_get0_public_key(key_), - &x, - &y, - nullptr) == 1); - BT_ASSERT(BN_bn2le_padded(params.x, sizeof(params.x), &x) == 1); - BT_ASSERT(BN_bn2le_padded(params.y, sizeof(params.y), &y) == 1); + PW_CHECK(EC_POINT_get_affine_coordinates_GFp(EC_KEY_get0_group(key_), + EC_KEY_get0_public_key(key_), + &x, + &y, + nullptr) == 1); + PW_CHECK(BN_bn2le_padded(params.x, sizeof(params.x), &x) == 1); + PW_CHECK(BN_bn2le_padded(params.y, sizeof(params.y), &y) == 1); BN_free(&x); BN_free(&y); return params; @@ -94,10 +94,10 @@ UInt256 EcdhKey::GetPublicKeyX() const { &x, /*y=*/nullptr, /*ctx=*/nullptr) == 1; - BT_ASSERT(success); + PW_CHECK(success); UInt256 out{}; success = BN_bn2le_padded(out.data(), out.size(), &x) == 1; - BT_ASSERT(success); + PW_CHECK(success); BN_free(&x); return out; } @@ -111,10 +111,10 @@ UInt256 EcdhKey::GetPublicKeyY() const { /*x=*/nullptr, &y, /*ctx=*/nullptr) == 1; - BT_ASSERT(success); + PW_CHECK(success); UInt256 out{}; success = BN_bn2le_padded(out.data(), out.size(), &y) == 1; - BT_ASSERT(success); + PW_CHECK(success); BN_free(&y); return out; } @@ -158,7 +158,7 @@ UInt256 LocalEcdhKey::CalculateDhKey(const EcdhKey& peer_public_key) const { EC_KEY_get0_public_key(peer_public_key.boringssl_key()), boringssl_key(), /*kdf=*/nullptr) == out.size(); - BT_ASSERT(success); + PW_CHECK(success); std::reverse(out.begin(), out.end()); return out; } @@ -167,8 +167,8 @@ void LocalEcdhKey::SetPrivateKeyForTesting(const UInt256& private_key) { BIGNUM pkey; BN_init(&pkey); BN_le2bn(private_key.data(), private_key.size(), &pkey); - BT_ASSERT_MSG(EC_KEY_set_private_key(mut_boringssl_key(), &pkey) == 1, - "Could not set private key in test"); + PW_CHECK(EC_KEY_set_private_key(mut_boringssl_key(), &pkey) == 1, + "Could not set private key in test"); BN_free(&pkey); } diff --git a/pw_bluetooth_sapphire/host/sm/error.cc b/pw_bluetooth_sapphire/host/sm/error.cc index 9ad11af648..146267cd22 100644 --- a/pw_bluetooth_sapphire/host/sm/error.cc +++ b/pw_bluetooth_sapphire/host/sm/error.cc @@ -71,7 +71,7 @@ std::string ProtocolErrorTraits::ToString(sm::ErrorCode ecode) { "%s (SMP %#.2x)", ErrorToString(ecode), static_cast(ecode)); - BT_DEBUG_ASSERT(status.ok()); + PW_DCHECK(status.ok()); return out; } diff --git a/pw_bluetooth_sapphire/host/sm/packet.cc b/pw_bluetooth_sapphire/host/sm/packet.cc index ea167b9a95..fc1f6bb7dc 100644 --- a/pw_bluetooth_sapphire/host/sm/packet.cc +++ b/pw_bluetooth_sapphire/host/sm/packet.cc @@ -30,7 +30,7 @@ ValidPacketReader::ValidPacketReader(const ByteBuffer* buffer) fit::result ValidPacketReader::ParseSdu( const ByteBufferPtr& sdu) { - BT_ASSERT(sdu); + PW_CHECK(sdu); size_t length = sdu->size(); if (length < sizeof(Header)) { bt_log(DEBUG, "sm", "PDU too short!"); diff --git a/pw_bluetooth_sapphire/host/sm/pairing_channel.cc b/pw_bluetooth_sapphire/host/sm/pairing_channel.cc index d3863a5b39..ec3c65e04e 100644 --- a/pw_bluetooth_sapphire/host/sm/pairing_channel.cc +++ b/pw_bluetooth_sapphire/host/sm/pairing_channel.cc @@ -27,11 +27,11 @@ PairingChannel::PairingChannel(l2cap::Channel::WeakPtr chan, : chan_(std::move(chan)), reset_timer_(std::move(timer_resetter)), weak_self_(this) { - BT_ASSERT(chan_); + PW_CHECK(chan_); if (chan_->link_type() == bt::LinkType::kLE) { - BT_ASSERT(chan_->id() == l2cap::kLESMPChannelId); + PW_CHECK(chan_->id() == l2cap::kLESMPChannelId); } else if (chan_->link_type() == bt::LinkType::kACL) { - BT_ASSERT(chan_->id() == l2cap::kSMPChannelId); + PW_CHECK(chan_->id() == l2cap::kSMPChannelId); } else { BT_PANIC("unsupported link type for SMP!"); } @@ -54,15 +54,15 @@ PairingChannel::PairingChannel(l2cap::Channel::WeakPtr chan, // is no way to configure this MTU, so we expect that L2CAP always provides a // channel with a sufficiently large MTU. This assertion serves as an explicit // acknowledgement of that contract between L2CAP and SMP. - BT_ASSERT(chan_->max_tx_sdu_size() >= kNoSecureConnectionsMtu && - chan_->max_rx_sdu_size() >= kNoSecureConnectionsMtu); + PW_CHECK(chan_->max_tx_sdu_size() >= kNoSecureConnectionsMtu && + chan_->max_rx_sdu_size() >= kNoSecureConnectionsMtu); } PairingChannel::PairingChannel(l2cap::Channel::WeakPtr chan) : PairingChannel(std::move(chan), []() {}) {} void PairingChannel::SetChannelHandler(Handler::WeakPtr new_handler) { - BT_ASSERT(new_handler.is_alive()); + PW_CHECK(new_handler.is_alive()); bt_log(TRACE, "sm", "changing pairing channel handler"); handler_ = std::move(new_handler); } diff --git a/pw_bluetooth_sapphire/host/sm/pairing_phase.cc b/pw_bluetooth_sapphire/host/sm/pairing_phase.cc index 24bd8d8f21..a73152762f 100644 --- a/pw_bluetooth_sapphire/host/sm/pairing_phase.cc +++ b/pw_bluetooth_sapphire/host/sm/pairing_phase.cc @@ -39,15 +39,15 @@ void PairingPhase::InvalidatePairingChannelHandler() { } void PairingPhase::OnFailure(Error error) { - BT_ASSERT(!has_failed()); + PW_CHECK(!has_failed()); bt_log(WARN, "sm", "pairing failed: %s", bt_str(error)); has_failed_ = true; - BT_ASSERT(listener_.is_alive()); + PW_CHECK(listener_.is_alive()); listener_->OnPairingFailed(error); } void PairingPhase::Abort(ErrorCode ecode) { - BT_ASSERT(!has_failed()); + PW_CHECK(!has_failed()); Error error(ecode); bt_log(INFO, "sm", "abort pairing: %s", bt_str(error)); diff --git a/pw_bluetooth_sapphire/host/sm/phase_1.cc b/pw_bluetooth_sapphire/host/sm/phase_1.cc index 15ca850529..14d0621465 100644 --- a/pw_bluetooth_sapphire/host/sm/phase_1.cc +++ b/pw_bluetooth_sapphire/host/sm/phase_1.cc @@ -86,29 +86,29 @@ Phase1::Phase1(PairingChannel::WeakPtr chan, io_capability_(io_capability), bondable_mode_(bondable_mode), on_complete_(std::move(on_complete)) { - BT_ASSERT(!(role == Role::kInitiator && preq_.has_value())); - BT_ASSERT(!(role == Role::kResponder && !preq_.has_value())); - BT_ASSERT(requested_level_ >= SecurityLevel::kEncrypted); + PW_CHECK(!(role == Role::kInitiator && preq_.has_value())); + PW_CHECK(!(role == Role::kResponder && !preq_.has_value())); + PW_CHECK(requested_level_ >= SecurityLevel::kEncrypted); if (requested_level_ > SecurityLevel::kEncrypted) { - BT_ASSERT(io_capability != IOCapability::kNoInputNoOutput); + PW_CHECK(io_capability != IOCapability::kNoInputNoOutput); } SetPairingChannelHandler(*this); } void Phase1::Start() { - BT_ASSERT(!has_failed()); + PW_CHECK(!has_failed()); if (role() == Role::kResponder) { - BT_ASSERT(preq_.has_value()); + PW_CHECK(preq_.has_value()); RespondToPairingRequest(*preq_); return; } - BT_ASSERT(!preq_.has_value()); + PW_CHECK(!preq_.has_value()); InitiateFeatureExchange(); } void Phase1::InitiateFeatureExchange() { // Only the initiator can initiate the feature exchange. - BT_ASSERT(role() == Role::kInitiator); + PW_CHECK(role() == Role::kInitiator); LocalPairingParams preq_values = BuildPairingParameters(); preq_ = PairingRequestParams{ .io_capability = preq_values.io_capability, @@ -123,7 +123,7 @@ void Phase1::InitiateFeatureExchange() { void Phase1::RespondToPairingRequest(const PairingRequestParams& req_params) { // We should only be in this state when pairing is initiated by the remote // i.e. we are the responder. - BT_ASSERT(role() == Role::kResponder); + PW_CHECK(role() == Role::kResponder); LocalPairingParams pres_values = BuildPairingParameters(); pres_ = PairingResponseParams{ @@ -179,7 +179,7 @@ LocalPairingParams Phase1::BuildPairingParameters() { // We always request identity information from the remote. local_params.remote_keys = KeyDistGen::kIdKey; - BT_ASSERT(listener().is_alive()); + PW_CHECK(listener().is_alive()); if (listener()->OnIdentityRequest().has_value()) { local_params.local_keys |= KeyDistGen::kIdKey; } @@ -279,8 +279,8 @@ fit::result Phase1::ResolveFeatures( remote_keys = pres.initiator_key_dist_gen; // When we are the responder we always respect the initiator's wishes. - BT_ASSERT((preq.initiator_key_dist_gen & remote_keys) == remote_keys); - BT_ASSERT((preq.responder_key_dist_gen & local_keys) == local_keys); + PW_CHECK((preq.initiator_key_dist_gen & remote_keys) == remote_keys); + PW_CHECK((preq.responder_key_dist_gen & local_keys) == local_keys); } // v5.1 Vol 3 Part C Section 9.4.2.2 says that bonding information shall not // be exchanged or stored in non-bondable mode. This check ensures that we diff --git a/pw_bluetooth_sapphire/host/sm/phase_2_legacy.cc b/pw_bluetooth_sapphire/host/sm/phase_2_legacy.cc index 0b4f680fa7..9aec51b51d 100644 --- a/pw_bluetooth_sapphire/host/sm/phase_2_legacy.cc +++ b/pw_bluetooth_sapphire/host/sm/phase_2_legacy.cc @@ -64,23 +64,23 @@ Phase2Legacy::Phase2Legacy(PairingChannel::WeakPtr chan, on_stk_ready_(std::move(cb)), weak_self_(this) { // Cache |preq| and |pres|. These are used for confirm value generation. - BT_ASSERT(preq.size() == preq_.size()); - BT_ASSERT(pres.size() == pres_.size()); - BT_ASSERT_MSG(IsSupportedLegacyMethod(features.method), - "unsupported legacy pairing method!"); + PW_CHECK(preq.size() == preq_.size()); + PW_CHECK(pres.size() == pres_.size()); + PW_CHECK(IsSupportedLegacyMethod(features.method), + "unsupported legacy pairing method!"); preq.Copy(&preq_); pres.Copy(&pres_); SetPairingChannelHandler(*this); } void Phase2Legacy::Start() { - BT_ASSERT(!has_failed()); - BT_ASSERT(!features_.secure_connections); - BT_ASSERT(!tk_.has_value()); - BT_ASSERT(!peer_confirm_.has_value()); - BT_ASSERT(!peer_rand_.has_value()); - BT_ASSERT(!sent_local_confirm_); - BT_ASSERT(!sent_local_rand_); + PW_CHECK(!has_failed()); + PW_CHECK(!features_.secure_connections); + PW_CHECK(!tk_.has_value()); + PW_CHECK(!peer_confirm_.has_value()); + PW_CHECK(!peer_rand_.has_value()); + PW_CHECK(!sent_local_confirm_); + PW_CHECK(!sent_local_rand_); MakeTemporaryKeyRequest(); } @@ -89,7 +89,7 @@ void Phase2Legacy::MakeTemporaryKeyRequest() { "sm", "TK request - method: %s", sm::util::PairingMethodToString(features_.method).c_str()); - BT_ASSERT(listener().is_alive()); + PW_CHECK(listener().is_alive()); auto self = weak_self_.GetWeakPtr(); if (features_.method == sm::PairingMethod::kPasskeyEntryInput) { // The TK will be provided by the user. @@ -123,7 +123,7 @@ void Phase2Legacy::MakeTemporaryKeyRequest() { } // TODO(fxbug.dev/42138242): Support providing a TK out of band. - BT_ASSERT(features_.method == sm::PairingMethod::kJustWorks); + PW_CHECK(features_.method == sm::PairingMethod::kJustWorks); listener()->ConfirmPairing([self](bool confirm) { if (!self.is_alive()) { return; @@ -172,8 +172,8 @@ void Phase2Legacy::HandleTemporaryKey(std::optional maybe_tk) { } void Phase2Legacy::SendConfirmValue() { - BT_ASSERT(!sent_local_confirm_); - BT_ASSERT(local_confirm_.has_value()); + PW_CHECK(!sent_local_confirm_); + PW_CHECK(local_confirm_.has_value()); // Only allowed on the LE transport. if (sm_chan().link_type() != bt::LinkType::kLE) { bt_log(DEBUG, @@ -198,8 +198,8 @@ void Phase2Legacy::OnPairingConfirm(PairingConfirmValue confirm) { // We MUST have a TK and have previously generated an Mconfirm - this was // implicitly checked in CanReceivePairingConfirm by checking whether we've // sent the confirm value. - BT_ASSERT(tk_.has_value()); - BT_ASSERT(sent_local_confirm_); + PW_CHECK(tk_.has_value()); + PW_CHECK(sent_local_confirm_); // We have sent Mconfirm and just received Sconfirm. We now send Mrand for // the peer to compare. @@ -213,11 +213,11 @@ void Phase2Legacy::OnPairingConfirm(PairingConfirmValue confirm) { } void Phase2Legacy::SendRandomValue() { - BT_ASSERT(!sent_local_rand_); + PW_CHECK(!sent_local_rand_); // This is always generated in the TK callback, which must have been called by // now as the random are sent after the confirm values, and the TK must exist // in order to send the confirm. - BT_ASSERT(local_rand_.has_value()); + PW_CHECK(local_rand_.has_value()); // Only allowed on the LE transport. if (sm_chan().link_type() != bt::LinkType::kLE) { @@ -236,9 +236,9 @@ void Phase2Legacy::OnPairingRandom(PairingRandomValue rand) { return; } // These should have been checked in CanReceivePairingRandom - BT_ASSERT(local_rand_.has_value()); - BT_ASSERT(tk_.has_value()); - BT_ASSERT(peer_confirm_.has_value()); + PW_CHECK(local_rand_.has_value()); + PW_CHECK(tk_.has_value()); + PW_CHECK(peer_confirm_.has_value()); peer_rand_ = rand; @@ -359,7 +359,7 @@ fit::result Phase2Legacy::CanReceivePairingRandom() const { } else { // We know we have not received Mrand, and should not have sent Srand // without receiving Mrand. - BT_ASSERT(!sent_local_rand_); + PW_CHECK(!sent_local_rand_); // We need to send Sconfirm before the initiator sends Mrand. if (!sent_local_confirm_) { diff --git a/pw_bluetooth_sapphire/host/sm/phase_2_legacy_test.cc b/pw_bluetooth_sapphire/host/sm/phase_2_legacy_test.cc index 6e8f1fa372..ef502cac51 100644 --- a/pw_bluetooth_sapphire/host/sm/phase_2_legacy_test.cc +++ b/pw_bluetooth_sapphire/host/sm/phase_2_legacy_test.cc @@ -166,10 +166,10 @@ class Phase2LegacyTest : public l2cap::testing::FakeChannelTest { } static std::pair ExtractCodeAnd128BitCmd(ByteBufferPtr sdu) { - BT_ASSERT_MSG(sdu, "Tried to ExtractCodeAnd128BitCmd from nullptr in test"); + PW_CHECK(sdu, "Tried to ExtractCodeAnd128BitCmd from nullptr in test"); auto maybe_reader = ValidPacketReader::ParseSdu(sdu); - BT_ASSERT_MSG(maybe_reader.is_ok(), - "Tried to ExtractCodeAnd128BitCmd from invalid SMP packet"); + PW_CHECK(maybe_reader.is_ok(), + "Tried to ExtractCodeAnd128BitCmd from invalid SMP packet"); return {maybe_reader.value().code(), maybe_reader.value().payload()}; } diff --git a/pw_bluetooth_sapphire/host/sm/phase_2_secure_connections.cc b/pw_bluetooth_sapphire/host/sm/phase_2_secure_connections.cc index f11136068c..95db8d0db9 100644 --- a/pw_bluetooth_sapphire/host/sm/phase_2_secure_connections.cc +++ b/pw_bluetooth_sapphire/host/sm/phase_2_secure_connections.cc @@ -58,32 +58,32 @@ Phase2SecureConnections::Phase2SecureConnections( responder_addr_(responder_addr), weak_self_(this), on_ltk_ready_(std::move(cb)) { - BT_ASSERT(features_.secure_connections); + PW_CHECK(features_.secure_connections); local_ecdh_ = LocalEcdhKey::Create(); - BT_ASSERT_MSG(local_ecdh_.has_value(), "failed to generate ecdh key"); - BT_ASSERT(sm_chan().SupportsSecureConnections()); + PW_CHECK(local_ecdh_.has_value(), "failed to generate ecdh key"); + PW_CHECK(sm_chan().SupportsSecureConnections()); SetPairingChannelHandler(*this); } void Phase2SecureConnections::Start() { - BT_ASSERT(!has_failed()); + PW_CHECK(!has_failed()); if (role() == Role::kInitiator) { SendLocalPublicKey(); } } void Phase2SecureConnections::SendLocalPublicKey() { - BT_ASSERT(!sent_local_ecdh_); + PW_CHECK(!sent_local_ecdh_); // If in the responder role (i.e. not in the initiator role), attempting to // send our Public Key before we've received the peer's is a programmer error. - BT_ASSERT(role() == Role::kInitiator || peer_ecdh_.has_value()); + PW_CHECK(role() == Role::kInitiator || peer_ecdh_.has_value()); sm_chan().SendMessage(kPairingPublicKey, local_ecdh_->GetSerializedPublicKey()); sent_local_ecdh_ = true; bt_log(DEBUG, "sm", "sent ecdh public key to peer"); if (role() == Role::kResponder) { - BT_ASSERT(ecdh_exchange_complete()); + PW_CHECK(ecdh_exchange_complete()); StartAuthenticationStage1(); } } @@ -123,7 +123,7 @@ void Phase2SecureConnections::OnPeerPublicKey( } EcdhKey peer_key = std::move(*maybe_peer_key); - BT_ASSERT(local_ecdh_.has_value()); + PW_CHECK(local_ecdh_.has_value()); if (peer_key.GetPublicKeyX() == local_ecdh_->GetPublicKeyX() && peer_key.GetPublicKeyY() == local_ecdh_->GetPublicKeyY()) { // NOTE(fxbug.dev/42161018): When passkey entry is used, the non-initiating @@ -145,13 +145,13 @@ void Phase2SecureConnections::OnPeerPublicKey( if (role() == Role::kResponder) { SendLocalPublicKey(); } else { - BT_ASSERT(ecdh_exchange_complete()); + PW_CHECK(ecdh_exchange_complete()); StartAuthenticationStage1(); } } void Phase2SecureConnections::StartAuthenticationStage1() { - BT_ASSERT(peer_ecdh_); + PW_CHECK(peer_ecdh_); auto self = weak_self_.GetWeakPtr(); auto complete_cb = [self](fit::result result) { if (self.is_alive()) { @@ -190,11 +190,11 @@ void Phase2SecureConnections::StartAuthenticationStage1() { void Phase2SecureConnections::OnAuthenticationStage1Complete( fit::result result) { - BT_ASSERT(peer_ecdh_.has_value()); - BT_ASSERT(stage_1_); - BT_ASSERT(!ltk_.has_value()); - BT_ASSERT(!expected_peer_dhkey_check_.has_value()); - BT_ASSERT(!local_dhkey_check_.has_value()); + PW_CHECK(peer_ecdh_.has_value()); + PW_CHECK(stage_1_); + PW_CHECK(!ltk_.has_value()); + PW_CHECK(!expected_peer_dhkey_check_.has_value()); + PW_CHECK(!local_dhkey_check_.has_value()); // The presence of Stage 1 determines whether to accept PairingConfirm/Random // packets, so as it is now over, it should be reset. stage_1_ = nullptr; @@ -208,7 +208,7 @@ void Phase2SecureConnections::OnAuthenticationStage1Complete( } void Phase2SecureConnections::StartAuthenticationStage2() { - BT_ASSERT(stage_1_results_.has_value()); + PW_CHECK(stage_1_results_.has_value()); std::optional maybe_f5 = util::F5(local_ecdh_->CalculateDhKey(peer_ecdh_.value()), stage_1_results_->initiator_rand, @@ -268,10 +268,10 @@ void Phase2SecureConnections::StartAuthenticationStage2() { } void Phase2SecureConnections::SendDhKeyCheckE() { - BT_ASSERT(stage_1_results_.has_value()); - BT_ASSERT(!sent_local_dhkey_check_); - BT_ASSERT(ltk_.has_value()); - BT_ASSERT(local_dhkey_check_.has_value()); + PW_CHECK(stage_1_results_.has_value()); + PW_CHECK(!sent_local_dhkey_check_); + PW_CHECK(ltk_.has_value()); + PW_CHECK(local_dhkey_check_.has_value()); // Send local DHKey Check sm_chan().SendMessage(kPairingDHKeyCheck, *local_dhkey_check_); @@ -280,7 +280,7 @@ void Phase2SecureConnections::SendDhKeyCheckE() { // As responder, we should only send the local DHKey check after receiving // and validating the peer's. The presence of `peer_dhkey_check` verifies // this invariant. - BT_ASSERT(actual_peer_dhkey_check_.has_value()); + PW_CHECK(actual_peer_dhkey_check_.has_value()); on_ltk_ready_(ltk_.value()); } } @@ -321,16 +321,16 @@ void Phase2SecureConnections::OnDhKeyCheck(PairingDHKeyCheckValueE check) { // waiting for user input in Stage 1 - if that happens, we validate the peer // DhKey check when Stage 1 completes. if (!stage_1_results_.has_value()) { - BT_ASSERT(role() == Role::kResponder); - BT_ASSERT(stage_1_); + PW_CHECK(role() == Role::kResponder); + PW_CHECK(stage_1_); return; } ValidatePeerDhKeyCheck(); } void Phase2SecureConnections::ValidatePeerDhKeyCheck() { - BT_ASSERT(actual_peer_dhkey_check_.has_value()); - BT_ASSERT(expected_peer_dhkey_check_.has_value()); + PW_CHECK(actual_peer_dhkey_check_.has_value()); + PW_CHECK(expected_peer_dhkey_check_.has_value()); if (*expected_peer_dhkey_check_ != *actual_peer_dhkey_check_) { bt_log(WARN, "sm", diff --git a/pw_bluetooth_sapphire/host/sm/phase_2_secure_connections_test.cc b/pw_bluetooth_sapphire/host/sm/phase_2_secure_connections_test.cc index 788a3829c8..36137d9fd4 100644 --- a/pw_bluetooth_sapphire/host/sm/phase_2_secure_connections_test.cc +++ b/pw_bluetooth_sapphire/host/sm/phase_2_secure_connections_test.cc @@ -124,10 +124,10 @@ class Phase2SecureConnectionsTest : public l2cap::testing::FakeChannelTest { } static std::pair ExtractCodeAnd128BitCmd(ByteBufferPtr sdu) { - BT_ASSERT_MSG(sdu, "Tried to ExtractCodeAnd128BitCmd from nullptr in test"); + PW_CHECK(sdu, "Tried to ExtractCodeAnd128BitCmd from nullptr in test"); auto maybe_reader = ValidPacketReader::ParseSdu(sdu); - BT_ASSERT_MSG(maybe_reader.is_ok(), - "Tried to ExtractCodeAnd128BitCmd from invalid SMP packet"); + PW_CHECK(maybe_reader.is_ok(), + "Tried to ExtractCodeAnd128BitCmd from invalid SMP packet"); return {maybe_reader.value().code(), maybe_reader.value().payload()}; } @@ -153,34 +153,33 @@ class Phase2SecureConnectionsTest : public l2cap::testing::FakeChannelTest { if (phase_2_sc_->role() == Role::kInitiator) { phase_2_sc_->Start(); RunUntilIdle(); - BT_ASSERT_MSG(local_key_.has_value(), - "initiator did not send ecdh key upon starting"); + PW_CHECK(local_key_.has_value(), + "initiator did not send ecdh key upon starting"); ReceiveCmd(kPairingPublicKey, peer_key_.GetSerializedPublicKey()); RunUntilIdle(); } else { phase_2_sc_->Start(); ReceiveCmd(kPairingPublicKey, peer_key_.GetSerializedPublicKey()); RunUntilIdle(); - BT_ASSERT_MSG(local_key_.has_value(), - "responder did not send ecdh key upon peer key"); + PW_CHECK(local_key_.has_value(), + "responder did not send ecdh key upon peer key"); if (features_.method == PairingMethod::kJustWorks || features_.method == PairingMethod::kNumericComparison) { - BT_ASSERT(responder_jw_nc_confirm.has_value()); + PW_CHECK(responder_jw_nc_confirm.has_value()); return responder_jw_nc_confirm; } } // We should only send confirm value immediately after ECDH key as responder // in Numeric Comparison/Just Works pairing, in which case we would've // already returned. - BT_ASSERT(!responder_jw_nc_confirm.has_value()); + PW_CHECK(!responder_jw_nc_confirm.has_value()); return responder_jw_nc_confirm; } UInt128 GenerateConfirmValue(const UInt128& random, bool gen_initiator_confirm, uint8_t r = 0) const { - BT_ASSERT_MSG(local_key_.has_value(), - "cannot compute confirm, missing key!"); + PW_CHECK(local_key_.has_value(), "cannot compute confirm, missing key!"); UInt256 pka = local_key_->GetPublicKeyX(), pkb = peer_key_.GetPublicKeyX(); if (phase_2_sc_->role() == Role::kResponder) { std::swap(pka, pkb); @@ -241,7 +240,7 @@ class Phase2SecureConnectionsTest : public l2cap::testing::FakeChannelTest { } LtkAndChecks FastForwardToDhKeyCheck() { - BT_ASSERT_MSG( + PW_CHECK( features_.method == PairingMethod::kJustWorks, "Fast forward to DHKey check only implemented for JustWorks method"); return phase_2_sc_->role() == Role::kInitiator @@ -272,8 +271,8 @@ class Phase2SecureConnectionsTest : public l2cap::testing::FakeChannelTest { MatchingPair stage1_vals = GenerateMatchingConfirmAndRandom(); ReceiveCmd(kPairingConfirm, stage1_vals.confirm); RunUntilIdle(); - BT_ASSERT_MSG(kPairingRandom == sent_code, - "did not send pairing random when expected!"); + PW_CHECK(kPairingRandom == sent_code, + "did not send pairing random when expected!"); ReceiveCmd(kPairingRandom, stage1_vals.random); RunUntilIdle(); @@ -294,11 +293,11 @@ class Phase2SecureConnectionsTest : public l2cap::testing::FakeChannelTest { ReceiveCmd(kPairingRandom, initiator_rand); RunUntilIdle(); - BT_ASSERT_MSG(kPairingRandom == sent_code, - "did not send pairing random when expected!"); - BT_ASSERT_MSG(GenerateConfirmValue( - rsp_rand, /*gen_initiator_confirm=*/false) == rsp_confirm, - "send invalid confirm value as JustWorks responder"); + PW_CHECK(kPairingRandom == sent_code, + "did not send pairing random when expected!"); + PW_CHECK(GenerateConfirmValue(rsp_rand, /*gen_initiator_confirm=*/false) == + rsp_confirm, + "send invalid confirm value as JustWorks responder"); return GenerateLtkAndChecks(initiator_rand, rsp_rand); } diff --git a/pw_bluetooth_sapphire/host/sm/phase_3.cc b/pw_bluetooth_sapphire/host/sm/phase_3.cc index e4c97a6c5b..9443f0332c 100644 --- a/pw_bluetooth_sapphire/host/sm/phase_3.cc +++ b/pw_bluetooth_sapphire/host/sm/phase_3.cc @@ -46,21 +46,20 @@ Phase3::Phase3(PairingChannel::WeakPtr chan, sent_local_keys_(false), on_complete_(std::move(on_complete)) { // LTKs may not be distributed during Secure Connections. - BT_ASSERT_MSG( - !(features_.secure_connections && - (ShouldSendLtk() || ShouldReceiveLtk())), - "Phase 3 may not distribute the LTK in Secure Connections pairing"); + PW_CHECK(!(features_.secure_connections && + (ShouldSendLtk() || ShouldReceiveLtk())), + "Phase 3 may not distribute the LTK in Secure Connections pairing"); - BT_ASSERT(HasKeysToDistribute(features_)); + PW_CHECK(HasKeysToDistribute(features_)); // The link must be encrypted with at least an STK in order for Phase 3 to // take place. - BT_ASSERT(le_sec.level() != SecurityLevel::kNoSecurity); + PW_CHECK(le_sec.level() != SecurityLevel::kNoSecurity); SetPairingChannelHandler(*this); } void Phase3::Start() { - BT_ASSERT(!has_failed()); - BT_ASSERT(!KeyExchangeComplete()); + PW_CHECK(!has_failed()); + PW_CHECK(!KeyExchangeComplete()); if (role() == Role::kInitiator && !RequestedKeysObtained()) { bt_log(DEBUG, "sm", "waiting to receive keys from the responder"); @@ -112,7 +111,7 @@ void Phase3::OnEncryptionInformation(const EncryptionInformationParams& ltk) { // Check that the received key has 0s at all locations more significant than // negotiated key_size uint8_t key_size = features_.encryption_key_size; - BT_DEBUG_ASSERT(key_size <= ltk.size()); + PW_DCHECK(key_size <= ltk.size()); for (auto i = key_size; i < ltk.size(); i++) { if (ltk[i] != 0) { bt_log(WARN, "sm", "received LTK is larger than max keysize! aborting"); @@ -121,7 +120,7 @@ void Phase3::OnEncryptionInformation(const EncryptionInformationParams& ltk) { } } - BT_DEBUG_ASSERT(!(obtained_remote_keys_ & KeyDistGen::kEncKey)); + PW_DCHECK(!(obtained_remote_keys_ & KeyDistGen::kEncKey)); peer_ltk_bytes_ = ltk; // Wait to receive EDiv and Rand @@ -190,7 +189,7 @@ void Phase3::OnIdentityInformation(const IRK& irk) { return; } - BT_DEBUG_ASSERT(!(obtained_remote_keys_ & KeyDistGen::kIdKey)); + PW_DCHECK(!(obtained_remote_keys_ & KeyDistGen::kIdKey)); irk_ = irk; // Wait to receive identity address @@ -254,7 +253,7 @@ void Phase3::OnExpectedKeyReceived() { } bool Phase3::SendLocalKeys() { - BT_DEBUG_ASSERT(!LocalKeysSent()); + PW_DCHECK(!LocalKeysSent()); if (ShouldSendLtk() && !SendEncryptionKey()) { return false; @@ -269,7 +268,7 @@ bool Phase3::SendLocalKeys() { } bool Phase3::SendEncryptionKey() { - BT_ASSERT(!features_.secure_connections); + PW_CHECK(!features_.secure_connections); // Only allowed on the LE transport. if (sm_chan().link_type() != bt::LinkType::kLE) { @@ -337,7 +336,7 @@ bool Phase3::SendIdentityInfo() { } void Phase3::SignalComplete() { - BT_ASSERT(KeyExchangeComplete()); + PW_CHECK(KeyExchangeComplete()); // The security properties of all keys are determined by the security // properties of the link used to distribute them. This is already reflected @@ -348,7 +347,7 @@ void Phase3::SignalComplete() { if (irk_.has_value()) { // If there is an IRK there must also be an identity address. - BT_ASSERT(identity_address_.has_value()); + PW_CHECK(identity_address_.has_value()); pairing_data.irk = Key(le_sec_, *irk_); pairing_data.identity_address = identity_address_; } diff --git a/pw_bluetooth_sapphire/host/sm/phase_3_test.cc b/pw_bluetooth_sapphire/host/sm/phase_3_test.cc index 22e09c9696..da1a4ffcd2 100644 --- a/pw_bluetooth_sapphire/host/sm/phase_3_test.cc +++ b/pw_bluetooth_sapphire/host/sm/phase_3_test.cc @@ -141,10 +141,10 @@ class Phase3Test : public l2cap::testing::FakeChannelTest { } static std::pair ExtractCodeAnd128BitCmd(ByteBufferPtr sdu) { - BT_ASSERT_MSG(sdu, "Tried to ExtractCodeAnd128BitCmd from nullptr in test"); + PW_CHECK(sdu, "Tried to ExtractCodeAnd128BitCmd from nullptr in test"); auto maybe_reader = ValidPacketReader::ParseSdu(sdu); - BT_ASSERT_MSG(maybe_reader.is_ok(), - "Tried to ExtractCodeAnd128BitCmd from invalid SMP packet"); + PW_CHECK(maybe_reader.is_ok(), + "Tried to ExtractCodeAnd128BitCmd from invalid SMP packet"); return {maybe_reader.value().code(), maybe_reader.value().payload()}; } diff --git a/pw_bluetooth_sapphire/host/sm/sc_stage_1_just_works_numeric_comparison.cc b/pw_bluetooth_sapphire/host/sm/sc_stage_1_just_works_numeric_comparison.cc index 0099d41174..57b7b60665 100644 --- a/pw_bluetooth_sapphire/host/sm/sc_stage_1_just_works_numeric_comparison.cc +++ b/pw_bluetooth_sapphire/host/sm/sc_stage_1_just_works_numeric_comparison.cc @@ -42,8 +42,8 @@ ScStage1JustWorksNumericComparison::ScStage1JustWorksNumericComparison( sm_chan_(std::move(sm_chan)), on_complete_(std::move(on_complete)), weak_self_(this) { - BT_ASSERT(method == PairingMethod::kJustWorks || - method == PairingMethod::kNumericComparison); + PW_CHECK(method == PairingMethod::kJustWorks || + method == PairingMethod::kNumericComparison); } void ScStage1JustWorksNumericComparison::Run() { @@ -93,10 +93,10 @@ void ScStage1JustWorksNumericComparison::OnPairingConfirm( void ScStage1JustWorksNumericComparison::SendPairingRandom() { // The random value is always sent after the confirm exchange (Vol 3, Part // H, 2.3.5.6.2). - BT_ASSERT(responder_confirm_.has_value()); - BT_ASSERT(!sent_local_rand_); + PW_CHECK(responder_confirm_.has_value()); + PW_CHECK(!sent_local_rand_); if (role_ == Role::kResponder) { - BT_ASSERT(peer_rand_.has_value()); + PW_CHECK(peer_rand_.has_value()); } sm_chan_->SendMessage(kPairingRandom, local_rand_); sent_local_rand_ = true; @@ -148,9 +148,9 @@ void ScStage1JustWorksNumericComparison::OnPairingRandom( } void ScStage1JustWorksNumericComparison::CompleteStage1() { - BT_ASSERT(responder_confirm_.has_value()); - BT_ASSERT(peer_rand_.has_value()); - BT_ASSERT(sent_local_rand_); + PW_CHECK(responder_confirm_.has_value()); + PW_CHECK(peer_rand_.has_value()); + PW_CHECK(sent_local_rand_); const auto& [initiator_rand, responder_rand] = util::MapToRoles(local_rand_, *peer_rand_, role_); const auto& [initiator_pub_key_x, responder_pub_key_x] = diff --git a/pw_bluetooth_sapphire/host/sm/sc_stage_1_passkey.cc b/pw_bluetooth_sapphire/host/sm/sc_stage_1_passkey.cc index fff6a99dba..c37635482b 100644 --- a/pw_bluetooth_sapphire/host/sm/sc_stage_1_passkey.cc +++ b/pw_bluetooth_sapphire/host/sm/sc_stage_1_passkey.cc @@ -60,8 +60,8 @@ ScStage1Passkey::ScStage1Passkey(PairingPhase::Listener::WeakPtr listener, sm_chan_(std::move(sm_chan)), on_complete_(std::move(on_complete)), weak_self_(this) { - BT_ASSERT(method == PairingMethod::kPasskeyEntryDisplay || - method == PairingMethod::kPasskeyEntryInput); + PW_CHECK(method == PairingMethod::kPasskeyEntryDisplay || + method == PairingMethod::kPasskeyEntryInput); } void ScStage1Passkey::Run() { @@ -116,10 +116,10 @@ void ScStage1Passkey::Run() { } void ScStage1Passkey::StartBitExchange() { - BT_ASSERT(passkey_.has_value()); + PW_CHECK(passkey_.has_value()); // The passkey is 6 digits i.e. representable in 2^20 bits. Attempting to // exchange > 20 bits indicates a programmer error. - BT_ASSERT(passkey_bit_location_ <= kMaxPasskeyBitLocation); + PW_CHECK(passkey_bit_location_ <= kMaxPasskeyBitLocation); local_rand_ = Random(); sent_local_confirm_ = sent_local_rand_ = false; @@ -128,18 +128,18 @@ void ScStage1Passkey::StartBitExchange() { // where we should have received a peer confirm before StartBitExchange is // if, as responder in the first bit exchange, we receive the peer // initiator's confirm while waiting for local user input. - BT_ASSERT((role_ == Role::kInitiator && !peer_confirm_.has_value()) || - passkey_bit_location_ == 0); + PW_CHECK((role_ == Role::kInitiator && !peer_confirm_.has_value()) || + passkey_bit_location_ == 0); SendPairingConfirm(); } // As responder, we wait for the peer confirm before taking any action. } void ScStage1Passkey::SendPairingConfirm() { - BT_ASSERT(!sent_local_confirm_); - BT_ASSERT(passkey_.has_value()); + PW_CHECK(!sent_local_confirm_); + PW_CHECK(passkey_.has_value()); if (role_ == Role::kResponder) { - BT_ASSERT(peer_confirm_.has_value()); + PW_CHECK(peer_confirm_.has_value()); } uint8_t current_passkey_bit = GetPasskeyBit(*passkey_, passkey_bit_location_); @@ -188,10 +188,10 @@ void ScStage1Passkey::OnPairingConfirm(PairingConfirmValue confirm) { } void ScStage1Passkey::SendPairingRandom() { - BT_ASSERT(sent_local_confirm_ && peer_confirm_.has_value()); - BT_ASSERT(!sent_local_rand_); + PW_CHECK(sent_local_confirm_ && peer_confirm_.has_value()); + PW_CHECK(!sent_local_rand_); if (role_ == Role::kResponder) { - BT_ASSERT(peer_rand_.has_value()); + PW_CHECK(peer_rand_.has_value()); } sm_chan_->SendMessage(kPairingRandom, local_rand_); sent_local_rand_ = true; @@ -240,10 +240,10 @@ void ScStage1Passkey::OnPairingRandom(PairingRandomValue rand) { } void ScStage1Passkey::FinishBitExchange() { - BT_ASSERT(sent_local_confirm_); - BT_ASSERT(peer_confirm_.has_value()); - BT_ASSERT(sent_local_rand_); - BT_ASSERT(peer_rand_.has_value()); + PW_CHECK(sent_local_confirm_); + PW_CHECK(peer_confirm_.has_value()); + PW_CHECK(sent_local_rand_); + PW_CHECK(peer_rand_.has_value()); passkey_bit_location_++; if (passkey_bit_location_ <= kMaxPasskeyBitLocation) { peer_confirm_ = std::nullopt; diff --git a/pw_bluetooth_sapphire/host/sm/security_manager.cc b/pw_bluetooth_sapphire/host/sm/security_manager.cc index ed834a3290..32247de7d7 100644 --- a/pw_bluetooth_sapphire/host/sm/security_manager.cc +++ b/pw_bluetooth_sapphire/host/sm/security_manager.cc @@ -279,11 +279,11 @@ SecurityManagerImpl::SecurityManagerImpl(hci::LowEnergyConnection::WeakPtr link, weak_self_(this), weak_listener_(this), weak_handler_(this) { - BT_ASSERT(delegate_.is_alive()); - BT_ASSERT(le_link_.is_alive()); - BT_ASSERT(smp.is_alive()); - BT_ASSERT(le_link_->handle() == smp->link_handle()); - BT_ASSERT(smp->id() == l2cap::kLESMPChannelId); + PW_CHECK(delegate_.is_alive()); + PW_CHECK(le_link_.is_alive()); + PW_CHECK(smp.is_alive()); + PW_CHECK(le_link_->handle() == smp->link_handle()); + PW_CHECK(smp->id() == l2cap::kLESMPChannelId); // `current_phase_` is default constructed into std::monostate in the // initializer list as no security upgrade is in progress upon construction. @@ -301,7 +301,7 @@ SecurityManagerImpl::SecurityManagerImpl(hci::LowEnergyConnection::WeakPtr link, } void SecurityManagerImpl::OnSecurityRequest(AuthReqField auth_req) { - BT_ASSERT(!SecurityUpgradeInProgress()); + PW_CHECK(!SecurityUpgradeInProgress()); if (role_ != Role::kInitiator) { bt_log( @@ -377,7 +377,7 @@ void SecurityManagerImpl::UpgradeSecurity(SecurityLevel level, // |request_queue| must be empty if there is no active security upgrade // request, which is equivalent to being in idle phase with no pending // security request. - BT_ASSERT(request_queue_.empty()); + PW_CHECK(request_queue_.empty()); request_queue_.emplace(level, std::move(callback)); UpgradeSecurityInternal(); } @@ -422,7 +422,7 @@ void SecurityManagerImpl::OnPairingRequest( } void SecurityManagerImpl::UpgradeSecurityInternal() { - BT_ASSERT_MSG( + PW_CHECK( !SecurityUpgradeInProgress(), "cannot upgrade security while security upgrade already in progress!"); const PendingRequest& next_req = request_queue_.front(); @@ -471,7 +471,7 @@ fit::result SecurityManagerImpl::RequestSecurityUpgrade( void SecurityManagerImpl::OnFeatureExchange(PairingFeatures features, PairingRequestParams preq, PairingResponseParams pres) { - BT_ASSERT(std::holds_alternative>(current_phase_)); + PW_CHECK(std::holds_alternative>(current_phase_)); bt_log(TRACE, "sm", "obtained LE Pairing features"); next_pairing_id_++; features_ = features; @@ -512,9 +512,9 @@ void SecurityManagerImpl::OnFeatureExchange(PairingFeatures features, } void SecurityManagerImpl::OnPhase2EncryptionKey(const UInt128& new_key) { - BT_ASSERT(le_link_.is_alive()); - BT_ASSERT(features_); - BT_ASSERT(InPhase2()); + PW_CHECK(le_link_.is_alive()); + PW_CHECK(features_); + PW_CHECK(InPhase2()); // EDiv and Rand values are 0 for Phase 2 keys generated by Legacy or Secure // Connections (Vol 3, Part H, 2.4.4 / 2.4.4.1). Secure Connections generates // an LTK, while Legacy generates an STK. @@ -557,7 +557,7 @@ void SecurityManagerImpl::OnEncryptionChange(hci::Result enabled_result) { // First notify the delegate in case of failure. if (bt_is_error( enabled_result, ERROR, "sm", "link layer authentication failed")) { - BT_ASSERT(delegate_.is_alive()); + PW_CHECK(delegate_.is_alive()); delegate_->OnAuthenticationFailure( fit::error(enabled_result.error_value())); } @@ -607,8 +607,8 @@ void SecurityManagerImpl::OnEncryptionChange(hci::Result enabled_result) { // function determine the security properties. SetSecurityProperties(ltk_->security()); if (security_request_phase) { - BT_ASSERT(role_ == Role::kResponder); - BT_ASSERT(!request_queue_.empty()); + PW_CHECK(role_ == Role::kResponder); + PW_CHECK(!request_queue_.empty()); NotifySecurityCallbacks(); } return; @@ -621,8 +621,8 @@ void SecurityManagerImpl::OnEncryptionChange(hci::Result enabled_result) { } void SecurityManagerImpl::EndPhase2() { - BT_ASSERT(features_.has_value()); - BT_ASSERT(InPhase2()); + PW_CHECK(features_.has_value()); + PW_CHECK(InPhase2()); SetSecurityProperties(FeaturesToProperties(*features_)); // If there are no keys to distribute, don't bother creating Phase 3 @@ -645,17 +645,17 @@ void SecurityManagerImpl::OnPairingComplete(PairingData pairing_data) { // We must either be in Phase3 or Phase 2 with no keys to distribute if // pairing has completed. if (!std::holds_alternative(current_phase_)) { - BT_ASSERT(InPhase2()); - BT_ASSERT(!HasKeysToDistribute(*features_)); + PW_CHECK(InPhase2()); + PW_CHECK(!HasKeysToDistribute(*features_)); } - BT_ASSERT(delegate_.is_alive()); - BT_ASSERT(features_.has_value()); + PW_CHECK(delegate_.is_alive()); + PW_CHECK(features_.has_value()); bt_log(DEBUG, "sm", "LE pairing complete"); delegate_->OnPairingComplete(fit::ok()); // In Secure Connections, the LTK will be generated in Phase 2, not exchanged // in Phase 3, so we want to ensure that it is still put in the pairing_data. if (features_->secure_connections) { - BT_ASSERT(ltk_.has_value()); + PW_CHECK(ltk_.has_value()); pairing_data.peer_ltk = pairing_data.local_ltk = ltk_; } else { // The SM-internal LTK is used to validate future encryption events on the @@ -673,8 +673,8 @@ void SecurityManagerImpl::OnPairingComplete(PairingData pairing_data) { if (features_->generate_ct_key.has_value()) { // If we are generating the CT key, we must be using secure connections, and // as such the peer and local LTKs will be equivalent. - BT_ASSERT(features_->secure_connections); - BT_ASSERT(pairing_data.peer_ltk == pairing_data.local_ltk); + PW_CHECK(features_->secure_connections); + PW_CHECK(pairing_data.peer_ltk == pairing_data.local_ltk); std::optional ct_key_value = util::LeLtkToBrEdrLinkKey( ltk_->key().value(), features_->generate_ct_key.value()); if (ct_key_value) { @@ -801,12 +801,12 @@ void SecurityManagerImpl::Abort(ErrorCode ecode) { std::optional SecurityManagerImpl::OnIdentityRequest() { // This is called by the bearer to determine if we have local identity // information to distribute. - BT_ASSERT(delegate_.is_alive()); + PW_CHECK(delegate_.is_alive()); return delegate_->OnIdentityInformationRequest(); } void SecurityManagerImpl::ConfirmPairing(ConfirmCallback confirm) { - BT_ASSERT(delegate_.is_alive()); + PW_CHECK(delegate_.is_alive()); delegate_->ConfirmPairing([id = next_pairing_id_, self = weak_self_.GetWeakPtr(), cb = std::move(confirm)](bool is_confirmed) { @@ -824,7 +824,7 @@ void SecurityManagerImpl::ConfirmPairing(ConfirmCallback confirm) { void SecurityManagerImpl::DisplayPasskey(uint32_t passkey, Delegate::DisplayMethod method, ConfirmCallback confirm) { - BT_ASSERT(delegate_.is_alive()); + PW_CHECK(delegate_.is_alive()); delegate_->DisplayPasskey( passkey, method, @@ -845,7 +845,7 @@ void SecurityManagerImpl::DisplayPasskey(uint32_t passkey, } void SecurityManagerImpl::RequestPasskey(PasskeyResponseCallback respond) { - BT_ASSERT(delegate_.is_alive()); + PW_CHECK(delegate_.is_alive()); delegate_->RequestPasskey([id = next_pairing_id_, self = weak_self_.GetWeakPtr(), cb = std::move(respond)](int64_t passkey) { @@ -915,7 +915,7 @@ void SecurityManagerImpl::OnPairingFailed(Error error) { // TODO(fxbug.dev/42172514): implement "waiting interval" to prevent repeated // attempts as described in Vol 3, Part H, 2.3.6. - BT_ASSERT(delegate_.is_alive()); + PW_CHECK(delegate_.is_alive()); delegate_->OnPairingComplete(fit::error(error)); auto requests = std::move(request_queue_); @@ -925,7 +925,7 @@ void SecurityManagerImpl::OnPairingFailed(Error error) { } if (SecurityUpgradeInProgress()) { - BT_ASSERT(le_link_.is_alive()); + PW_CHECK(le_link_.is_alive()); le_link_->set_ltk(hci_spec::LinkKey()); } ResetState(); @@ -943,7 +943,7 @@ void SecurityManagerImpl::OnPairingFailed(Error error) { void SecurityManagerImpl::StartNewTimer() { if (timeout_task_.is_pending()) { - BT_ASSERT(timeout_task_.Cancel()); + PW_CHECK(timeout_task_.Cancel()); } timeout_task_.PostAfter(kPairingTimeout); } @@ -971,7 +971,7 @@ void SecurityManagerImpl::OnPairingTimeout() { std::pair SecurityManagerImpl::LEPairingAddresses() { - BT_ASSERT(SecurityUpgradeInProgress()); + PW_CHECK(SecurityUpgradeInProgress()); const DeviceAddress *initiator = &le_link_->local_address(), *responder = &le_link_->peer_address(); if (role_ == Role::kResponder) { diff --git a/pw_bluetooth_sapphire/host/sm/security_manager_test.cc b/pw_bluetooth_sapphire/host/sm/security_manager_test.cc index 2fb29e4678..f2a7303dc1 100644 --- a/pw_bluetooth_sapphire/host/sm/security_manager_test.cc +++ b/pw_bluetooth_sapphire/host/sm/security_manager_test.cc @@ -191,7 +191,7 @@ class SecurityManagerTest : public l2cap::testing::FakeChannelTest, } void UpgradeSecurity(SecurityLevel level) { - BT_DEBUG_ASSERT(pairing_); + PW_DCHECK(pairing_); pairing_->UpgradeSecurity(level, [this](auto status, const auto& props) { security_callback_count_++; security_status_ = status; @@ -201,7 +201,7 @@ class SecurityManagerTest : public l2cap::testing::FakeChannelTest, // Called when SMP sends a packet over the fake channel. void OnDataReceived(std::unique_ptr packet) { - BT_DEBUG_ASSERT(packet); + PW_DCHECK(packet); PacketReader reader(packet.get()); switch (reader.code()) { @@ -373,7 +373,7 @@ class SecurityManagerTest : public l2cap::testing::FakeChannelTest, UInt128* out_value, bool peer_initiator = false, uint32_t tk = 0) { - BT_DEBUG_ASSERT(out_value); + PW_DCHECK(out_value); tk = pw::bytes::ConvertOrderTo(cpp20::endian::little, tk); UInt128 tk128; @@ -402,8 +402,8 @@ class SecurityManagerTest : public l2cap::testing::FakeChannelTest, Role local_role, bool gen_initiator_confirm, uint8_t r = 0) { - BT_ASSERT_MSG(public_ecdh_key_.has_value(), - "cannot compute confirm, missing key!"); + PW_CHECK(public_ecdh_key_.has_value(), + "cannot compute confirm, missing key!"); UInt256 pka = public_ecdh_key_->GetPublicKeyX(), pkb = peer_key.GetPublicKeyX(); if (local_role == Role::kResponder) { @@ -633,8 +633,8 @@ class InitiatorPairingTest : public SecurityManagerTest { void GenerateMatchingLegacyConfirmAndRandom(UInt128* out_confirm, UInt128* out_random, uint32_t tk = 0) { - BT_DEBUG_ASSERT(out_confirm); - BT_DEBUG_ASSERT(out_random); + PW_DCHECK(out_confirm); + PW_DCHECK(out_random); *out_random = kHardCodedPairingRandom; GenerateLegacyConfirmValue( *out_random, out_confirm, /*peer_initiator=*/false, tk); @@ -698,7 +698,7 @@ class InitiatorPairingTest : public SecurityManagerTest { EXPECT_EQ(0, pairing_failed_count()); EXPECT_EQ(0, security_callback_count()); - BT_DEBUG_ASSERT(out_stk); + PW_DCHECK(out_stk); UInt128 tk; tk.fill(0); @@ -857,8 +857,8 @@ class ResponderPairingTest : public SecurityManagerTest { void GenerateMatchingLegacyConfirmAndRandom(UInt128* out_confirm, UInt128* out_random, uint32_t tk = 0) { - BT_DEBUG_ASSERT(out_confirm); - BT_DEBUG_ASSERT(out_random); + PW_DCHECK(out_confirm); + PW_DCHECK(out_random); *out_random = kHardCodedPairingRandom; GenerateLegacyConfirmValue( *out_random, out_confirm, /*peer_initiator=*/true, tk); @@ -930,7 +930,7 @@ class ResponderPairingTest : public SecurityManagerTest { EXPECT_EQ(0, pairing_failed_count()); EXPECT_EQ(0, security_callback_count()); - BT_DEBUG_ASSERT(out_stk); + PW_DCHECK(out_stk); UInt128 tk; tk.fill(0); diff --git a/pw_bluetooth_sapphire/host/sm/security_request_phase.cc b/pw_bluetooth_sapphire/host/sm/security_request_phase.cc index 45907ef439..b68df799ac 100644 --- a/pw_bluetooth_sapphire/host/sm/security_request_phase.cc +++ b/pw_bluetooth_sapphire/host/sm/security_request_phase.cc @@ -44,7 +44,7 @@ void SecurityRequestPhase::Start() { void SecurityRequestPhase::MakeSecurityRequest(SecurityLevel desired_level, BondableMode bondable_mode) { - BT_ASSERT(desired_level >= SecurityLevel::kEncrypted); + PW_CHECK(desired_level >= SecurityLevel::kEncrypted); AuthReqField security_req_payload = 0u; if (desired_level >= SecurityLevel::kAuthenticated) { // inclusive-language: ignore diff --git a/pw_bluetooth_sapphire/host/sm/test_security_manager.cc b/pw_bluetooth_sapphire/host/sm/test_security_manager.cc index 8a54344bb2..8287a2e37c 100644 --- a/pw_bluetooth_sapphire/host/sm/test_security_manager.cc +++ b/pw_bluetooth_sapphire/host/sm/test_security_manager.cc @@ -76,7 +76,7 @@ std::unique_ptr TestSecurityManagerFactory::CreateSm( WeakSelf::WeakPtr TestSecurityManagerFactory::GetTestSm( hci_spec::ConnectionHandle conn_handle) { auto iter = test_sms_.find(conn_handle); - BT_ASSERT(iter != test_sms_.end()); + PW_CHECK(iter != test_sms_.end()); return iter->second; } diff --git a/pw_bluetooth_sapphire/host/sm/types.cc b/pw_bluetooth_sapphire/host/sm/types.cc index f34c917052..07154151a2 100644 --- a/pw_bluetooth_sapphire/host/sm/types.cc +++ b/pw_bluetooth_sapphire/host/sm/types.cc @@ -104,9 +104,8 @@ SecurityProperties::SecurityProperties(hci_spec::LinkKeyType lk_type) IsAuthenticatedKey(lk_type), IsSecureConnectionsKey(lk_type), kMaxEncryptionKeySize) { - BT_DEBUG_ASSERT_MSG( - lk_type != hci_spec::LinkKeyType::kChangedCombination, - "Can't infer security information from a Changed Combination Key"); + PW_DCHECK(lk_type != hci_spec::LinkKeyType::kChangedCombination, + "Can't infer security information from a Changed Combination Key"); } SecurityProperties::SecurityProperties(const SecurityProperties& other) { diff --git a/pw_bluetooth_sapphire/host/sm/util.cc b/pw_bluetooth_sapphire/host/sm/util.cc index e469c3ed50..1745c06f1b 100644 --- a/pw_bluetooth_sapphire/host/sm/util.cc +++ b/pw_bluetooth_sapphire/host/sm/util.cc @@ -59,7 +59,7 @@ const auto kF5KeyId = std::array{0x65, 0x6C, 0x74, 0x62}; // Swap the endianness of a 128-bit integer. |in| and |out| should not be backed // by the same buffer. void Swap128(const UInt128& in, UInt128* out) { - BT_DEBUG_ASSERT(out); + PW_DCHECK(out); for (size_t i = 0; i < in.size(); ++i) { (*out)[i] = in[in.size() - i - 1]; } @@ -68,7 +68,7 @@ void Swap128(const UInt128& in, UInt128* out) { // XOR two 128-bit integers and return the result in |out|. It is possible to // pass a pointer to one of the inputs as |out|. void Xor128(const UInt128& int1, const UInt128& int2, UInt128* out) { - BT_DEBUG_ASSERT(out); + PW_DCHECK(out); for (size_t i = 0; i < kUInt128Size; ++i) { out->at(i) = int1.at(i) ^ int2.at(i); @@ -296,9 +296,9 @@ void C1(const UInt128& tk, const DeviceAddress& initiator_addr, const DeviceAddress& responder_addr, UInt128* out_confirm_value) { - BT_DEBUG_ASSERT(preq.size() == kPreqSize); - BT_DEBUG_ASSERT(pres.size() == kPreqSize); - BT_DEBUG_ASSERT(out_confirm_value); + PW_DCHECK(preq.size() == kPreqSize); + PW_DCHECK(pres.size() == kPreqSize); + PW_DCHECK(out_confirm_value); UInt128 p1, p2; @@ -333,7 +333,7 @@ void S1(const UInt128& tk, const UInt128& r1, const UInt128& r2, UInt128* out_stk) { - BT_DEBUG_ASSERT(out_stk); + PW_DCHECK(out_stk); UInt128 r_prime; @@ -348,7 +348,7 @@ void S1(const UInt128& tk, } uint32_t Ah(const UInt128& k, uint32_t r) { - BT_DEBUG_ASSERT(r <= k24BitMax); + PW_DCHECK(r <= k24BitMax); // r' = padding || r. UInt128 r_prime; @@ -479,7 +479,7 @@ std::optional F4(const UInt256& u, current_view = WriteToBuffer(u, current_view); // Ensures |current_view| is at the end of data_to_encrypt - BT_DEBUG_ASSERT(current_view.size() == 0); + PW_DCHECK(current_view.size() == 0); return AesCmac(x, data_to_encrypt); } @@ -517,7 +517,7 @@ std::optional F5(const UInt256& dhkey, current_view = WriteToBuffer(counter, current_view); // Ensures |current_view| is at the end of data_to_encrypt - BT_DEBUG_ASSERT(current_view.size() == 0); + PW_DCHECK(current_view.size() == 0); maybe_cmac = AesCmac(t_key, data_to_encrypt); if (!maybe_cmac.has_value()) { return std::nullopt; @@ -560,7 +560,7 @@ std::optional F6(const UInt128& mackey, current_view = WriteToBuffer(n2, current_view); current_view = WriteToBuffer(n1, current_view); // Ensures |current_view| is at the end of data_to_encrypt - BT_DEBUG_ASSERT(current_view.size() == 0); + PW_DCHECK(current_view.size() == 0); return AesCmac(mackey, data_to_encrypt); } @@ -576,7 +576,7 @@ std::optional G2(const UInt256& initiator_pubkey_x, WriteToBuffer(responder_nonce, data_to_encrypt.mutable_view()); current_view = WriteToBuffer(responder_pubkey_x, current_view); current_view = WriteToBuffer(initiator_pubkey_x, current_view); - BT_DEBUG_ASSERT(current_view.size() == 0); + PW_DCHECK(current_view.size() == 0); std::optional maybe_cmac = AesCmac(initiator_nonce, data_to_encrypt); if (!maybe_cmac.has_value()) { return std::nullopt; diff --git a/pw_bluetooth_sapphire/host/testing/fake_controller.cc b/pw_bluetooth_sapphire/host/testing/fake_controller.cc index c388113363..959aa75824 100644 --- a/pw_bluetooth_sapphire/host/testing/fake_controller.cc +++ b/pw_bluetooth_sapphire/host/testing/fake_controller.cc @@ -205,7 +205,7 @@ void FakeController::ClearDefaultCommandStatus(hci_spec::OpCode opcode) { void FakeController::SetDefaultResponseStatus(hci_spec::OpCode opcode, pwemb::StatusCode status) { - BT_DEBUG_ASSERT(status != pwemb::StatusCode::SUCCESS); + PW_DCHECK(status != pwemb::StatusCode::SUCCESS); default_status_map_[opcode] = status; } @@ -214,7 +214,7 @@ void FakeController::ClearDefaultResponseStatus(hci_spec::OpCode opcode) { } bool FakeController::AddPeer(std::unique_ptr peer) { - BT_DEBUG_ASSERT(peer); + PW_DCHECK(peer); if (peers_.count(peer->address()) != 0u) { return false; @@ -243,7 +243,7 @@ FakePeer* FakeController::FindPeer(const DeviceAddress& address) { } void FakeController::SendCommand(pw::span command) { - BT_ASSERT(command.size() >= sizeof(hci_spec::CommandHeader)); + PW_CHECK(command.size() >= sizeof(hci_spec::CommandHeader)); // Post the packet to simulate async HCI behavior. (void)heap_dispatcher().Post( @@ -361,7 +361,7 @@ void FakeController::SendLEMetaEvent(hci_spec::EventCode subevent_code, void FakeController::SendACLPacket(hci_spec::ConnectionHandle handle, const ByteBuffer& payload) { - BT_DEBUG_ASSERT(payload.size() <= hci_spec::kMaxACLPayloadSize); + PW_DCHECK(payload.size() <= hci_spec::kMaxACLPayloadSize); DynamicByteBuffer buffer(sizeof(hci_spec::ACLDataHeader) + payload.size()); MutablePacketView acl(&buffer, payload.size()); @@ -378,8 +378,8 @@ void FakeController::SendACLPacket(hci_spec::ConnectionHandle handle, void FakeController::SendL2CAPBFrame(hci_spec::ConnectionHandle handle, l2cap::ChannelId channel_id, const ByteBuffer& payload) { - BT_DEBUG_ASSERT(payload.size() <= - hci_spec::kMaxACLPayloadSize - sizeof(l2cap::BasicHeader)); + PW_DCHECK(payload.size() <= + hci_spec::kMaxACLPayloadSize - sizeof(l2cap::BasicHeader)); DynamicByteBuffer buffer(sizeof(l2cap::BasicHeader) + payload.size()); MutablePacketView bframe(&buffer, payload.size()); @@ -487,7 +487,7 @@ void FakeController::ConnectLowEnergy(const DeviceAddress& addr, void FakeController::SendConnectionRequest(const DeviceAddress& addr, pwemb::LinkType link_type) { FakePeer* peer = FindPeer(addr); - BT_ASSERT(peer); + PW_CHECK(peer); peer->set_last_connection_request_link_type(link_type); bt_log(DEBUG, @@ -525,7 +525,7 @@ void FakeController::L2CAPConnectionParameterUpdate( return; } - BT_DEBUG_ASSERT(!peer->logical_links().empty()); + PW_DCHECK(!peer->logical_links().empty()); l2cap::ConnectionParameterUpdateRequestPayload payload; payload.interval_min = @@ -582,8 +582,8 @@ void FakeController::Disconnect(const DeviceAddress& addr, } auto links = peer->Disconnect(); - BT_DEBUG_ASSERT(!peer->connected()); - BT_DEBUG_ASSERT(!links.empty()); + PW_DCHECK(!peer->connected()); + PW_DCHECK(!links.empty()); for (auto link : links) { NotifyConnectionState(addr, link, /*connected=*/false); @@ -980,7 +980,7 @@ void FakeController::OnLECreateConnectionCommandReceived( std::optional addr_type = DeviceAddress::LeAddrToDeviceAddr(params.peer_address_type().Read()); - BT_DEBUG_ASSERT(addr_type && *addr_type != DeviceAddress::Type::kBREDR); + PW_DCHECK(addr_type && *addr_type != DeviceAddress::Type::kBREDR); const DeviceAddress peer_address(*addr_type, DeviceAddressBytes(params.peer_address())); @@ -1279,7 +1279,7 @@ void FakeController::OnLEConnectionUpdateCommandReceived( return; } - BT_DEBUG_ASSERT(peer->connected()); + PW_DCHECK(peer->connected()); uint16_t min_interval = params.connection_interval_min().UncheckedRead(); uint16_t max_interval = params.connection_interval_max().UncheckedRead(); @@ -1333,7 +1333,7 @@ void FakeController::OnDisconnectCommandReceived( return; } - BT_DEBUG_ASSERT(peer->connected()); + PW_DCHECK(peer->connected()); RespondWithCommandStatus(hci_spec::kDisconnect, pwemb::StatusCode::SUCCESS); @@ -1719,7 +1719,7 @@ void FakeController::OnLECreateConnectionCancel() { le_connect_pending_ = false; le_connect_rsp_task_.Cancel(); - BT_DEBUG_ASSERT(le_connect_params_); + PW_DCHECK(le_connect_params_); NotifyConnectionState(le_connect_params_->peer_address, 0, @@ -2357,7 +2357,7 @@ void FakeController::OnLinkKeyRequestReplyCommandReceived( RespondWithCommandComplete(hci_spec::kLinkKeyRequestReply, pwemb::StatusCode::SUCCESS); - BT_ASSERT(!peer->logical_links().empty()); + PW_CHECK(!peer->logical_links().empty()); for (auto& conn_handle : peer->logical_links()) { auto event = hci::EmbossEventPacket::New( @@ -2461,7 +2461,7 @@ void FakeController::OnUserConfirmationRequestReplyCommand( pwemb::KeyType::UNAUTHENTICATED_COMBINATION_FROM_P192); SendCommandChannelPacket(link_key_event.data()); - BT_ASSERT(!peer->logical_links().empty()); + PW_CHECK(!peer->logical_links().empty()); for (auto& conn_handle : peer->logical_links()) { auto event = hci::EmbossEventPacket::New( @@ -3266,7 +3266,7 @@ void FakeController::OnLESetExtendedAdvertisingEnable( // rest of the function deals with enabling advertising for a given set of // advertising sets - BT_ASSERT(params.enable().Read() == pwemb::GenericEnableParam::ENABLE); + PW_CHECK(params.enable().Read() == pwemb::GenericEnableParam::ENABLE); if (num_sets == 0) { bt_log( @@ -3281,8 +3281,8 @@ void FakeController::OnLESetExtendedAdvertisingEnable( // FakeController currently doesn't support testing with duration and max // events. When those are used in the host, these checks will fail and // remind us to add the necessary code to FakeController. - BT_ASSERT(params.data()[i].duration().Read() == 0); - BT_ASSERT(params.data()[i].max_extended_advertising_events().Read() == 0); + PW_CHECK(params.data()[i].duration().Read() == 0); + PW_CHECK(params.data()[i].max_extended_advertising_events().Read() == 0); hci_spec::AdvertisingHandle handle = params.data()[i].advertising_handle().Read(); @@ -4069,7 +4069,7 @@ void FakeController::OnVendorCommand( void FakeController::OnACLDataPacketReceived( const ByteBuffer& acl_data_packet) { if (acl_data_callback_) { - BT_DEBUG_ASSERT(data_dispatcher_); + PW_DCHECK(data_dispatcher_); DynamicByteBuffer packet_copy(acl_data_packet); (void)data_dispatcher_->Post( [packet_copy = std::move(packet_copy), cb = acl_data_callback_.share()]( @@ -4153,9 +4153,9 @@ void FakeController::OnIsoDataPacketReceived( void FakeController::SetDataCallback(DataCallback callback, pw::async::Dispatcher& pw_dispatcher) { - BT_DEBUG_ASSERT(callback); - BT_DEBUG_ASSERT(!acl_data_callback_); - BT_DEBUG_ASSERT(!data_dispatcher_); + PW_DCHECK(callback); + PW_DCHECK(!acl_data_callback_); + PW_DCHECK(!data_dispatcher_); acl_data_callback_ = std::move(callback); data_dispatcher_.emplace(pw_dispatcher); diff --git a/pw_bluetooth_sapphire/host/testing/fake_gatt_server.cc b/pw_bluetooth_sapphire/host/testing/fake_gatt_server.cc index 7156cba753..70d3450833 100644 --- a/pw_bluetooth_sapphire/host/testing/fake_gatt_server.cc +++ b/pw_bluetooth_sapphire/host/testing/fake_gatt_server.cc @@ -28,7 +28,7 @@ namespace bt::testing { FakeGattServer::FakeGattServer(FakePeer* dev) : dev_(dev) { - BT_ASSERT(dev_); + PW_CHECK(dev_); // Initialize services services_.insert({/*start_handle=*/1, @@ -122,8 +122,8 @@ void FakeGattServer::HandleReadByGrpType(hci_spec::ConnectionHandle conn, for (auto& [_, service] : services_) { // FakeGattServer only supports 16bit UUIDs currently. - BT_ASSERT(service.type.CompactSize(/*allow_32bit=*/false) == - UUIDElemSize::k16Bit); + PW_CHECK(service.type.CompactSize(/*allow_32bit=*/false) == + UUIDElemSize::k16Bit); att::AttributeGroupDataEntry* entry = next_entry.AsMutable(); entry->start_handle = diff --git a/pw_bluetooth_sapphire/host/testing/fake_l2cap.cc b/pw_bluetooth_sapphire/host/testing/fake_l2cap.cc index fe281bcfd1..8e6b62dbc4 100644 --- a/pw_bluetooth_sapphire/host/testing/fake_l2cap.cc +++ b/pw_bluetooth_sapphire/host/testing/fake_l2cap.cc @@ -31,7 +31,7 @@ FakeL2cap::FakeL2cap(SendFrameCallback send_frame_callback, void FakeL2cap::RegisterHandler(l2cap::ChannelId cid, ChannelReceiveCallback callback) { - BT_ASSERT(cid < l2cap::kFirstDynamicChannelId); + PW_CHECK(cid < l2cap::kFirstDynamicChannelId); if (callbacks_.find(cid) != callbacks_.end()) { bt_log(WARN, "fake-hci", @@ -53,7 +53,7 @@ bool FakeL2cap::RegisterDynamicChannel(hci_spec::ConnectionHandle conn, l2cap::Psm psm, l2cap::ChannelId local_cid, l2cap::ChannelId remote_cid) { - BT_ASSERT(local_cid >= l2cap::kFirstDynamicChannelId); + PW_CHECK(local_cid >= l2cap::kFirstDynamicChannelId); auto channel_map = dynamic_channels_.find(conn); if (channel_map != dynamic_channels_.end()) { if (channel_map->second.find(local_cid) == channel_map->second.end()) { @@ -84,7 +84,7 @@ bool FakeL2cap::RegisterDynamicChannelWithPsm(hci_spec::ConnectionHandle conn, l2cap::ChannelId local_cid) { auto channel = FindDynamicChannelByLocalId(conn, local_cid); if (channel.is_alive()) { - BT_ASSERT(channel->opened()); + PW_CHECK(channel->opened()); auto psm_iter = registered_services_.find(channel->psm()); if (psm_iter == registered_services_.end()) { bt_log(ERROR, diff --git a/pw_bluetooth_sapphire/host/testing/fake_peer.cc b/pw_bluetooth_sapphire/host/testing/fake_peer.cc index 84b705572b..dd3bfbb852 100644 --- a/pw_bluetooth_sapphire/host/testing/fake_peer.cc +++ b/pw_bluetooth_sapphire/host/testing/fake_peer.cc @@ -51,13 +51,13 @@ FakePeer::FakePeer(const DeviceAddress& address, } void FakePeer::set_scan_response(const ByteBuffer& data) { - BT_DEBUG_ASSERT(scannable_); + PW_DCHECK(scannable_); scan_response_ = DynamicByteBuffer(data); } DynamicByteBuffer FakePeer::CreateInquiryResponseEvent( pw::bluetooth::emboss::InquiryMode mode) const { - BT_DEBUG_ASSERT(address_.type() == DeviceAddress::Type::kBREDR); + PW_DCHECK(address_.type() == DeviceAddress::Type::kBREDR); if (mode == pw::bluetooth::emboss::InquiryMode::STANDARD) { size_t packet_size = @@ -98,7 +98,7 @@ DynamicByteBuffer FakePeer::CreateInquiryResponseEvent( } void FakePeer::AddLink(hci_spec::ConnectionHandle handle) { - BT_DEBUG_ASSERT(!HasLink(handle)); + PW_DCHECK(!HasLink(handle)); logical_links_.insert(handle); if (logical_links_.size() == 1u) { @@ -107,7 +107,7 @@ void FakePeer::AddLink(hci_spec::ConnectionHandle handle) { } void FakePeer::RemoveLink(hci_spec::ConnectionHandle handle) { - BT_DEBUG_ASSERT(HasLink(handle)); + PW_DCHECK(HasLink(handle)); logical_links_.erase(handle); if (logical_links_.empty()) set_connected(false); @@ -139,8 +139,8 @@ void FakePeer::SendPacket(hci_spec::ConnectionHandle conn, void FakePeer::WriteScanResponseReport( pw::bluetooth::emboss::LEAdvertisingReportDataWriter report) const { - BT_DEBUG_ASSERT(scannable_); - BT_DEBUG_ASSERT(scan_response_.size() < 0xFF); + PW_DCHECK(scannable_); + PW_DCHECK(scan_response_.size() < 0xFF); report.data_length().Write(static_cast(scan_response_.size())); report = pw::bluetooth::emboss::MakeLEAdvertisingReportDataView( report.BackingStorage().data(), @@ -164,8 +164,7 @@ void FakePeer::WriteScanResponseReport( DynamicByteBuffer FakePeer::BuildLegacyAdvertisingReportEvent( bool include_scan_rsp) const { - BT_DEBUG_ASSERT(advertising_data_.size() <= - hci_spec::kMaxLEAdvertisingDataLength); + PW_DCHECK(advertising_data_.size() <= hci_spec::kMaxLEAdvertisingDataLength); std::vector reports_sizes; reports_sizes.push_back( pw::bluetooth::emboss::LEAdvertisingReportData::MinSizeInBytes() + @@ -173,7 +172,7 @@ DynamicByteBuffer FakePeer::BuildLegacyAdvertisingReportEvent( size_t reports_size = reports_sizes[0]; if (include_scan_rsp) { - BT_DEBUG_ASSERT(scannable_); + PW_DCHECK(scannable_); reports_sizes.push_back( pw::bluetooth::emboss::LEAdvertisingReportData::MinSizeInBytes() + scan_response_.size()); @@ -191,7 +190,7 @@ DynamicByteBuffer FakePeer::BuildLegacyAdvertisingReportEvent( view.le_meta_event().subevent_code().Write( hci_spec::kLEAdvertisingReportSubeventCode); - BT_DEBUG_ASSERT(reports_sizes.size() < 0xFF); + PW_DCHECK(reports_sizes.size() < 0xFF); view.num_reports().Write(static_cast(reports_sizes.size())); // Initially construct an incomplete view to write the |data_length| field. @@ -242,9 +241,8 @@ DynamicByteBuffer FakePeer::BuildLegacyAdvertisingReportEvent( } DynamicByteBuffer FakePeer::BuildLegacyScanResponseReportEvent() const { - BT_DEBUG_ASSERT(scannable_); - BT_DEBUG_ASSERT(scan_response_.size() <= - hci_spec::kMaxLEAdvertisingDataLength); + PW_DCHECK(scannable_); + PW_DCHECK(scan_response_.size() <= hci_spec::kMaxLEAdvertisingDataLength); size_t report_size = pw::bluetooth::emboss::LEAdvertisingReportData::MinSizeInBytes() + scan_response_.size(); @@ -332,7 +330,7 @@ void FakePeer::FillExtendedAdvertisingReport( // skip direct_address_type and direct_address for now since we don't use it - BT_DEBUG_ASSERT(data.size() < 0xFF); + PW_DCHECK(data.size() < 0xFF); report.data_length().Write(static_cast(data.size())); std::memcpy(report.data().BackingStorage().begin(), data.data(), data.size()); } @@ -394,16 +392,16 @@ DynamicByteBuffer FakePeer::BuildExtendedAdvertisingReports( } DynamicByteBuffer FakePeer::BuildExtendedAdvertisingReportEvent() const { - BT_DEBUG_ASSERT(advertising_data_.size() <= - hci_spec::kMaxLEExtendedAdvertisingDataLength); + PW_DCHECK(advertising_data_.size() <= + hci_spec::kMaxLEExtendedAdvertisingDataLength); return BuildExtendedAdvertisingReports(advertising_data_, /*is_scan_response=*/false); } DynamicByteBuffer FakePeer::BuildExtendedScanResponseEvent() const { - BT_DEBUG_ASSERT(scannable_); - BT_DEBUG_ASSERT(scan_response_.size() <= - hci_spec::kMaxLEExtendedAdvertisingDataLength); + PW_DCHECK(scannable_); + PW_DCHECK(scan_response_.size() <= + hci_spec::kMaxLEExtendedAdvertisingDataLength); return BuildExtendedAdvertisingReports(scan_response_, /*is_scan_response=*/true); } diff --git a/pw_bluetooth_sapphire/host/testing/fake_sdp_server.cc b/pw_bluetooth_sapphire/host/testing/fake_sdp_server.cc index 0990040a23..c02cb7ed79 100644 --- a/pw_bluetooth_sapphire/host/testing/fake_sdp_server.cc +++ b/pw_bluetooth_sapphire/host/testing/fake_sdp_server.cc @@ -36,7 +36,7 @@ void FakeSdpServer::RegisterWithL2cap(FakeL2cap* l2cap) { void FakeSdpServer::HandleSdu(FakeDynamicChannel::WeakPtr channel, const ByteBuffer& sdu) { - BT_ASSERT(channel->opened()); + PW_CHECK(channel->opened()); auto response = server()->HandleRequest( std::make_unique(sdu), l2cap::kDefaultMTU); if (response) { diff --git a/pw_bluetooth_sapphire/host/testing/fake_signaling_server.cc b/pw_bluetooth_sapphire/host/testing/fake_signaling_server.cc index ba5a226625..6803357e7e 100644 --- a/pw_bluetooth_sapphire/host/testing/fake_signaling_server.cc +++ b/pw_bluetooth_sapphire/host/testing/fake_signaling_server.cc @@ -29,11 +29,11 @@ void FakeSignalingServer::RegisterWithL2cap(FakeL2cap* l2cap_) { void FakeSignalingServer::HandleSdu(hci_spec::ConnectionHandle conn, const ByteBuffer& sdu) { - BT_ASSERT_MSG(sdu.size() >= sizeof(l2cap::CommandHeader), - "SDU has only %zu bytes", - sdu.size()); - BT_ASSERT(sdu.To().length == - (sdu.size() - sizeof(l2cap::CommandHeader))); + PW_CHECK(sdu.size() >= sizeof(l2cap::CommandHeader), + "SDU has only %zu bytes", + sdu.size()); + PW_CHECK(sdu.To().length == + (sdu.size() - sizeof(l2cap::CommandHeader))); // Extract CommandCode and strip signaling packet header from sdu. l2cap::CommandHeader packet_header = sdu.To(); l2cap::CommandCode packet_code = packet_header.code; diff --git a/pw_bluetooth_sapphire/host/testing/inspect_util.cc b/pw_bluetooth_sapphire/host/testing/inspect_util.cc index 27f6dc63da..7d7eb1edd8 100644 --- a/pw_bluetooth_sapphire/host/testing/inspect_util.cc +++ b/pw_bluetooth_sapphire/host/testing/inspect_util.cc @@ -28,7 +28,7 @@ inspect::Hierarchy ReadInspect(const inspect::Inspector& inspector) { hierarchy = std::move(res); })); executor.run(); - BT_ASSERT(hierarchy.is_ok()); + PW_CHECK(hierarchy.is_ok()); return hierarchy.take_value(); } diff --git a/pw_bluetooth_sapphire/host/testing/mock_controller.cc b/pw_bluetooth_sapphire/host/testing/mock_controller.cc index 402a1d9081..055c43f2f0 100644 --- a/pw_bluetooth_sapphire/host/testing/mock_controller.cc +++ b/pw_bluetooth_sapphire/host/testing/mock_controller.cc @@ -135,8 +135,8 @@ bool MockController::AllExpectedCommandPacketsSent() const { } void MockController::SetDataCallback(DataCallback callback) { - BT_DEBUG_ASSERT(callback); - BT_DEBUG_ASSERT(!data_callback_); + PW_DCHECK(callback); + PW_DCHECK(!data_callback_); data_callback_ = std::move(callback); } @@ -151,8 +151,8 @@ void MockController::SetTransactionCallback(fit::closure callback) { } void MockController::SetTransactionCallback(TransactionCallback callback) { - BT_DEBUG_ASSERT(callback); - BT_DEBUG_ASSERT(!transaction_callback_); + PW_DCHECK(callback); + PW_DCHECK(!transaction_callback_); transaction_callback_ = std::move(callback); } diff --git a/pw_bluetooth_sapphire/host/testing/run_all_unittests.cc b/pw_bluetooth_sapphire/host/testing/run_all_unittests.cc index 319fa99fad..c7ed3eb00a 100644 --- a/pw_bluetooth_sapphire/host/testing/run_all_unittests.cc +++ b/pw_bluetooth_sapphire/host/testing/run_all_unittests.cc @@ -104,7 +104,7 @@ int main(int argc, char** argv) { pw::string::Format( new_argv_seed_option, "--gtest_random_seed=%d", random_seed) .ok(); - BT_ASSERT(format_ok); + PW_CHECK(format_ok); new_argv.push_back(new_argv_seed_option); } diff --git a/pw_bluetooth_sapphire/host/transport/acl_data_channel.cc b/pw_bluetooth_sapphire/host/transport/acl_data_channel.cc index 73da7317e9..67a1a69568 100644 --- a/pw_bluetooth_sapphire/host/transport/acl_data_channel.cc +++ b/pw_bluetooth_sapphire/host/transport/acl_data_channel.cc @@ -191,25 +191,24 @@ AclDataChannelImpl::AclDataChannelImpl(Transport* transport, hci_(hci), bredr_buffer_info_(bredr_buffer_info), le_buffer_info_(le_buffer_info) { - BT_DEBUG_ASSERT(transport_); - BT_ASSERT(hci_); + PW_DCHECK(transport_); + PW_CHECK(hci_); - BT_DEBUG_ASSERT(bredr_buffer_info.IsAvailable() || - le_buffer_info.IsAvailable()); + PW_DCHECK(bredr_buffer_info.IsAvailable() || le_buffer_info.IsAvailable()); num_completed_packets_event_handler_id_ = transport_->command_channel()->AddEventHandler( hci_spec::kNumberOfCompletedPacketsEventCode, fit::bind_member< &AclDataChannelImpl::NumberOfCompletedPacketsCallback>(this)); - BT_DEBUG_ASSERT(num_completed_packets_event_handler_id_); + PW_DCHECK(num_completed_packets_event_handler_id_); data_buffer_overflow_event_handler_id_ = transport_->command_channel()->AddEventHandler( hci_spec::kDataBufferOverflowEventCode, fit::bind_member<&AclDataChannelImpl::DataBufferOverflowCallback>( this)); - BT_DEBUG_ASSERT(data_buffer_overflow_event_handler_id_); + PW_DCHECK(data_buffer_overflow_event_handler_id_); bt_log(DEBUG, "hci", "AclDataChannel initialized"); } @@ -233,9 +232,9 @@ void AclDataChannelImpl::RegisterConnection( connection->handle()); auto [_, inserted] = registered_connections_.emplace(connection->handle(), connection); - BT_ASSERT_MSG(inserted, - "connection with handle %#.4x already registered", - connection->handle()); + PW_CHECK(inserted, + "connection with handle %#.4x already registered", + connection->handle()); // Reset the round-robin iterators because they have been invalidated. ResetRoundRobinIterators(); @@ -300,7 +299,7 @@ void AclDataChannelImpl::IncrementPendingPacketsForLink( } void AclDataChannelImpl::SendPackets(ConnectionMap::iterator& current_link) { - BT_DEBUG_ASSERT(current_link != registered_connections_.end()); + PW_DCHECK(current_link != registered_connections_.end()); const ConnectionMap::iterator original_link = current_link; const LinkType link_type = original_link->second->type(); size_t free_buffer_packets = GetNumFreePacketsForLinkType(link_type); @@ -324,7 +323,7 @@ void AclDataChannelImpl::SendPackets(ConnectionMap::iterator& current_link) { // If there is an available packet, send and update packet counts ACLDataPacketPtr packet = current_link->second->GetNextOutboundPacket(); - BT_DEBUG_ASSERT(packet); + PW_DCHECK(packet); hci_->SendAclData(packet->view().data().subspan()); is_packet_queued = true; @@ -361,7 +360,7 @@ void AclDataChannelImpl::AttachInspect(inspect::Node& parent, } void AclDataChannelImpl::SetDataRxHandler(ACLPacketHandler rx_callback) { - BT_ASSERT(rx_callback); + PW_CHECK(rx_callback); rx_callback_ = std::move(rx_callback); hci_->SetReceiveAclFunction( fit::bind_member<&AclDataChannelImpl::OnRxPacket>(this)); @@ -372,8 +371,8 @@ void AclDataChannelImpl::ClearControllerPacketCount( // Ensure link has already been unregistered. Otherwise, queued packets for // this handle could be sent after clearing packet count, and the packet count // could become corrupted. - BT_ASSERT(registered_connections_.find(handle) == - registered_connections_.end()); + PW_CHECK(registered_connections_.find(handle) == + registered_connections_.end()); bt_log(DEBUG, "hci", "clearing pending packets (handle: %#.4x)", handle); @@ -472,8 +471,8 @@ AclDataChannelImpl::NumberOfCompletedPacketsCallback( } auto view = event.unchecked_view< pw::bluetooth::emboss::NumberOfCompletedPacketsEventView>(); - BT_ASSERT(view.header().event_code_enum().Read() == - pw::bluetooth::emboss::EventCode::NUMBER_OF_COMPLETED_PACKETS); + PW_CHECK(view.header().event_code_enum().Read() == + pw::bluetooth::emboss::EventCode::NUMBER_OF_COMPLETED_PACKETS); size_t handles_in_packet = (event.size() - @@ -545,12 +544,11 @@ AclDataChannelImpl::NumberOfCompletedPacketsCallback( size_t AclDataChannelImpl::GetNumFreePacketsForLinkType( LinkType link_type) const { if (link_type == LinkType::kACL || IsBrEdrBufferShared()) { - BT_DEBUG_ASSERT(bredr_buffer_info_.max_num_packets() >= - *num_pending_bredr_packets_); + PW_DCHECK(bredr_buffer_info_.max_num_packets() >= + *num_pending_bredr_packets_); return bredr_buffer_info_.max_num_packets() - *num_pending_bredr_packets_; } else if (link_type == LinkType::kLE) { - BT_DEBUG_ASSERT(le_buffer_info_.max_num_packets() >= - *num_pending_le_packets_); + PW_DCHECK(le_buffer_info_.max_num_packets() >= *num_pending_le_packets_); return le_buffer_info_.max_num_packets() - *num_pending_le_packets_; } return 0; @@ -559,10 +557,10 @@ size_t AclDataChannelImpl::GetNumFreePacketsForLinkType( void AclDataChannelImpl::DecrementPendingPacketsForLinkType(LinkType link_type, size_t count) { if (link_type == LinkType::kACL || IsBrEdrBufferShared()) { - BT_DEBUG_ASSERT(*num_pending_bredr_packets_ >= count); + PW_DCHECK(*num_pending_bredr_packets_ >= count); *num_pending_bredr_packets_.Mutable() -= count; } else if (link_type == LinkType::kLE) { - BT_DEBUG_ASSERT(*num_pending_le_packets_ >= count); + PW_DCHECK(*num_pending_le_packets_ >= count); *num_pending_le_packets_.Mutable() -= count; } } @@ -571,17 +569,16 @@ void AclDataChannelImpl::IncrementPendingPacketsForLinkType( LinkType link_type) { if (link_type == LinkType::kACL || IsBrEdrBufferShared()) { *num_pending_bredr_packets_.Mutable() += 1; - BT_DEBUG_ASSERT(*num_pending_bredr_packets_ <= - bredr_buffer_info_.max_num_packets()); + PW_DCHECK(*num_pending_bredr_packets_ <= + bredr_buffer_info_.max_num_packets()); } else if (link_type == LinkType::kLE) { *num_pending_le_packets_.Mutable() += 1; - BT_DEBUG_ASSERT(*num_pending_le_packets_ <= - le_buffer_info_.max_num_packets()); + PW_DCHECK(*num_pending_le_packets_ <= le_buffer_info_.max_num_packets()); } } void AclDataChannelImpl::OnRxPacket(pw::span buffer) { - BT_ASSERT(rx_callback_); + PW_CHECK(rx_callback_); if (buffer.size() < sizeof(hci_spec::ACLDataHeader)) { // TODO(fxbug.dev/42179582): Handle these types of errors by signaling diff --git a/pw_bluetooth_sapphire/host/transport/acl_data_packet.cc b/pw_bluetooth_sapphire/host/transport/acl_data_packet.cc index ccfcaab9ed..23ed3abd89 100644 --- a/pw_bluetooth_sapphire/host/transport/acl_data_packet.cc +++ b/pw_bluetooth_sapphire/host/transport/acl_data_packet.cc @@ -37,10 +37,10 @@ using LargeACLDataPacket = allocators::kLargeACLDataPacketSize>; ACLDataPacketPtr NewACLDataPacket(size_t payload_size) { - BT_ASSERT_MSG(payload_size <= allocators::kLargeACLDataPayloadSize, - "payload size %zu too large (allowed = %zu)", - payload_size, - allocators::kLargeACLDataPayloadSize); + PW_CHECK(payload_size <= allocators::kLargeACLDataPayloadSize, + "payload size %zu too large (allowed = %zu)", + payload_size, + allocators::kLargeACLDataPayloadSize); if (payload_size <= allocators::kSmallACLDataPayloadSize) { return std::make_unique(payload_size); @@ -112,11 +112,11 @@ void ACLDataPacket::WriteHeader( hci_spec::ACLPacketBoundaryFlag packet_boundary_flag, hci_spec::ACLBroadcastFlag broadcast_flag) { // Must fit inside 12-bits. - BT_DEBUG_ASSERT(connection_handle <= 0x0FFF); + PW_DCHECK(connection_handle <= 0x0FFF); // Must fit inside 2-bits. - BT_DEBUG_ASSERT(static_cast(packet_boundary_flag) <= 0x03); - BT_DEBUG_ASSERT(static_cast(broadcast_flag) <= 0x03); + PW_DCHECK(static_cast(packet_boundary_flag) <= 0x03); + PW_DCHECK(static_cast(broadcast_flag) <= 0x03); // Bitwise OR causes int promotion, so the result must be explicitly casted. uint16_t handle_and_flags = static_cast( diff --git a/pw_bluetooth_sapphire/host/transport/command_channel.cc b/pw_bluetooth_sapphire/host/transport/command_channel.cc index b4521b1556..7aa66c17bc 100644 --- a/pw_bluetooth_sapphire/host/transport/command_channel.cc +++ b/pw_bluetooth_sapphire/host/transport/command_channel.cc @@ -62,7 +62,7 @@ CommandChannel::QueuedCommand::QueuedCommand( EmbossCommandPacket command_packet, std::unique_ptr transaction_data) : packet(std::move(command_packet)), data(std::move(transaction_data)) { - BT_DEBUG_ASSERT(data); + PW_DCHECK(data); } CommandChannel::TransactionData::TransactionData( @@ -82,7 +82,7 @@ CommandChannel::TransactionData::TransactionData( callback_(std::move(callback)), timeout_task_(channel_->dispatcher_), handler_id_(0u) { - BT_DEBUG_ASSERT(transaction_id != 0u); + PW_DCHECK(transaction_id != 0u); exclusions_.insert(opcode_); } @@ -101,7 +101,7 @@ CommandChannel::TransactionData::~TransactionData() { void CommandChannel::TransactionData::StartTimer() { // Transactions should only ever be started once. - BT_DEBUG_ASSERT(!timeout_task_.is_pending()); + PW_DCHECK(!timeout_task_.is_pending()); timeout_task_.set_function( [chan = channel_, tid = id()](auto, pw::Status status) { if (status.ok()) { @@ -240,9 +240,9 @@ CommandChannel::TransactionId CommandChannel::SendExclusiveCommandInternal( return 0; } - BT_ASSERT_MSG((complete_event_code == hci_spec::kLEMetaEventCode) == - le_meta_subevent_code.has_value(), - "only LE Meta Event subevents are supported"); + PW_CHECK((complete_event_code == hci_spec::kLEMetaEventCode) == + le_meta_subevent_code.has_value(), + "only LE Meta Event subevents are supported"); if (IsAsync(complete_event_code)) { // Cannot send an asynchronous command if there's an external event handler @@ -561,7 +561,7 @@ void CommandChannel::MaybeAddTransactionHandler(TransactionData* data) { EventHandlerId handler_id = NewEventHandler(code, event_type, data->opcode(), data->MakeCallback()); - BT_ASSERT(handler_id != 0u); + PW_CHECK(handler_id != 0u); data->set_handler_id(handler_id); handlers->emplace(code, handler_id); bt_log(TRACE, @@ -576,8 +576,8 @@ CommandChannel::EventHandlerId CommandChannel::NewEventHandler( EventType event_type, hci_spec::OpCode pending_opcode, EventCallbackVariant event_callback_variant) { - BT_DEBUG_ASSERT(event_code); - BT_DEBUG_ASSERT( + PW_DCHECK(event_code); + PW_DCHECK( (std::holds_alternative(event_callback_variant) && std::get(event_callback_variant)) || (std::holds_alternative(event_callback_variant) && @@ -598,8 +598,8 @@ CommandChannel::EventHandlerId CommandChannel::NewEventHandler( handler_id, EventTypeToString(event_type).c_str(), event_code); - BT_DEBUG_ASSERT(event_handler_id_map_.find(handler_id) == - event_handler_id_map_.end()); + PW_DCHECK(event_handler_id_map_.find(handler_id) == + event_handler_id_map_.end()); event_handler_id_map_[handler_id] = std::move(data); return handler_id; @@ -608,8 +608,8 @@ CommandChannel::EventHandlerId CommandChannel::NewEventHandler( void CommandChannel::UpdateTransaction(std::unique_ptr event) { hci_spec::EventCode event_code = event->event_code(); - BT_DEBUG_ASSERT(event_code == hci_spec::kCommandStatusEventCode || - event_code == hci_spec::kCommandCompleteEventCode); + PW_DCHECK(event_code == hci_spec::kCommandStatusEventCode || + event_code == hci_spec::kCommandCompleteEventCode); hci_spec::OpCode matching_opcode; @@ -650,7 +650,7 @@ void CommandChannel::UpdateTransaction(std::unique_ptr event) { } std::unique_ptr& transaction_ref = it->second; - BT_DEBUG_ASSERT(transaction_ref->opcode() == matching_opcode); + PW_DCHECK(transaction_ref->opcode() == matching_opcode); // If the command is synchronous or there's no handler to cleanup, we're done. if (transaction_ref->handler_id() == 0u) { @@ -732,10 +732,10 @@ void CommandChannel::NotifyEventHandler(std::unique_ptr event) { event_id, event_code); auto handler_iter = event_handler_id_map_.find(event_id); - BT_DEBUG_ASSERT(handler_iter != event_handler_id_map_.end()); + PW_DCHECK(handler_iter != event_handler_id_map_.end()); EventHandlerData& handler = handler_iter->second; - BT_DEBUG_ASSERT(handler.event_code == event_code); + PW_DCHECK(handler.event_code == event_code); std::visit( [&pending_callbacks, event_id](auto& callback) { diff --git a/pw_bluetooth_sapphire/host/transport/control_packets.cc b/pw_bluetooth_sapphire/host/transport/control_packets.cc index c8c1557035..38489f76ee 100644 --- a/pw_bluetooth_sapphire/host/transport/control_packets.cc +++ b/pw_bluetooth_sapphire/host/transport/control_packets.cc @@ -35,7 +35,7 @@ using EventFixedSizedPacket = template bool StatusCodeFromEvent(const EventPacket& event, pw::bluetooth::emboss::StatusCode* out_code) { - BT_DEBUG_ASSERT(out_code); + PW_DCHECK(out_code); if (event.view().payload_size() < sizeof(T)) return false; @@ -49,7 +49,7 @@ bool StatusCodeFromEvent(const EventPacket& event, template bool StatusCodeFromEmbossEvent(const EventPacket& event, pw::bluetooth::emboss::StatusCode* out_code) { - BT_DEBUG_ASSERT(out_code); + PW_DCHECK(out_code); auto emboss_packet = EmbossEventPacket::New(event.event_code()); bt::MutableBufferView dest = emboss_packet.mutable_data(); @@ -73,7 +73,7 @@ bool StatusCodeFromEmbossEvent(const EventPacket& event, template bool StatusCodeFromSubevent(const EventPacket& event, pw::bluetooth::emboss::StatusCode* out_code) { - BT_ASSERT(out_code); + PW_CHECK(out_code); if (event.view().payload_size() < sizeof(hci_spec::LEMetaEventParams) + sizeof(T)) @@ -87,7 +87,7 @@ bool StatusCodeFromSubevent(const EventPacket& event, template <> bool StatusCodeFromEvent( const EventPacket& event, pw::bluetooth::emboss::StatusCode* out_code) { - BT_DEBUG_ASSERT(out_code); + PW_DCHECK(out_code); const auto* params = event.return_params(); if (!params) diff --git a/pw_bluetooth_sapphire/host/transport/emboss_control_packets.cc b/pw_bluetooth_sapphire/host/transport/emboss_control_packets.cc index ba27888ad1..106c8d0a0f 100644 --- a/pw_bluetooth_sapphire/host/transport/emboss_control_packets.cc +++ b/pw_bluetooth_sapphire/host/transport/emboss_control_packets.cc @@ -26,10 +26,9 @@ namespace android_emb = pw::bluetooth::vendor::android_hci; EmbossCommandPacket::EmbossCommandPacket(hci_spec::OpCode opcode, size_t packet_size) : DynamicPacket(packet_size) { - BT_ASSERT_MSG( - packet_size >= - pw::bluetooth::emboss::CommandHeader::IntrinsicSizeInBytes(), - "command packet size must be at least 3 bytes to accomodate header"); + PW_CHECK(packet_size >= + pw::bluetooth::emboss::CommandHeader::IntrinsicSizeInBytes(), + "command packet size must be at least 3 bytes to accomodate header"); auto header = view(); header.opcode_bits().BackingStorage().WriteUInt(opcode); header.parameter_total_size().Write( @@ -56,7 +55,7 @@ pw::bluetooth::emboss::CommandHeaderView EmbossCommandPacket::header_view() EmbossEventPacket::EmbossEventPacket(size_t packet_size) : DynamicPacket(packet_size) { - BT_ASSERT_MSG( + PW_CHECK( packet_size >= pw::bluetooth::emboss::EventHeader::IntrinsicSizeInBytes(), "event packet size must be at least 2 bytes to accomodate header"); } diff --git a/pw_bluetooth_sapphire/host/transport/fake_sco_data_channel.cc b/pw_bluetooth_sapphire/host/transport/fake_sco_data_channel.cc index 7f0408d23a..b2fff86382 100644 --- a/pw_bluetooth_sapphire/host/transport/fake_sco_data_channel.cc +++ b/pw_bluetooth_sapphire/host/transport/fake_sco_data_channel.cc @@ -20,12 +20,12 @@ void FakeScoDataChannel::RegisterConnection( WeakPtr connection) { auto [iter, inserted] = connections_.emplace( connection->handle(), RegisteredConnection{std::move(connection)}); - BT_ASSERT(inserted); + PW_CHECK(inserted); } void FakeScoDataChannel::UnregisterConnection( hci_spec::ConnectionHandle handle) { - BT_ASSERT(connections_.erase(handle) == 1); + PW_CHECK(connections_.erase(handle) == 1); } void FakeScoDataChannel::OnOutboundPacketReadable() { readable_count_++; } diff --git a/pw_bluetooth_sapphire/host/transport/iso_data_channel.cc b/pw_bluetooth_sapphire/host/transport/iso_data_channel.cc index a42f281c4f..e6f7abbe6e 100644 --- a/pw_bluetooth_sapphire/host/transport/iso_data_channel.cc +++ b/pw_bluetooth_sapphire/host/transport/iso_data_channel.cc @@ -48,7 +48,7 @@ IsoDataChannelImpl::IsoDataChannelImpl(const DataBufferInfo& buffer_info, : command_channel_(command_channel), hci_(hci), buffer_info_(buffer_info) { // IsoDataChannel shouldn't be used if the buffer is unavailable (implying the // controller doesn't support isochronous channels). - BT_ASSERT(buffer_info_.IsAvailable()); + PW_CHECK(buffer_info_.IsAvailable()); hci_->SetReceiveIsoFunction( fit::bind_member<&IsoDataChannelImpl::OnRxPacket>(this)); diff --git a/pw_bluetooth_sapphire/host/transport/mock_acl_data_channel.cc b/pw_bluetooth_sapphire/host/transport/mock_acl_data_channel.cc index f92551b1f8..d8a9273df5 100644 --- a/pw_bluetooth_sapphire/host/transport/mock_acl_data_channel.cc +++ b/pw_bluetooth_sapphire/host/transport/mock_acl_data_channel.cc @@ -19,12 +19,12 @@ namespace bt::hci::testing { void MockAclDataChannel::ReceivePacket(std::unique_ptr packet) { - BT_ASSERT(data_rx_handler_); + PW_CHECK(data_rx_handler_); data_rx_handler_(std::move(packet)); } void MockAclDataChannel::SetDataRxHandler(ACLPacketHandler rx_callback) { - BT_ASSERT(rx_callback); + PW_CHECK(rx_callback); data_rx_handler_ = std::move(rx_callback); } @@ -36,9 +36,9 @@ void MockAclDataChannel::RegisterConnection( connection->handle()); auto [_, inserted] = registered_connections_.emplace(connection->handle(), connection); - BT_ASSERT_MSG(inserted, - "connection with handle %#.4x already registered", - connection->handle()); + PW_CHECK(inserted, + "connection with handle %#.4x already registered", + connection->handle()); } void MockAclDataChannel::UnregisterConnection( diff --git a/pw_bluetooth_sapphire/host/transport/sco_data_channel.cc b/pw_bluetooth_sapphire/host/transport/sco_data_channel.cc index 0e089f7e67..0e579c06b7 100644 --- a/pw_bluetooth_sapphire/host/transport/sco_data_channel.cc +++ b/pw_bluetooth_sapphire/host/transport/sco_data_channel.cc @@ -81,7 +81,7 @@ class ScoDataChannelImpl final : public ScoDataChannel { return false; } auto iter = connections_.find(active_connection_->handle()); - BT_ASSERT(iter != connections_.end()); + PW_CHECK(iter != connections_.end()); return (iter->second.config_state == HciConfigState::kConfigured); } @@ -112,13 +112,13 @@ ScoDataChannelImpl::ScoDataChannelImpl(const DataBufferInfo& buffer_info, : command_channel_(command_channel), hci_(hci), buffer_info_(buffer_info) { // ScoDataChannel shouldn't be used if the buffer is unavailable (implying the // controller doesn't support SCO). - BT_ASSERT(buffer_info_.IsAvailable()); + PW_CHECK(buffer_info_.IsAvailable()); num_completed_packets_event_handler_id_ = command_channel_->AddEventHandler( hci_spec::kNumberOfCompletedPacketsEventCode, fit::bind_member<&ScoDataChannelImpl::OnNumberOfCompletedPacketsEvent>( this)); - BT_ASSERT(num_completed_packets_event_handler_id_); + PW_CHECK(num_completed_packets_event_handler_id_); hci_->SetReceiveScoFunction( fit::bind_member<&ScoDataChannelImpl::OnRxPacket>(this)); @@ -130,14 +130,14 @@ ScoDataChannelImpl::~ScoDataChannelImpl() { void ScoDataChannelImpl::RegisterConnection( WeakPtr connection) { - BT_ASSERT(connection->parameters().view().output_data_path().Read() == - pw::bluetooth::emboss::ScoDataPath::HCI); + PW_CHECK(connection->parameters().view().output_data_path().Read() == + pw::bluetooth::emboss::ScoDataPath::HCI); ConnectionData conn_data{.connection = connection}; auto [_, inserted] = connections_.emplace(connection->handle(), std::move(conn_data)); - BT_ASSERT_MSG(inserted, - "connection with handle %#.4x already registered", - connection->handle()); + PW_CHECK(inserted, + "connection with handle %#.4x already registered", + connection->handle()); MaybeUpdateActiveConnection(); } @@ -154,7 +154,7 @@ void ScoDataChannelImpl::UnregisterConnection( void ScoDataChannelImpl::ClearControllerPacketCount( hci_spec::ConnectionHandle handle) { bt_log(DEBUG, "hci", "clearing pending packets (handle: %#.4x)", handle); - BT_ASSERT(connections_.find(handle) == connections_.end()); + PW_CHECK(connections_.find(handle) == connections_.end()); auto iter = pending_packet_counts_.find(handle); if (iter == pending_packet_counts_.end()) { @@ -226,8 +226,8 @@ ScoDataChannelImpl::OnNumberOfCompletedPacketsEvent( } auto view = event.unchecked_view< pw::bluetooth::emboss::NumberOfCompletedPacketsEventView>(); - BT_ASSERT(view.header().event_code_enum().Read() == - pw::bluetooth::emboss::EventCode::NUMBER_OF_COMPLETED_PACKETS); + PW_CHECK(view.header().event_code_enum().Read() == + pw::bluetooth::emboss::EventCode::NUMBER_OF_COMPLETED_PACKETS); const size_t handles_in_packet = (event.size() - @@ -415,7 +415,7 @@ void ScoDataChannelImpl::ConfigureHci() { } auto conn = connections_.find(active_connection_->handle()); - BT_ASSERT(conn != connections_.end()); + PW_CHECK(conn != connections_.end()); auto callback = [self = weak_self_.GetWeakPtr(), handle = conn->first](pw::Status status) { diff --git a/pw_bluetooth_sapphire/host/transport/sco_data_packet.cc b/pw_bluetooth_sapphire/host/transport/sco_data_packet.cc index 3ca8c1b28f..ae3c556030 100644 --- a/pw_bluetooth_sapphire/host/transport/sco_data_packet.cc +++ b/pw_bluetooth_sapphire/host/transport/sco_data_packet.cc @@ -61,7 +61,7 @@ void ScoDataPacket::InitializeFromBuffer() { void ScoDataPacket::WriteHeader(hci_spec::ConnectionHandle connection_handle) { // Handle must fit inside 12-bits. - BT_ASSERT(connection_handle <= 0x0FFF); + PW_CHECK(connection_handle <= 0x0FFF); // This sets the Packet Status Flag (upper bits of handle_and_flags) to 0, // which is required for Host->Controller SCO packets. mutable_view()->mutable_header()->handle_and_flags = diff --git a/pw_bluetooth_sapphire/host/transport/transport.cc b/pw_bluetooth_sapphire/host/transport/transport.cc index 3812582f6b..835b90fdb5 100644 --- a/pw_bluetooth_sapphire/host/transport/transport.cc +++ b/pw_bluetooth_sapphire/host/transport/transport.cc @@ -27,14 +27,14 @@ Transport::Transport(std::unique_ptr controller, : WeakSelf(this), dispatcher_(dispatcher), controller_(std::move(controller)) { - BT_ASSERT(controller_); + PW_CHECK(controller_); } Transport::~Transport() { bt_log(INFO, "hci", "Transport shutting down"); } void Transport::Initialize( fit::callback complete_callback) { - BT_ASSERT(!command_channel_); + PW_CHECK(!command_channel_); bt_log(DEBUG, "hci", "initializing Transport"); auto self = GetWeakPtr(); @@ -112,7 +112,7 @@ bool Transport::InitializeScoDataChannel(const DataBufferInfo& buffer_info) { } bool Transport::InitializeIsoDataChannel(const DataBufferInfo& buffer_info) { - BT_ASSERT(buffer_info.IsAvailable()); + PW_CHECK(buffer_info.IsAvailable()); if (static_cast(*features_ & FeaturesBits::kHciIso) == 0) { bt_log(WARN, "hci", "HCI ISO not supported"); @@ -125,13 +125,13 @@ bool Transport::InitializeIsoDataChannel(const DataBufferInfo& buffer_info) { } FeaturesBits Transport::GetFeatures() { - BT_ASSERT(features_); + PW_CHECK(features_); return features_.value(); } void Transport::SetTransportErrorCallback(fit::closure callback) { - BT_ASSERT(callback); - BT_ASSERT(!error_cb_); + PW_CHECK(callback); + PW_CHECK(!error_cb_); error_cb_ = std::move(callback); } @@ -145,7 +145,7 @@ void Transport::OnChannelError() { } void Transport::AttachInspect(inspect::Node& parent, const std::string& name) { - BT_ASSERT(acl_data_channel_); + PW_CHECK(acl_data_channel_); hci_node_ = parent.CreateChild(name); if (command_channel_) { diff --git a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/att/attribute.h b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/att/attribute.h index dfe5b9718f..fadb2811b5 100644 --- a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/att/attribute.h +++ b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/att/attribute.h @@ -237,14 +237,14 @@ class AttributeGrouping final { } const UUID& group_type() const { - BT_DEBUG_ASSERT(!attributes_.empty()); + PW_DCHECK(!attributes_.empty()); return attributes_[0].type(); } // Value of the group declaration attribute. BufferView decl_value() const { - BT_DEBUG_ASSERT(!attributes_.empty()); - BT_DEBUG_ASSERT(attributes_[0].value()); + PW_DCHECK(!attributes_.empty()); + PW_DCHECK(attributes_[0].value()); return attributes_[0].value()->view(); } @@ -254,8 +254,7 @@ class AttributeGrouping final { bool active() const { return active_; } void set_active(bool active) { - BT_DEBUG_ASSERT_MSG(complete(), - "set_active() called on incomplete grouping!"); + PW_DCHECK(complete(), "set_active() called on incomplete grouping!"); active_ = active; } diff --git a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/att/bearer.h b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/att/bearer.h index 0b44eec2bc..561bc147b5 100644 --- a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/att/bearer.h +++ b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/att/bearer.h @@ -75,7 +75,7 @@ class Bearer final { // procedures. uint16_t preferred_mtu() const { return preferred_mtu_; } void set_preferred_mtu(uint16_t value) { - BT_DEBUG_ASSERT(value >= kLEMinMTU); + PW_DCHECK(value >= kLEMinMTU); preferred_mtu_ = value; } diff --git a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/assert.h b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/assert.h index 85ccc37866..47b828db4c 100644 --- a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/assert.h +++ b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/assert.h @@ -13,6 +13,7 @@ // the License. #pragma once +#include "pw_assert/assert.h" #include "pw_assert/check.h" #define BT_PANIC(msg, ...) PW_CRASH(msg, ##__VA_ARGS__) diff --git a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/bounded_inspect_list_node.h b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/bounded_inspect_list_node.h index 207a7f0576..d4640b4609 100644 --- a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/bounded_inspect_list_node.h +++ b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/bounded_inspect_list_node.h @@ -57,7 +57,7 @@ class BoundedInspectListNode { }; explicit BoundedInspectListNode(size_t capacity) : capacity_(capacity) { - BT_ASSERT(capacity_ > 0u); + PW_CHECK(capacity_ > 0u); } ~BoundedInspectListNode() = default; diff --git a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/byte_buffer.h b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/byte_buffer.h index d356401d79..bcbf7bfa1c 100644 --- a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/byte_buffer.h +++ b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/byte_buffer.h @@ -107,7 +107,7 @@ class ByteBuffer { // Read-only random access operator. inline const uint8_t& operator[](size_t pos) const { - BT_ASSERT_MSG(pos < size(), "invalid offset (pos = %zu)", pos); + PW_CHECK(pos < size(), "invalid offset (pos = %zu)", pos); return data()[pos]; } @@ -161,10 +161,10 @@ class ByteBuffer { auto ReadMember() const { using ClassT = typename bt_lib_cpp_type::MemberPointerTraits< PointerToMember>::ClassType; - BT_ASSERT_MSG(sizeof(ClassT) <= this->size(), - "insufficient buffer (class size: %zu, buffer size: %zu)", - sizeof(ClassT), - this->size()); + PW_CHECK(sizeof(ClassT) <= this->size(), + "insufficient buffer (class size: %zu, buffer size: %zu)", + sizeof(ClassT), + this->size()); using MemberT = typename bt_lib_cpp_type::MemberPointerTraits< PointerToMember>::MemberType; if constexpr (std::is_array_v) { @@ -215,10 +215,10 @@ class ByteBuffer { // From the ReadMember<&Foo::bar>(2) example, ClassT = Foo using ClassT = typename bt_lib_cpp_type::MemberPointerTraits< PointerToMember>::ClassType; - BT_ASSERT_MSG(sizeof(ClassT) <= this->size(), - "insufficient buffer (class size: %zu, buffer size: %zu)", - sizeof(ClassT), - this->size()); + PW_CHECK(sizeof(ClassT) <= this->size(), + "insufficient buffer (class size: %zu, buffer size: %zu)", + sizeof(ClassT), + this->size()); // From the ReadMember<&Foo::bar>(2) example, MemberT = float[3] using MemberT = typename bt_lib_cpp_type::MemberPointerTraits< @@ -241,15 +241,14 @@ class ByteBuffer { // unlikely case that it contains additional bytes, we can't use its size // for array indexing calculations. static_assert(sizeof(MemberAsStdArrayT) == sizeof(MemberT)); - BT_ASSERT_MSG(index < kArraySize, - "index past array bounds (index: %zu, array size: %zu)", - index, - kArraySize); + PW_CHECK(index < kArraySize, + "index past array bounds (index: %zu, array size: %zu)", + index, + kArraySize); } else { // Allow flexible array members (at the end of structs) that have zero // length - BT_ASSERT_MSG(base_offset == sizeof(ClassT), - "read from zero-length array"); + PW_CHECK(base_offset == sizeof(ClassT), "read from zero-length array"); } // From the ReadMember<&Foo::bar>(2) example, ElementT = float @@ -307,7 +306,7 @@ class MutableByteBuffer : public ByteBuffer { // Random access operator that allows mutations. inline uint8_t& operator[](size_t pos) { - BT_ASSERT_MSG(pos < size(), "invalid offset (pos = %zu)", pos); + PW_CHECK(pos < size(), "invalid offset (pos = %zu)", pos); return mutable_data()[pos]; } @@ -323,7 +322,7 @@ class MutableByteBuffer : public ByteBuffer { template T* AsMutable() { static_assert(std::is_trivially_copyable_v); - BT_ASSERT(size() >= sizeof(T)); + PW_CHECK(size() >= sizeof(T)); return reinterpret_cast(mutable_data()); } @@ -428,7 +427,7 @@ class StaticByteBuffer : public MutableByteBuffer { // This is a runtime assert because this class was written to work with // non-constant values but most uses of StaticByteBuffer are in tests so // this is an acceptable cost. - BT_DEBUG_ASSERT((is_byte_storable(bytes) && ...)); + PW_DASSERT((is_byte_storable(bytes) && ...)); } } diff --git a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/error.h b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/error.h index 629eb9c22c..62c34442bc 100644 --- a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/error.h +++ b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/error.h @@ -59,7 +59,7 @@ template <> struct ProtocolErrorTraits { // This won't be called but still needs to be stubbed out to link correctly. static std::string ToString(NoProtocolError) { - BT_ASSERT(false); + PW_CHECK(false); return std::string(); } }; @@ -216,12 +216,12 @@ class [[nodiscard]] Error { } [[nodiscard]] constexpr HostError host_error() const { - BT_ASSERT_MSG(is_host_error(), "Does not hold HostError"); + PW_ASSERT(is_host_error()); return std::get(error_); } [[nodiscard]] constexpr ProtocolErrorCode protocol_error() const { - BT_ASSERT_MSG(is_protocol_error(), "Does not hold protocol error"); + PW_ASSERT(is_protocol_error()); return std::get(error_); } @@ -285,7 +285,7 @@ class [[nodiscard]] Error { std::enable_if_t, int> = 0> constexpr explicit Error(const ProtocolErrorCode& proto_error) : error_(proto_error) { - BT_ASSERT(!ProtocolErrorTraits::is_success(proto_error)); + PW_ASSERT(!ProtocolErrorTraits::is_success(proto_error)); } std::variant error_; diff --git a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/inspectable.h b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/inspectable.h index a8527fc3d3..b37d7c4746 100644 --- a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/inspectable.h +++ b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/inspectable.h @@ -135,7 +135,7 @@ class Inspectable { } virtual void AttachInspect(inspect::Node& node, std::string name) { - BT_ASSERT_MSG(false, "AttachInspect not implemented for PropertyT"); + PW_CHECK(false, "AttachInspect not implemented for PropertyT"); } // Returns a InspectableGuard wrapper around the contained value that allows diff --git a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/packet_view.h b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/packet_view.h index 19547f93ef..c612ba11ff 100644 --- a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/packet_view.h +++ b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/packet_view.h @@ -36,13 +36,13 @@ class PacketViewBase { size_t size() const { return size_; } size_t payload_size() const { - BT_ASSERT(size() >= header_size()); + PW_CHECK(size() >= header_size()); return size() - header_size(); } template const PayloadType& payload() const { - BT_ASSERT(sizeof(PayloadType) <= payload_size()); + PW_CHECK(sizeof(PayloadType) <= payload_size()); return *reinterpret_cast(payload_data().data()); } @@ -62,11 +62,11 @@ class PacketViewBase { : header_size_(header_size), buffer_(buffer), size_(header_size_ + payload_size) { - BT_ASSERT(buffer_); - BT_ASSERT_MSG(buffer_->size() >= size_, - "view size %zu exceeds buffer size %zu", - size_, - buffer_->size()); + PW_CHECK(buffer_); + PW_CHECK(buffer_->size() >= size_, + "view size %zu exceeds buffer size %zu", + size_, + buffer_->size()); } // Default copy ctor is required for PacketView and MutablePacketView to be @@ -79,8 +79,8 @@ class PacketViewBase { PacketViewBase& operator=(const PacketViewBase&) = delete; void set_size(size_t size) { - BT_ASSERT(buffer_->size() >= size); - BT_ASSERT(size >= header_size()); + PW_CHECK(buffer_->size() >= size); + PW_CHECK(size >= header_size()); size_ = size; } @@ -192,7 +192,7 @@ class MutablePacketView : public PacketView { template PayloadType* mutable_payload() const { - BT_ASSERT(sizeof(PayloadType) <= this->payload_size()); + PW_CHECK(sizeof(PayloadType) <= this->payload_size()); return reinterpret_cast(mutable_payload_bytes()); } }; diff --git a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/pipeline_monitor.h b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/pipeline_monitor.h index 163f1632f6..c1a58afdb4 100644 --- a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/pipeline_monitor.h +++ b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/pipeline_monitor.h @@ -66,7 +66,7 @@ class PipelineMonitor final { } Token& operator=(Token&& other) noexcept { - BT_ASSERT(&parent_.get() == &other.parent_.get()); + PW_CHECK(&parent_.get() == &other.parent_.get()); id_ = std::exchange(other.id_, kInvalidTokenId); return *this; } @@ -98,7 +98,7 @@ class PipelineMonitor final { if (!parent_.is_alive()) { return Token(parent_, kInvalidTokenId); } - BT_ASSERT(id_ != kInvalidTokenId); + PW_CHECK(id_ != kInvalidTokenId); return parent_->Split(this, bytes_to_take); } @@ -145,11 +145,11 @@ class PipelineMonitor final { [[nodiscard]] int64_t tokens_issued() const { return tokens_issued_; } [[nodiscard]] size_t bytes_in_flight() const { return bytes_in_flight_; } [[nodiscard]] int64_t tokens_in_flight() const { - BT_ASSERT(issued_tokens_.size() <= std::numeric_limits::max()); + PW_CHECK(issued_tokens_.size() <= std::numeric_limits::max()); return issued_tokens_.size(); } [[nodiscard]] size_t bytes_retired() const { - BT_ASSERT(bytes_issued() >= bytes_in_flight()); + PW_CHECK(bytes_issued() >= bytes_in_flight()); return bytes_issued() - bytes_in_flight(); } [[nodiscard]] int64_t tokens_retired() const { @@ -181,11 +181,11 @@ class PipelineMonitor final { [[nodiscard]] Token Split(Token* token, size_t bytes_to_take) { // For consistency, complete all token map and counter modifications before // processing alerts. - BT_ASSERT(this == &token->parent_.get()); + PW_CHECK(this == &token->parent_.get()); auto iter = issued_tokens_.find(token->id_); - BT_ASSERT(iter != issued_tokens_.end()); + PW_CHECK(iter != issued_tokens_.end()); TokenInfo& token_info = iter->second; - BT_ASSERT(bytes_to_take <= token_info.byte_count); + PW_CHECK(bytes_to_take <= token_info.byte_count); if (token_info.byte_count == bytes_to_take) { return std::move(*token); } @@ -311,9 +311,9 @@ class PipelineMonitor final { void Retire(Token* token) { // For consistency, complete all token map and counter modifications before // processing alerts. - BT_ASSERT(this == &token->parent_.get()); + PW_CHECK(this == &token->parent_.get()); auto node = issued_tokens_.extract(token->id_); - BT_ASSERT(bool{node}); + PW_CHECK(bool{node}); const TokenInfo& token_info = node.mapped(); bytes_in_flight_ -= token_info.byte_count; const pw::chrono::SystemClock::duration age = diff --git a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/random.h b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/random.h index b16459909c..f1514f287c 100644 --- a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/random.h +++ b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/random.h @@ -30,7 +30,7 @@ template T Random() { static_assert(std::is_trivial_v && !std::is_pointer_v, "Type cannot be filled with random bytes"); - BT_DEBUG_ASSERT(random_generator()); + PW_DCHECK(random_generator()); T t; random_generator()->Get({reinterpret_cast(&t), sizeof(T)}); return t; diff --git a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/retire_log.h b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/retire_log.h index 4d9a2e9f5b..90ac89c322 100644 --- a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/retire_log.h +++ b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/retire_log.h @@ -132,14 +132,14 @@ class RetireLog final { std::array quantiles; // output auto unsorted_begin = elements.begin(); for (auto [partition, index] : partitions_and_indexes) { - BT_ASSERT(partition >= 0.); - BT_ASSERT(partition <= 1.); + PW_CHECK(partition >= 0.); + PW_CHECK(partition <= 1.); // Even though the last element is at index depth()-1, use depth() here // instead to ensure the final (max) element has sufficient range // representation. const size_t cut_point = static_cast(static_cast(depth()) * partition); - BT_ASSERT(cut_point <= depth()); + PW_CHECK(cut_point <= depth()); // In the case that partition = 1.0, cut_point = depth(). Saturate to the // final (max) element. diff --git a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/slab_buffer.h b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/slab_buffer.h index 5b7a872996..3f3f18ddc6 100644 --- a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/slab_buffer.h +++ b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/slab_buffer.h @@ -22,8 +22,8 @@ template class SlabBuffer : public MutableByteBuffer { public: explicit SlabBuffer(size_t size) : size_(size) { - BT_ASSERT(size); - BT_ASSERT(size_ <= buffer_.size()); + PW_CHECK(size); + PW_CHECK(size_ <= buffer_.size()); } // ByteBuffer overrides: diff --git a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/smart_task.h b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/smart_task.h index 5bf30af89b..5b12c74415 100644 --- a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/smart_task.h +++ b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/smart_task.h @@ -31,7 +31,7 @@ class SmartTask { ~SmartTask() { if (pending_) { - BT_ASSERT(Cancel()); + PW_CHECK(Cancel()); } } diff --git a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/weak_self.h b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/weak_self.h index c09a2fd728..aea57025ac 100644 --- a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/weak_self.h +++ b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/weak_self.h @@ -38,7 +38,7 @@ class WeakRef : public pw::RefCounted { // Get a reference to the alive object. void* get() { - BT_ASSERT_MSG(ptr_, "attempted to get a destroyed ptr"); + PW_CHECK(ptr_, "attempted to get a destroyed ptr"); return ptr_; } @@ -85,13 +85,13 @@ class RecyclingWeakRef : public pw::Recyclable, bool is_in_use() { return in_use_; } void* get() { - BT_ASSERT_MSG(in_use_, "shouldn't get an unallocated ptr"); - BT_ASSERT_MSG(ptr_, "attempted to get a destroyed ptr"); + PW_CHECK(in_use_, "shouldn't get an unallocated ptr"); + PW_CHECK(ptr_, "attempted to get a destroyed ptr"); return ptr_; } pw::IntrusivePtr alloc(void* p) { - BT_ASSERT(!in_use_); + PW_CHECK(!in_use_); in_use_ = true; ptr_ = p; return pw::IntrusivePtr(this); @@ -177,7 +177,7 @@ class WeakPtr { bool is_alive() const { return ptr_ && ptr_->is_alive(); } T& get() const { - BT_ASSERT_MSG(ptr_, "tried to get never-assigned weak pointer"); + PW_CHECK(ptr_, "tried to get never-assigned weak pointer"); return *static_cast(ptr_->get()); } @@ -263,7 +263,7 @@ class WeakSelf { WeakPtr GetWeakPtr() { auto weak_ref = manager_.GetWeakRef(); - BT_ASSERT_MSG(weak_ref.has_value(), "weak pointer not available"); + PW_CHECK(weak_ref.has_value(), "weak pointer not available"); return WeakPtr(*std::move(weak_ref)); } diff --git a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/windowed_inspect_numeric_property.h b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/windowed_inspect_numeric_property.h index 409c439edc..6a2de5087e 100644 --- a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/windowed_inspect_numeric_property.h +++ b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/common/windowed_inspect_numeric_property.h @@ -53,7 +53,7 @@ class WindowedInspectNumericProperty { return; } - BT_ASSERT(!values_.empty()); + PW_CHECK(!values_.empty()); auto oldest_value = values_.front(); // Undo expiring value. property_.Subtract(oldest_value.second); @@ -86,7 +86,7 @@ class WindowedInspectNumericProperty { // // AttachInspect is only supported for the convenience types declared below. virtual void AttachInspect(::inspect::Node& node, std::string name) { - BT_ASSERT_MSG(false, "AttachInspect not implemented for NumericPropertyT"); + PW_CHECK(false, "AttachInspect not implemented for NumericPropertyT"); } // Add the given value to the value of this numeric metric. diff --git a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/gap/bredr_connection.h b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/gap/bredr_connection.h index a94219a373..a828e02f9d 100644 --- a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/gap/bredr_connection.h +++ b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/gap/bredr_connection.h @@ -112,12 +112,12 @@ class BrEdrConnection final { bool interrogation_complete() const { return !request_.has_value(); } sm::SecurityProperties security_properties() const { - BT_ASSERT(pairing_state_manager_); + PW_CHECK(pairing_state_manager_); return pairing_state_manager_->security_properties(); } void set_security_mode(BrEdrSecurityMode mode) { - BT_ASSERT(pairing_state_manager_); + PW_CHECK(pairing_state_manager_); pairing_state_manager_->set_security_mode(mode); } diff --git a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/gap/bredr_connection_request.h b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/gap/bredr_connection_request.h index 622990378b..ae4fdc5a5b 100644 --- a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/gap/bredr_connection_request.h +++ b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/gap/bredr_connection_request.h @@ -117,7 +117,7 @@ class BrEdrConnectionRequest final { } Peer::InitializingConnectionToken take_peer_init_token() { - BT_ASSERT(peer_init_conn_token_); + PW_CHECK(peer_init_conn_token_); return std::exchange(peer_init_conn_token_, std::nullopt).value(); } diff --git a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/gap/low_energy_connection.h b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/gap/low_energy_connection.h index 8b3eadd3ab..f005e32a15 100644 --- a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/gap/low_energy_connection.h +++ b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/gap/low_energy_connection.h @@ -126,21 +126,21 @@ class LowEnergyConnection final : public sm::Delegate { // Sets a callback that will be called when the peer disconnects. void set_peer_disconnect_callback(PeerDisconnectCallback cb) { - BT_ASSERT(cb); + PW_CHECK(cb); peer_disconnect_callback_ = std::move(cb); } // |peer_conn_token| is a token generated by the connected Peer, and is used // to synchronize connection state. void set_peer_conn_token(Peer::ConnectionToken peer_conn_token) { - BT_ASSERT(interrogation_completed_); - BT_ASSERT(!peer_conn_token_); + PW_CHECK(interrogation_completed_); + PW_CHECK(!peer_conn_token_); peer_conn_token_ = std::move(peer_conn_token); } // Sets a callback that will be called when a fatal connection error occurs. void set_error_callback(ErrorCallback cb) { - BT_ASSERT(cb); + PW_CHECK(cb); error_callback_ = std::move(cb); } diff --git a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/hci-spec/lmp_feature_set.h b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/hci-spec/lmp_feature_set.h index bbd8411ba9..e57efc32ab 100644 --- a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/hci-spec/lmp_feature_set.h +++ b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/hci-spec/lmp_feature_set.h @@ -52,7 +52,7 @@ class LMPFeatureSet { // Sets |page| features to |features| inline void SetPage(size_t page, uint64_t features) { - BT_ASSERT(page < kMaxPages); + PW_CHECK(page < kMaxPages); features_[page] = features; valid_pages_[page] = true; } diff --git a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/hci/low_energy_advertiser.h b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/hci/low_energy_advertiser.h index d11e5b8047..864ef68fe0 100644 --- a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/hci/low_energy_advertiser.h +++ b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/hci/low_energy_advertiser.h @@ -34,7 +34,7 @@ class AdvertisingIntervalRange final { constexpr AdvertisingIntervalRange(uint16_t min, uint16_t max) : min_(std::max(min, hci_spec::kLEAdvertisingIntervalMin)), max_(std::min(max, hci_spec::kLEAdvertisingIntervalMax)) { - BT_ASSERT(min < max); + PW_ASSERT(min < max); } uint16_t min() const { return min_; } diff --git a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/l2cap/bredr_command_handler.h b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/l2cap/bredr_command_handler.h index 3f61cdb84c..371087ee6d 100644 --- a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/l2cap/bredr_command_handler.h +++ b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/l2cap/bredr_command_handler.h @@ -77,20 +77,20 @@ class BrEdrCommandHandler final : public CommandHandler { InformationResult result() const { return result_; } uint16_t connectionless_mtu() const { - BT_ASSERT(result() == InformationResult::kSuccess); - BT_ASSERT(type() == InformationType::kConnectionlessMTU); + PW_CHECK(result() == InformationResult::kSuccess); + PW_CHECK(type() == InformationType::kConnectionlessMTU); return data_.To(); } ExtendedFeatures extended_features() const { - BT_ASSERT(result() == InformationResult::kSuccess); - BT_ASSERT(type() == InformationType::kExtendedFeaturesSupported); + PW_CHECK(result() == InformationResult::kSuccess); + PW_CHECK(type() == InformationType::kExtendedFeaturesSupported); return data_.To(); } FixedChannelsSupported fixed_channels() const { - BT_ASSERT(result() == InformationResult::kSuccess); - BT_ASSERT(type() == InformationType::kFixedChannelsSupported); + PW_CHECK(result() == InformationResult::kSuccess); + PW_CHECK(type() == InformationType::kFixedChannelsSupported); return data_.To(); } diff --git a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/l2cap/frame_headers.h b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/l2cap/frame_headers.h index 5376813d78..f3a06d6111 100644 --- a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/l2cap/frame_headers.h +++ b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/l2cap/frame_headers.h @@ -95,7 +95,7 @@ struct EnhancedControlField { } void set_receive_seq_num(uint8_t seq_num) { - BT_DEBUG_ASSERT(seq_num <= kMaxSeqNum); + PW_DCHECK(seq_num <= kMaxSeqNum); // "Receive Sequence Number - ReqSeq" Vol 3, Part A, Section 3.3.2, // Table 3.2. uint16_t host_val = @@ -142,7 +142,7 @@ struct SimpleInformationFrameHeader : public EnhancedControlField { SimpleInformationFrameHeader() = default; explicit SimpleInformationFrameHeader(uint8_t tx_seq) { - BT_DEBUG_ASSERT(tx_seq <= kMaxSeqNum); + PW_DCHECK(tx_seq <= kMaxSeqNum); uint16_t host_val = pw::bytes::ConvertOrderFrom(cpp20::endian::little, raw_value); host_val |= (tx_seq << 1); @@ -150,7 +150,7 @@ struct SimpleInformationFrameHeader : public EnhancedControlField { } uint8_t tx_seq() const { - BT_DEBUG_ASSERT(!designates_supervisory_frame()); + PW_DCHECK(!designates_supervisory_frame()); return (pw::bytes::ConvertOrderFrom(cpp20::endian::little, raw_value) & (0b0111'1110)) >> 1; @@ -192,7 +192,7 @@ struct SimpleSupervisoryFrame : public EnhancedControlField { SimpleSupervisoryFrame() = default; explicit SimpleSupervisoryFrame(SupervisoryFunction sfunc) { - BT_DEBUG_ASSERT(sfunc <= SupervisoryFunction::SelectiveReject); + PW_DCHECK(sfunc <= SupervisoryFunction::SelectiveReject); set_supervisory_frame(); // See Vol 3, Part A, Sec 3.3.2, Table 3.2. uint16_t host_val = diff --git a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/l2cap/pdu.h b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/l2cap/pdu.h index 42e972f9c9..e8b050d598 100644 --- a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/l2cap/pdu.h +++ b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/l2cap/pdu.h @@ -69,7 +69,7 @@ class PDU final { // The connection handle that identifies the logical link this PDU is intended // for. hci_spec::ConnectionHandle connection_handle() const { - BT_DEBUG_ASSERT(is_valid()); + PW_DCHECK(is_valid()); return (*fragments_.begin())->connection_handle(); } diff --git a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/l2cap/tx_engine.h b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/l2cap/tx_engine.h index b4909a4e7b..9dc8ffba41 100644 --- a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/l2cap/tx_engine.h +++ b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/l2cap/tx_engine.h @@ -62,7 +62,7 @@ class TxEngine { : channel_id_(channel_id), max_tx_sdu_size_(max_tx_sdu_size), channel_(channel) { - BT_ASSERT(max_tx_sdu_size_); + PW_CHECK(max_tx_sdu_size_); } virtual ~TxEngine() = default; diff --git a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/sdp/data_element.h b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/sdp/data_element.h index c51727f823..fa7ef9dab6 100644 --- a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/sdp/data_element.h +++ b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/sdp/data_element.h @@ -32,17 +32,17 @@ namespace bt::sdp { // DataElement elem; // A null type // uint32_t seymour = 0xFEED; // elem.Set(seymour); -// BT_DEBUG_ASSERT(elem.type() == DataElement::Type::kUnsignedInt); -// BT_DEBUG_ASSERT(elem.Get()); -// BT_DEBUG_ASSERT(*elem.Get() == seymour); +// PW_DCHECK(elem.type() == DataElement::Type::kUnsignedInt); +// PW_DCHECK(elem.Get()); +// PW_DCHECK(*elem.Get() == seymour); // // std::vector service_class_ids; // DataElement uuid; // uuid.Set(UUID(sdp::ServiceClass::kAudioSource)); // service_class_ids.emplace_back(std::move(uuid)); // elem.Set(service_class_ids); -// BT_DEBUG_ASSERT(e.type() == DataElement::Type::kSequence); -// BT_DEBUG_ASSERT(!e.Get()); +// PW_DCHECK(e.type() == DataElement::Type::kSequence); +// PW_DCHECK(!e.Get()); class DataElement { public: // Type Descriptors. Only the top 5 bits are used, see kTypeMask in Bluetooth diff --git a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/sdp/pdu.h b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/sdp/pdu.h index b133013b97..564ece89dd 100644 --- a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/sdp/pdu.h +++ b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/sdp/pdu.h @@ -229,7 +229,7 @@ struct AttributeRange { AttributeRange(AttributeId attribute_range_start, AttributeId attribute_range_end) : start(attribute_range_start), end(attribute_range_end) { - BT_DEBUG_ASSERT(start <= end); + PW_DCHECK(start <= end); } AttributeId start; @@ -258,7 +258,7 @@ class ServiceAttributeRequest : public Request { // Set the maximum size allowed in the response in the Attribute list // Not allowed to be lower than kMinMaximumAttributeByteCount (7) void set_max_attribute_byte_count(uint16_t count) { - BT_DEBUG_ASSERT(count >= kMinMaximumAttributeByteCount); + PW_DCHECK(count >= kMinMaximumAttributeByteCount); max_attribute_byte_count_ = count; } uint16_t max_attribute_byte_count() const { @@ -365,7 +365,7 @@ class ServiceSearchAttributeRequest : public Request { // Set the maximum size allowed in the response in the Attribute list // Not allowed to be lower than kMinMaximumAttributeByteCount (7) void set_max_attribute_byte_count(uint16_t count) { - BT_DEBUG_ASSERT(count >= kMinMaximumAttributeByteCount); + PW_DCHECK(count >= kMinMaximumAttributeByteCount); max_attribute_byte_count_ = count; } uint16_t max_attribute_byte_count() const { diff --git a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/sm/pairing_channel.h b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/sm/pairing_channel.h index e9892ca310..81905eb155 100644 --- a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/sm/pairing_channel.h +++ b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/sm/pairing_channel.h @@ -69,8 +69,8 @@ class PairingChannel { template void SendMessageNoTimerReset(Code message_code, const PayloadType& payload) { auto kExpectedSize = kCodeToPayloadSize.find(message_code); - BT_ASSERT(kExpectedSize != kCodeToPayloadSize.end()); - BT_ASSERT(sizeof(PayloadType) == kExpectedSize->second); + PW_CHECK(kExpectedSize != kCodeToPayloadSize.end()); + PW_CHECK(sizeof(PayloadType) == kExpectedSize->second); auto pdu = util::NewPdu(sizeof(PayloadType)); PacketWriter writer(message_code, pdu.get()); *writer.mutable_payload() = payload; diff --git a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/sm/pairing_phase.h b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/sm/pairing_phase.h index 2cf24916bd..4e929526d4 100644 --- a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/sm/pairing_phase.h +++ b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/sm/pairing_phase.h @@ -105,7 +105,7 @@ class PairingPhase { void HandleChannelClosed(); PairingChannel& sm_chan() const { - BT_ASSERT(sm_chan_.is_alive()); + PW_CHECK(sm_chan_.is_alive()); return sm_chan_.get(); } diff --git a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/testing/fake_controller.h b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/testing/fake_controller.h index c6f6464edf..914cf365a8 100644 --- a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/testing/fake_controller.h +++ b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/testing/fake_controller.h @@ -480,9 +480,9 @@ class FakeController final : public ControllerTestDoubleBase, return num_supported_advertising_sets_; } void set_num_supported_advertising_sets(uint8_t value) { - BT_ASSERT(value >= extended_advertising_states_.size()); - BT_ASSERT(value <= hci_spec::kAdvertisingHandleMax + - 1); // support advertising handle of 0 + PW_CHECK(value >= extended_advertising_states_.size()); + PW_CHECK(value <= hci_spec::kAdvertisingHandleMax + + 1); // support advertising handle of 0 num_supported_advertising_sets_ = value; } diff --git a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/transport/emboss_packet.h b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/transport/emboss_packet.h index 79f534e117..7a5a2bb8ce 100644 --- a/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/transport/emboss_packet.h +++ b/pw_bluetooth_sapphire/public/pw_bluetooth_sapphire/internal/host/transport/emboss_packet.h @@ -74,14 +74,14 @@ class StaticPacket { template T view(Args... args) { T view(args..., buffer_.mutable_data(), buffer_.size()); - BT_ASSERT(view.IsComplete()); + PW_CHECK(view.IsComplete()); return view; } template T view(Args... args) const { T view(args..., buffer_.data(), buffer_.size()); - BT_ASSERT(view.IsComplete()); + PW_CHECK(view.IsComplete()); return view; } @@ -121,18 +121,16 @@ class DynamicPacket { template T view(Args... args) { T view(args..., buffer_.mutable_data(), size()); - BT_ASSERT_MSG( - view.IsComplete(), - "emboss packet buffer not large enough to hold requested view"); + PW_CHECK(view.IsComplete(), + "emboss packet buffer not large enough to hold requested view"); return view; } template T view(Args... args) const { T view(args..., buffer_.data(), size()); - BT_ASSERT_MSG( - view.IsComplete(), - "emboss packet buffer not large enough to hold requested view"); + PW_CHECK(view.IsComplete(), + "emboss packet buffer not large enough to hold requested view"); return view; }