/* SPDX-License-Identifier: LGPL-2.1+ */
+#include <malloc.h>
#include <stdint.h>
#include "alloc-util.h"
#include "macro.h"
-#include "util.h"
+#include "memory-util.h"
+#include "tests.h"
static void test_alloca(void) {
static const uint8_t zero[997] = { };
assert_se(!memcmp(t, zero, 997));
}
+static void test_GREEDY_REALLOC(void) {
+ _cleanup_free_ int *a = NULL, *b = NULL;
+ size_t n_allocated = 0, i, j;
+
+ /* Give valgrind a chance to verify our realloc() operations */
+
+ for (i = 0; i < 20480; i++) {
+ assert_se(GREEDY_REALLOC(a, n_allocated, i + 1));
+ assert_se(n_allocated >= i + 1);
+ assert_se(malloc_usable_size(a) >= (i + 1) * sizeof(int));
+ a[i] = (int) i;
+ assert_se(GREEDY_REALLOC(a, n_allocated, i / 2));
+ assert_se(n_allocated >= i / 2);
+ assert_se(malloc_usable_size(a) >= (i / 2) * sizeof(int));
+ }
+
+ for (j = 0; j < i / 2; j++)
+ assert_se(a[j] == (int) j);
+
+ for (i = 30, n_allocated = 0; i < 20480; i += 7) {
+ assert_se(GREEDY_REALLOC(b, n_allocated, i + 1));
+ assert_se(n_allocated >= i + 1);
+ assert_se(malloc_usable_size(b) >= (i + 1) * sizeof(int));
+ b[i] = (int) i;
+ assert_se(GREEDY_REALLOC(b, n_allocated, i / 2));
+ assert_se(n_allocated >= i / 2);
+ assert_se(malloc_usable_size(b) >= (i / 2) * sizeof(int));
+ }
+
+ for (j = 30; j < i / 2; j += 7)
+ assert_se(b[j] == (int) j);
+}
+
static void test_memdup_multiply_and_greedy_realloc(void) {
int org[] = {1, 2, 3};
_cleanup_free_ int *dup;
assert(!h);
}
+static int cleanup_counter = 0;
+
+static void cleanup1(void *a) {
+ log_info("%s(%p)", __func__, a);
+ assert_se(++cleanup_counter == *(int*) a);
+}
+static void cleanup2(void *a) {
+ log_info("%s(%p)", __func__, a);
+ assert_se(++cleanup_counter == *(int*) a);
+}
+static void cleanup3(void *a) {
+ log_info("%s(%p)", __func__, a);
+ assert_se(++cleanup_counter == *(int*) a);
+}
+
+static void test_cleanup_order(void) {
+ _cleanup_(cleanup1) int x1 = 4, x2 = 3;
+ _cleanup_(cleanup3) int z = 2;
+ _cleanup_(cleanup2) int y = 1;
+ log_debug("x1: %p", &x1);
+ log_debug("x2: %p", &x2);
+ log_debug("y: %p", &y);
+ log_debug("z: %p", &z);
+}
+
int main(int argc, char *argv[]) {
+ test_setup_logging(LOG_DEBUG);
+
test_alloca();
+ test_GREEDY_REALLOC();
test_memdup_multiply_and_greedy_realloc();
test_bool_assign();
+ test_cleanup_order();
return 0;
}