From c9212e29547c0d6ab1bbbad884ef2f46fe5e97fe Mon Sep 17 00:00:00 2001 From: RJ Ascani Date: Tue, 24 Sep 2024 13:46:12 -0700 Subject: [PATCH] Align tflite::BufferPlan properly (#2698) In the non_persistent_buffer_planner_shim_test, a tflite::BufferPlan is created using a statically allocated buffer. A static array is allocated and the address of it is used with a reinterpret_cast. This is undefined behavior, as it could result in misaligned member accesses. This PR forces the statically allocated array to align as if it was a tflite::BufferPlan, and then uses placement new to construct it within the buffer. BUG=none --- .../non_persistent_buffer_planner_shim_test.cc | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tensorflow/lite/micro/memory_planner/non_persistent_buffer_planner_shim_test.cc b/tensorflow/lite/micro/memory_planner/non_persistent_buffer_planner_shim_test.cc index 5ccd469f05c..b774f4ddefb 100644 --- a/tensorflow/lite/micro/memory_planner/non_persistent_buffer_planner_shim_test.cc +++ b/tensorflow/lite/micro/memory_planner/non_persistent_buffer_planner_shim_test.cc @@ -34,9 +34,10 @@ tflite::BufferPlan* CreateBufferPlan() { // Some targets do not support dynamic memory (i.e., no malloc or new), thus, // the test need to place non-transitent memories in static variables. This is // safe because tests are guarateed to run serially. - static int8_t buffer_plan_buffer[tflite::SizeOfBufferPlan(kBufferCnt)]; + alignas(tflite::BufferPlan) static int8_t + buffer_plan_buffer[tflite::SizeOfBufferPlan(kBufferCnt)]; tflite::BufferPlan* buffer_plan_ptr = - reinterpret_cast(buffer_plan_buffer); + new (buffer_plan_buffer) tflite::BufferPlan(); buffer_plan_ptr->buffer_count = kBufferCnt; buffer_plan_ptr->buffer_plan_entries[0].offset = kBuffer0Offset; buffer_plan_ptr->buffer_plan_entries[1].offset = kBuffer1Offset;