From de07668b0bb07ac2f542fdced61e6153de7f4bfc Mon Sep 17 00:00:00 2001 From: Guido Casati Date: Fri, 19 Sep 2025 15:58:40 +0200 Subject: [PATCH] Fix potential memory leak in ngap_gNB_handover_request_acknowledge Move UE context creation and storage to after successful PDU encoding to prevent memory leaks if encoding fails. Also add proper PDU cleanup when AMF fetch fails and use consistent NULL check style. This ensures UE context is only stored when the operation is guaranteed to succeed, improving error handling and memory management. --- openair3/NGAP/ngap_gNB.c | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/openair3/NGAP/ngap_gNB.c b/openair3/NGAP/ngap_gNB.c index b2ba38de52..68e77d369c 100644 --- a/openair3/NGAP/ngap_gNB.c +++ b/openair3/NGAP/ngap_gNB.c @@ -376,20 +376,6 @@ static int ngap_gNB_handover_request_acknowledge(instance_t instance, ngap_hando DevAssert(msg != NULL); DevAssert(ngap != NULL); - // First, create and store NGAP UE context - ngap_gNB_ue_context_t ue_context_p = { - .amf_ref = ngap_gNB_get_AMF_from_instance(ngap), - .gNB_ue_ngap_id = msg->gNB_ue_ngap_id, - .amf_ue_ngap_id = msg->amf_ue_ngap_id, - .gNB_instance = ngap, - .ue_state = NGAP_UE_CONNECTED, - }; - if (ue_context_p.amf_ref == NULL) { - NGAP_ERROR("Failed to fetch AMF for current NGAP instance\n"); - return -1; - } - ngap_store_ue_context(&ue_context_p); - NGAP_NGAP_PDU_t *pdu = encode_ng_handover_request_ack(msg); if (!pdu) { NGAP_ERROR("Failed to encode NG Handover Request Acknowledge\n"); @@ -405,6 +391,21 @@ static int ngap_gNB_handover_request_acknowledge(instance_t instance, ngap_hando return -1; } + // Create and store NGAP UE context + ngap_gNB_ue_context_t ue_context_p = { + .amf_ref = ngap_gNB_get_AMF_from_instance(ngap), + .gNB_ue_ngap_id = msg->gNB_ue_ngap_id, + .amf_ue_ngap_id = msg->amf_ue_ngap_id, + .gNB_instance = ngap, + .ue_state = NGAP_UE_CONNECTED, + }; + if (!ue_context_p.amf_ref) { + NGAP_ERROR("Failed to fetch AMF for current NGAP instance\n"); + ASN_STRUCT_FREE(asn_DEF_NGAP_NGAP_PDU, pdu); + return -1; + } + ngap_store_ue_context(&ue_context_p); + /* UE associated signalling -> use the allocated stream */ ngap_gNB_itti_send_sctp_data_req(ngap->instance, ue_context_p.amf_ref->assoc_id, ba.buf, ba.len, ue_context_p.tx_stream); NGAP_INFO("Sent Handover Request Acknowledge to AMF\n");