2 * Copyright 2019 Intel Corporation
3 * SPDX-License-Identifier: MIT
17 #define fdopen _fdopen
18 #define O_CREAT _O_CREAT
19 #define O_EXCL _O_EXCL
20 #define O_WRONLY _O_WRONLY
25 os_file_create_unique(const char *filename
, int filemode
)
27 int fd
= open(filename
, O_CREAT
| O_EXCL
| O_WRONLY
, filemode
);
30 return fdopen(fd
, "w");
34 #if defined(__linux__)
38 #include <sys/syscall.h>
41 /* copied from <linux/kcmp.h> */
45 readN(int fd
, char *buf
, size_t len
)
50 ssize_t ret
= read(fd
, buf
+ total
, len
- total
);
55 if (ret
== -EINTR
|| ret
== -EAGAIN
)
64 } while (total
!= len
);
66 return total
? (ssize_t
)total
: err
;
70 os_read_file(const char *filename
, size_t *size
)
72 /* Note that this also serves as a slight margin to avoid a 2x grow when
73 * the file is just a few bytes larger when we read it than when we
75 * The string's NULL terminator is also included in here.
79 int fd
= open(filename
, O_RDONLY
);
81 /* errno set by open() */
85 /* Pre-allocate a buffer at least the size of the file if we can read
89 if (fstat(fd
, &stat
) == 0)
92 char *buf
= malloc(len
);
99 ssize_t actually_read
;
100 size_t offset
= 0, remaining
= len
- 1;
101 while ((actually_read
= readN(fd
, buf
+ offset
, remaining
)) == (ssize_t
)remaining
) {
102 char *newbuf
= realloc(buf
, 2 * len
);
112 offset
+= actually_read
;
113 remaining
= len
- offset
- 1;
118 if (actually_read
> 0)
119 offset
+= actually_read
;
121 /* Final resize to actual size */
123 char *newbuf
= realloc(buf
, len
);
140 os_same_file_description(int fd1
, int fd2
)
142 pid_t pid
= getpid();
144 /* Same file descriptor trivially implies same file description */
148 return syscall(SYS_kcmp
, pid
, pid
, KCMP_FILE
, fd1
, fd2
);
156 os_read_file(const char *filename
, size_t *size
)
163 os_same_file_description(int fd1
, int fd2
)
165 /* Same file descriptor trivially implies same file description */
169 /* Otherwise we can't tell */