From 1690cc2c74e13031451b0aa617ed221477baba1b Mon Sep 17 00:00:00 2001 From: Eric Biggers Date: Thu, 3 Jun 2021 12:58:11 -0700 Subject: programs/utils: add full_pwrite() and preallocate_file() These helper functions will be used by the implementation of the --out-merkle-tree option for 'fsverity digest' and 'fsverity sign'. Link: https://lore.kernel.org/r/20210603195812.50838-4-ebiggers@kernel.org Reviewed-by: Victor Hsieh Signed-off-by: Eric Biggers --- programs/utils.c | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) (limited to 'programs/utils.c') diff --git a/programs/utils.c b/programs/utils.c index ce19b57..116eb95 100644 --- a/programs/utils.c +++ b/programs/utils.c @@ -13,10 +13,14 @@ #include #include +#include #include #include #include #include +#ifdef _WIN32 +# include +#endif /* ========== Memory allocation ========== */ @@ -126,6 +130,26 @@ bool get_file_size(struct filedes *file, u64 *size_ret) return true; } +bool preallocate_file(struct filedes *file, u64 size) +{ + int res; + + if (size == 0) + return true; +#ifdef _WIN32 + /* Not exactly the same as posix_fallocate(), but good enough... */ + res = _chsize_s(file->fd, size); +#else + res = posix_fallocate(file->fd, 0, size); +#endif + if (res != 0) { + error_msg_errno("preallocating %" PRIu64 "-byte file '%s'", + size, file->name); + return false; + } + return true; +} + bool full_read(struct filedes *file, void *buf, size_t count) { while (count) { @@ -160,6 +184,41 @@ bool full_write(struct filedes *file, const void *buf, size_t count) return true; } +static int raw_pwrite(int fd, const void *buf, int count, u64 offset) +{ +#ifdef _WIN32 + HANDLE h = (HANDLE)_get_osfhandle(fd); + OVERLAPPED pos = { .Offset = offset, .OffsetHigh = offset >> 32 }; + DWORD written = 0; + + /* Not exactly the same as pwrite(), but good enough... */ + if (!WriteFile(h, buf, count, &written, &pos)) { + errno = EIO; + return -1; + } + return written; +#else + return pwrite(fd, buf, count, offset); +#endif +} + +bool full_pwrite(struct filedes *file, const void *buf, size_t count, + u64 offset) +{ + while (count) { + int n = raw_pwrite(file->fd, buf, min(count, INT_MAX), offset); + + if (n < 0) { + error_msg_errno("writing to '%s'", file->name); + return false; + } + buf += n; + count -= n; + offset += n; + } + return true; +} + bool filedes_close(struct filedes *file) { int res; -- cgit v1.2.3