1 /* SPDX-License-Identifier: GPL-2.0-or-later */
18 void *xmalloc(size_t size
)
20 void *p
= malloc(size
);
22 fprintf(stderr
, "Failed to allocate memory\n");
28 char *to_chars(const CHAR16 uchars
[], size_t size
)
30 char *chars
= xmalloc(size
/ 2 + 1);
32 const CHAR16
*from
= uchars
;
42 // In case there was no terminating NUL.
43 if (to
!= chars
&& to
[-1] != '\0')
49 CHAR16
*to_uchars(const char chars
[], size_t *size
)
51 *size
= (strlen(chars
) + 1) * 2;
52 CHAR16
*uchars
= xmalloc(*size
);
54 const char *from
= chars
;
63 bool str_eq(const char lhs
[], const char rhs
[])
65 return strcmp(lhs
, rhs
) == 0;
68 struct mem_range_t
map_file(const char path
[], bool rw
)
70 struct mem_range_t range
= {0};
72 int open_flags
= rw
? O_RDWR
: O_RDONLY
;
73 int mmap_flags
= rw
? PROT_READ
| PROT_WRITE
: PROT_READ
;
75 int fd
= open(path
, open_flags
);
77 fprintf(stderr
, "Failed to open(): %s\n", strerror(errno
));
82 if (fstat(fd
, &stat_buf
) != 0) {
84 fprintf(stderr
, "Failed to fstat(): %s\n", strerror(errno
));
88 if (stat_buf
.st_size
== 0) {
90 fprintf(stderr
, "Can't map an empty \"%s\" file\n", path
);
94 uint8_t *mem
= mmap(/*addr=*/NULL
, stat_buf
.st_size
, mmap_flags
,
95 MAP_SHARED
| MAP_POPULATE
, fd
, /*offset=*/0);
97 if (mem
== MAP_FAILED
) {
98 fprintf(stderr
, "Failed to mmap(): %s\n", strerror(errno
));
103 range
.length
= stat_buf
.st_size
;
107 void unmap_file(struct mem_range_t store
)
109 if (munmap(store
.start
, store
.length
) != 0)
110 fprintf(stderr
, "Failed to munmap(): %s\n", strerror(errno
));