forked from bluewhalesystems/sold
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoutput_file.cc
98 lines (83 loc) · 2.71 KB
/
output_file.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include "mold.h"
#include <fcntl.h>
#include <libgen.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
static u32 get_umask() {
u32 orig_umask = umask(0);
umask(orig_umask);
return orig_umask;
}
class MemoryMappedOutputFile : public OutputFile {
public:
MemoryMappedOutputFile(std::string path, i64 filesize)
: OutputFile(path, filesize) {
std::string dir = dirname(strdup(config.output.c_str()));
tmpfile = strdup((dir + "/.mold-XXXXXX").c_str());
i64 fd = mkstemp(tmpfile);
if (fd == -1)
Fatal() << "cannot open " << tmpfile << ": " << strerror(errno);
if (rename(config.output.c_str(), tmpfile) == 0) {
::close(fd);
fd = ::open(tmpfile, O_RDWR | O_CREAT, 0777);
if (fd == -1) {
if (errno != ETXTBSY)
Fatal() << "cannot open " << config.output << ": " << strerror(errno);
unlink(tmpfile);
fd = ::open(tmpfile, O_RDWR | O_CREAT, 0777);
if (fd == -1)
Fatal() << "cannot open " << config.output << ": " << strerror(errno);
}
}
if (ftruncate(fd, filesize))
Fatal() << "ftruncate failed";
if (fchmod(fd, (0777 & ~get_umask())) == -1)
Fatal() << "fchmod failed";
buf = (u8 *)mmap(nullptr, filesize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (buf == MAP_FAILED)
Fatal() << config.output << ": mmap failed: " << strerror(errno);
::close(fd);
}
void close() override {
Timer t("close_file");
munmap(buf, filesize);
if (rename(tmpfile, config.output.c_str()) == -1)
Fatal() << config.output << ": rename filed: " << strerror(errno);
tmpfile = nullptr;
}
};
class MallocOutputFile : public OutputFile {
public:
MallocOutputFile(std::string path, u64 filesize)
: OutputFile(path, filesize) {
buf = (u8 *)mmap(NULL, filesize, PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANONYMOUS, -1, 0);
if (buf == MAP_FAILED)
Fatal() << "mmap failed: " << strerror(errno);
}
void close() override {
Timer t("close_file");
i64 fd = ::open(path.c_str(), O_RDWR | O_CREAT, 0777);
if (fd == -1)
Fatal() << "cannot open " << config.output << ": " << strerror(errno);
FILE *fp = fdopen(fd, "w");
fwrite(buf, filesize, 1, fp);
fclose(fp);
}
};
OutputFile *OutputFile::open(std::string path, u64 filesize) {
Timer t("open_file");
bool is_special = false;
struct stat st;
if (stat(path.c_str(), &st) == 0 && (st.st_mode & S_IFMT) != S_IFREG)
is_special = true;
OutputFile *file;
if (is_special)
file = new MallocOutputFile(path, filesize);
else
file = new MemoryMappedOutputFile(path, filesize);
if (config.filler != -1)
memset(file->buf, config.filler, filesize);
return file;
}