From aafa95bd07feeec9e40fc658c8536a548c5b25d5 Mon Sep 17 00:00:00 2001 From: Pu Cheng Date: Fri, 20 Nov 2026 05:49:41 +0800 Subject: [PATCH] in BUGFIX return the previous start address when changing memory input ly_in_memory() and ly_in_memory_chunk() are documented to return the previous starting address, which the caller is responsible to free, but they returned the current read position. After some data were read or parsed, the returned pointer pointed inside the previous data and freeing it was an invalid free. --- src/in.c | 4 ++-- tests/utests/basic/test_inout.c | 14 +++++++++++++- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/src/in.c b/src/in.c index c92739147..97977855f 100644 --- a/src/in.c +++ b/src/in.c @@ -220,7 +220,7 @@ ly_in_memory(struct ly_in *in, const char *str) LY_CHECK_ARG_RET(NULL, in, in->type == LY_IN_MEMORY, NULL); - data = in->current; + data = in->start; if (str) { in->start = in->current = str; @@ -240,7 +240,7 @@ ly_in_memory_chunk(struct ly_in *in, const void *mem, uint32_t mem_len) LY_CHECK_ARG_RET(NULL, in, in->type == LY_IN_MEMORY, NULL); - data = in->current; + data = in->start; if (mem) { in->start = in->current = mem; diff --git a/tests/utests/basic/test_inout.c b/tests/utests/basic/test_inout.c index c5e1d5c9c..8acf0e856 100644 --- a/tests/utests/basic/test_inout.c +++ b/tests/utests/basic/test_inout.c @@ -80,7 +80,8 @@ static void test_input_mem(void **UNUSED(state)) { struct ly_in *in = NULL; - char *str1 = "a", *str2 = "b"; + char *str1 = "a", *str2 = "b", *str3 = "abc"; + char buf[2]; assert_int_equal(LY_EINVAL, ly_in_new_memory(NULL, NULL)); CHECK_LOG_LASTMSG("Invalid argument str (ly_in_new_memory())."); @@ -95,6 +96,17 @@ test_input_mem(void **UNUSED(state)) assert_ptr_equal(str2, ly_in_memory(in, NULL)); assert_ptr_equal(str2, ly_in_memory(in, NULL)); ly_in_free(in, 0); + + /* the previous start address is returned also after some data were read */ + assert_int_equal(LY_SUCCESS, ly_in_new_memory(str3, &in)); + assert_int_equal(LY_SUCCESS, ly_in_read(in, buf, 2)); + assert_ptr_equal(str3, ly_in_memory(in, str1)); + ly_in_free(in, 0); + + assert_int_equal(LY_SUCCESS, ly_in_new_memory_chunk(str3, 3, &in)); + assert_int_equal(LY_SUCCESS, ly_in_read(in, buf, 2)); + assert_ptr_equal(str3, ly_in_memory_chunk(in, str1, 1)); + ly_in_free(in, 0); } static void