./
Coverage:
low: ≥ 0%
medium: ≥ 50.0%
high: ≥ 80.0%
Lines:
30 / 33
90.9%
Branches:
19 / 24
79.2%
Functions:
2 / 2
100.0%

kfsw-services/src/snapshot_file.c
Line Branch Exec Source
1 #include <errno.h>
2 #include <stddef.h>
3 #include <stdint.h>
4
5 #include <zephyr/fs/fs.h>
6
7 #include <kfsw/platform/storage.h>
8
9 #include <kfsw/services/snapshot.h>
10
11 /* fs_write is allowed to write less than it was given. */
12 2174 static int write_all(struct fs_file_t *file, const uint8_t *data, size_t size)
13 {
14 2174 size_t offset = 0U;
15
16
2/2
✓ Branch 0 taken 2174 times.
✓ Branch 1 taken 2166 times.
4340 while (offset < size) {
17 2174 ssize_t written = fs_write(file, &data[offset], size - offset);
18
19
2/2
✓ Branch 0 taken 8 times.
✓ Branch 1 taken 2166 times.
2174 if (written < 0) {
20 8 return (int)written;
21 }
22
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 2166 times.
2166 if (written == 0) {
23 ✗ return -EIO;
24 }
25 2166 offset += (size_t)written;
26 }
27 2166 return 0;
28 }
29
30 2180 int kfsw_snapshot_write(const char *path, const char *temporary_path, const uint8_t *data,
31 size_t size)
32 {
33 struct fs_file_t file;
34 int result;
35 int close_result;
36
37
3/6
✓ Branch 0 taken 2180 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2180 times.
✗ Branch 3 not taken.
✗ Branch 4 not taken.
✓ Branch 5 taken 2180 times.
2180 if ((path == NULL) || (temporary_path == NULL) || (data == NULL)) {
38 ✗ return -EINVAL;
39 }
40
1/2
✗ Branch 1 not taken.
✓ Branch 2 taken 2180 times.
2180 if (!kfsw_storage_is_ready()) {
41 ✗ return -ENODEV;
42 }
43
44 /* A temporary left by an interrupted write would otherwise be appended
45 * to or reopened at its old length.
46 */
47 2180 (void)fs_unlink(temporary_path);
48
49 2180 fs_file_t_init(&file);
50 2180 result = fs_open(&file, temporary_path, FS_O_CREATE | FS_O_WRITE | FS_O_TRUNC);
51
2/2
✓ Branch 0 taken 6 times.
✓ Branch 1 taken 2174 times.
2180 if (result != 0) {
52 6 return result;
53 }
54
55 2174 result = write_all(&file, data, size);
56
2/2
✓ Branch 0 taken 2166 times.
✓ Branch 1 taken 8 times.
2174 if (result == 0) {
57 /* Sync before the rename. */
58 2166 result = fs_sync(&file);
59 }
60 2174 close_result = fs_close(&file);
61
2/2
✓ Branch 0 taken 2158 times.
✓ Branch 1 taken 16 times.
2174 if (result == 0) {
62 2158 result = close_result;
63 }
64
2/2
✓ Branch 0 taken 16 times.
✓ Branch 1 taken 2158 times.
2174 if (result != 0) {
65 16 (void)fs_unlink(temporary_path);
66 16 return result;
67 }
68
69 /* Rename is the atomic step; the target is not unlinked first. */
70 2158 result = fs_rename(temporary_path, path);
71
2/2
✓ Branch 0 taken 10 times.
✓ Branch 1 taken 2148 times.
2158 if (result != 0) {
72 10 (void)fs_unlink(temporary_path);
73 }
74 2158 return result;
75 }
76