From fd369e066c94ba19e4233dc36030441754220553 Mon Sep 17 00:00:00 2001 From: haozi007 Date: Wed, 8 Nov 2023 10:32:43 +0800 Subject: [PATCH 03/13] add function to transfer of ownership Signed-off-by: haozi007 --- src/auto_cleanup.h | 18 ++++++++++++++++++ tests/auto_cleanup_ut.cpp | 30 +++++++++++++++++++++++++++++- 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/src/auto_cleanup.h b/src/auto_cleanup.h index 2fa9f41..6d04372 100644 --- a/src/auto_cleanup.h +++ b/src/auto_cleanup.h @@ -24,6 +24,10 @@ #ifndef __ISULA_AUTO_CLEANUP_H #define __ISULA_AUTO_CLEANUP_H +#ifndef _GNU_SOURCE +#define _GNU_SOURCE 1 +#endif + #include #include #include @@ -36,6 +40,20 @@ extern "C" { #endif +#define isula_transfer_fd(fd) \ + ({ \ + int __tmp_fd = (fd); \ + (fd) = -EBADF; \ + __tmp_fd; \ + }) + +#define isula_transfer_ptr(ptr) \ + ({ \ + __typeof__(ptr) __tmp_ptr = (ptr); \ + (ptr) = NULL; \ + __tmp_ptr; \ + }) + #define auto_cleanup_tag(name) __attribute__((__cleanup__(name##_cb))) // define all used auto tags diff --git a/tests/auto_cleanup_ut.cpp b/tests/auto_cleanup_ut.cpp index b167bcb..2600d56 100644 --- a/tests/auto_cleanup_ut.cpp +++ b/tests/auto_cleanup_ut.cpp @@ -122,6 +122,17 @@ size_t do_auto_free() #endif } +int *do_auto_free_and_transfer() +{ + __isula_auto_free int *test = nullptr; + + // use 1024 * 1024 to ensure memory allo from mmap + test = static_cast(malloc(sizeof(int))); + *test = 8; + + return isula_transfer_ptr(test); +} + TEST(autocleanup_testcase, test__isula_auto_free) { #if defined(__GLIBC__) && ((__GLIBC__ > 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 33)) @@ -145,6 +156,10 @@ TEST(autocleanup_testcase, test__isula_auto_free) ASSERT_NE(used, after.hblks); ASSERT_NE(used, before.hblks); ASSERT_EQ(before.hblks, after.hblks); + + __isula_auto_free int *transfer_ptr = do_auto_free_and_transfer(); + ASSERT_NE(nullptr, transfer_ptr); + ASSERT_EQ(8, *transfer_ptr); } int do_auto_file() @@ -198,14 +213,27 @@ int do_auto_close() return fd; } +int do_auto_close_and_transfer() +{ + __isula_auto_close int fd = -1; + + fd = open("/proc/self/cmdline", 0444); + + return isula_transfer_fd(fd); +} + TEST(autocleanup_testcase, test__isula_auto_close) { int openfd, ret; size_t i; struct stat sbuf = { 0 }; + __isula_auto_close int transfer_fd = -1; - openfd = do_auto_close(); + transfer_fd = do_auto_close_and_transfer(); + ret = fstat(transfer_fd, &sbuf); + ASSERT_EQ(0, ret); + openfd = do_auto_close(); ret = fstat(openfd, &sbuf); ASSERT_NE(0, ret); ASSERT_EQ(EBADF, errno); -- 2.33.0