Line data Source code
1 : /* SPDX-License-Identifier: GPL-2.0-only */
2 : /*
3 : * Copyright (c) 2023 Meta Platforms, Inc. and affiliates.
4 : */
5 :
6 : #include "core/helper.h"
7 :
8 : #include <errno.h>
9 : #include <fcntl.h>
10 : #include <stdio.h>
11 : #include <stdlib.h>
12 : #include <sys/types.h>
13 : #include <unistd.h>
14 :
15 : #include "core/logger.h"
16 :
17 : #define OPEN_MODE_644 (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
18 :
19 7 : int bf_read_file(const char *path, void **buf, size_t *len)
20 : {
21 : _cleanup_close_ int fd = -1;
22 : _cleanup_free_ void *_buf = NULL;
23 : size_t _len;
24 : ssize_t r;
25 :
26 7 : bf_assert(path);
27 6 : bf_assert(buf);
28 5 : bf_assert(len);
29 :
30 4 : fd = open(path, O_RDONLY);
31 4 : if (fd < 0)
32 1 : return bf_err_r(errno, "failed to open %s", path);
33 :
34 3 : _len = lseek(fd, 0, SEEK_END);
35 3 : lseek(fd, 0, SEEK_SET);
36 :
37 3 : _buf = malloc(_len);
38 3 : if (!_buf)
39 1 : return bf_err_r(errno, "failed to allocate memory");
40 :
41 2 : r = read(fd, _buf, _len);
42 2 : if (r < 0)
43 1 : return bf_err_r(errno, "failed to read serialized data");
44 1 : if ((size_t)r != _len)
45 0 : return bf_err_r(EIO, "can't read full serialized data");
46 :
47 : closep(&fd);
48 :
49 1 : *buf = TAKE_PTR(_buf);
50 1 : *len = _len;
51 :
52 1 : return 0;
53 : }
54 :
55 6 : int bf_write_file(const char *path, const void *buf, size_t len)
56 : {
57 : _cleanup_close_ int fd = -1;
58 : ssize_t r;
59 :
60 6 : bf_assert(path);
61 5 : bf_assert(buf);
62 :
63 4 : fd = open(path, O_TRUNC | O_CREAT | O_WRONLY, OPEN_MODE_644);
64 4 : if (fd < 0)
65 1 : return bf_err_r(errno, "failed to open %s", path);
66 :
67 3 : r = write(fd, buf, len);
68 3 : if (r < 0)
69 1 : return bf_err_r(errno, "failed to write to %s", path);
70 2 : if ((size_t)r != len)
71 1 : return bf_err_r(EIO, "can't write full data to %s", path);
72 :
73 : closep(&fd);
74 :
75 : return 0;
76 : }
|