diff options
author | Mattias Nissler <122288598+mnissler-rivos@users.noreply.github.com> | 2023-08-15 13:38:30 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2023-08-15 12:38:30 +0100 |
commit | e8c37f83fb92848f328e297ace37536253ee08bc (patch) | |
tree | ff61bba39e20b62240e46b95504d2f1f6f4671c1 /lib/libvfio-user.c | |
parent | 1cca91aeb8ae8f531f9c3b9c59d83630e9941a5e (diff) | |
download | libvfio-user-e8c37f83fb92848f328e297ace37536253ee08bc.zip libvfio-user-e8c37f83fb92848f328e297ace37536253ee08bc.tar.gz libvfio-user-e8c37f83fb92848f328e297ace37536253ee08bc.tar.bz2 |
Introduce close_safely helper function (#763)
The helper function centralizes some extra checks and diligence desired
by many/most current code paths but currently inconsistently applied.
This includes bypassing the close call when the file descriptor is -1
already, resetting the file descriptor variable to -1 after closing, and
preserving errno.
All calls to close are replaced by close_safely. Some warning log output
is lost over this, but it doesn't seem like this was very useful anyways
given that Linux always closes the file descriptor anyways.
Signed-off-by: Mattias Nissler <mnissler@rivosinc.com>
Diffstat (limited to 'lib/libvfio-user.c')
-rw-r--r-- | lib/libvfio-user.c | 23 |
1 files changed, 8 insertions, 15 deletions
diff --git a/lib/libvfio-user.c b/lib/libvfio-user.c index 663d2cd..48013c2 100644 --- a/lib/libvfio-user.c +++ b/lib/libvfio-user.c @@ -755,12 +755,9 @@ handle_dma_map(vfu_ctx_t *vfu_ctx, vfu_msg_t *msg, dma_map->size, fd, dma_map->offset, prot); if (ret < 0) { - ret = errno; vfu_log(vfu_ctx, LOG_ERR, "failed to add DMA region %s: %m", rstr); - if (fd != -1) { - close(fd); - } - return ERROR_INT(ret); + close_safely(&fd); + return -1; } if (vfu_ctx->dma_register != NULL) { @@ -1096,14 +1093,12 @@ free_msg(vfu_ctx_t *vfu_ctx, vfu_msg_t *msg) free(msg->in.iov.iov_base); for (i = 0; i < msg->in.nr_fds; i++) { - if (msg->in.fds[i] != -1) { - if (msg->processed_cmd) { - vfu_log(vfu_ctx, LOG_DEBUG, - "closing unexpected fd %d (index %zu) from cmd %u", - msg->in.fds[i], i, msg->hdr.cmd); - } - close(msg->in.fds[i]); + if (msg->in.fds[i] != -1 && msg->processed_cmd) { + vfu_log(vfu_ctx, LOG_DEBUG, + "closing unexpected fd %d (index %zu) from cmd %u", + msg->in.fds[i], i, msg->hdr.cmd); } + close_safely(&msg->in.fds[i]); } free(msg->in.fds); @@ -1276,11 +1271,9 @@ get_request_header(vfu_ctx_t *vfu_ctx, vfu_msg_t **msgp) *msgp = alloc_msg(&hdr, fds, nr_fds); if (*msgp == NULL) { - int saved_errno = errno; for (i = 0; i < nr_fds; i++) { - close(fds[i]); + close_safely(&fds[i]); } - errno = saved_errno; return -1; } |