Debian Codegraph @

util/mec152x/utils.c

raw symbols SCIP
1 /* SPDX-License-Identifier: GPL-2.0-or-later */
2
3 #include "utils.h"
4
5 #include <sys/mman.h>
6 #include <sys/stat.h>
7 #include <fcntl.h>
8 #include <unistd.h>
9
10 #include <errno.h>
11 #include <limits.h>
12 #include <stdbool.h>
13 #include <stddef.h>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
17
18 /* Return CRC-8 of the data, using x^8 x^2 x 1 polynomial. */
19 uint8_t crc8_itu(const uint8_t *data, int len)
20 {
21 unsigned int crc = 0;
22 int i, j;
23
24 for (j = 0; j < len; j++, data++) {
25 crc ^= (*data << 8);
26 for (i = 8; i; i--) {
27 if (crc & 0x8000)
28 crc ^= (0x1070 << 3);
29 crc <<= 1;
30 }
31 }
32
33 return (uint8_t)(crc >> 8) ^ 0x55;
34 }
35
36 struct mem_range map_file(const char path[], bool rw)
37 {
38 struct mem_range range = {0};
39
40 int open_flags = rw ? O_RDWR : O_RDONLY;
41 int mmap_flags = rw ? PROT_READ | PROT_WRITE : PROT_READ;
42
43 int fd = open(path, open_flags);
44 if (fd == -1) {
45 fprintf(stderr, "Failed to open(): %s\n", strerror(errno));
46 return range;
47 }
48
49 struct stat stat_buf;
50 if (fstat(fd, &stat_buf) != 0) {
51 (void)close(fd);
52 fprintf(stderr, "Failed to fstat(): %s\n", strerror(errno));
53 return range;
54 }
55
56 if (stat_buf.st_size == 0) {
57 (void)close(fd);
58 fprintf(stderr, "Can't map an empty \"%s\" file\n", path);
59 return range;
60 }
61
62 uint8_t *mem = mmap(/*addr=*/NULL, stat_buf.st_size, mmap_flags,
63 MAP_SHARED | MAP_POPULATE, fd, /*offset=*/0);
64 (void)close(fd);
65 if (mem == MAP_FAILED) {
66 fprintf(stderr, "Failed to mmap(): %s\n", strerror(errno));
67 return range;
68 }
69
70 range.start = mem;
71 range.length = stat_buf.st_size;
72 return range;
73 }
74
75 void unmap_file(struct mem_range store)
76 {
77 if (munmap(store.start, store.length) != 0)
78 fprintf(stderr, "Failed to munmap(): %s\n", strerror(errno));
79 }