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__)
37 #include <linux/kcmp.h>
39 #include <sys/syscall.h>
44 readN(int fd
, char *buf
, size_t len
)
49 ssize_t ret
= read(fd
, buf
+ total
, len
- total
);
54 if (ret
== -EINTR
|| ret
== -EAGAIN
)
63 } while (total
!= len
);
65 return total
? (ssize_t
)total
: err
;
69 os_read_file(const char *filename
)
71 /* Note that this also serves as a slight margin to avoid a 2x grow when
72 * the file is just a few bytes larger when we read it than when we
74 * The string's NULL terminator is also included in here.
78 int fd
= open(filename
, O_RDONLY
);
80 /* errno set by open() */
84 /* Pre-allocate a buffer at least the size of the file if we can read
88 if (fstat(fd
, &stat
) == 0)
91 char *buf
= malloc(len
);
98 ssize_t actually_read
;
99 size_t offset
= 0, remaining
= len
- 1;
100 while ((actually_read
= readN(fd
, buf
+ offset
, remaining
)) == (ssize_t
)remaining
) {
101 char *newbuf
= realloc(buf
, 2 * len
);
111 offset
+= actually_read
;
112 remaining
= len
- offset
- 1;
117 if (actually_read
> 0)
118 offset
+= actually_read
;
120 /* Final resize to actual size */
122 char *newbuf
= realloc(buf
, len
);
136 os_same_file_description(int fd1
, int fd2
)
138 pid_t pid
= getpid();
140 return syscall(SYS_kcmp
, pid
, pid
, KCMP_FILE
, fd1
, fd2
) == 0;
148 os_read_file(const char *filename
)
155 os_same_file_description(int fd1
, int fd2
)
160 debug_warn_once("Can't tell if different file descriptors reference the same"
161 " file description, false negatives might cause trouble!\n");