From 5fe3e097f121a17b37c098f87cba2b4a51d6208b Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=A9mie=20Galarneau?= Date: Fri, 19 Jun 2020 18:20:08 -0400 Subject: [PATCH] common: add lttng_dynamic_array_set_count() MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Add an lttng_dynamic_array_set_count() helper to resize a dynamic array. Signed-off-by: Jérémie Galarneau Change-Id: Ic38efdb9c2ee6a4176fcde93e4b0d45052d14799 --- src/common/dynamic-array.c | 29 +++++++++++++++++++++++++++++ src/common/dynamic-array.h | 19 +++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/src/common/dynamic-array.c b/src/common/dynamic-array.c index 198df19bb..81c2c3efa 100644 --- a/src/common/dynamic-array.c +++ b/src/common/dynamic-array.c @@ -18,6 +18,35 @@ void lttng_dynamic_array_init(struct lttng_dynamic_array *array, array->destructor = destructor; } +LTTNG_HIDDEN +int lttng_dynamic_array_set_count(struct lttng_dynamic_array *array, + size_t new_element_count) +{ + int ret; + + if (!array) { + ret = -1; + goto end; + } + + if (array->destructor) { + size_t i; + + for (i = new_element_count; i < array->size; i++) { + void *element = lttng_dynamic_array_get_element( + array, i); + + array->destructor(element); + } + } + + array->size = new_element_count; + ret = lttng_dynamic_buffer_set_size(&array->buffer, + new_element_count * array->element_size); +end: + return ret; +} + LTTNG_HIDDEN int lttng_dynamic_array_add_element(struct lttng_dynamic_array *array, const void *element) diff --git a/src/common/dynamic-array.h b/src/common/dynamic-array.h index 208dd1956..0b488a39c 100644 --- a/src/common/dynamic-array.h +++ b/src/common/dynamic-array.h @@ -56,6 +56,25 @@ void *lttng_dynamic_array_get_element(const struct lttng_dynamic_array *array, return array->buffer.data + (element_index * array->element_size); } +/* + * Set the array's element count to new_element_count. Any added element will + * be zeroed. + * + * Be careful to expand the array's element count _before_ calling out external + * APIs (e.g. read(3)) which may populate the buffer as setting the element + * count after will zero-out the result of the operation. + * + * Shrinking an array does not zero the old content. If the buffer may contain + * sensititve information, it must be cleared manually _before_ changing the + * size. + * + * NOTE: It is striclty _invalid_ to access memory after _size_, regardless + * of prior calls to set_capacity(). + */ +LTTNG_HIDDEN +int lttng_dynamic_array_set_count(struct lttng_dynamic_array *array, + size_t new_element_count); + /* * Add an element to the end of a dynamic array. The array's element count is * increased by one and its underlying capacity is adjusted automatically. -- 2.34.1