forked from jacobdufault/cquery
-
Notifications
You must be signed in to change notification settings - Fork 0
/
platform_linux.cc
331 lines (276 loc) · 8.4 KB
/
platform_linux.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
#if defined(__linux__) || defined(__APPLE__)
#include "platform.h"
#include "utils.h"
#include <loguru.hpp>
#include <pthread.h>
#include <cassert>
#include <iostream>
#include <string>
#include <assert.h>
#include <errno.h>
#include <limits.h>
#include <semaphore.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h> // required for stat.h
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <semaphore.h>
#include <sys/mman.h>
#ifndef __APPLE__
#include <sys/prctl.h>
#endif
#if defined(__linux__)
#include <malloc.h>
#endif
namespace {
// Returns the canonicalized absolute pathname, without expanding symbolic
// links. This is a variant of realpath(2), C++ rewrite of
// https://github.com/freebsd/freebsd/blob/master/lib/libc/stdlib/realpath.c
optional<std::string> RealPathNotExpandSymlink(std::string path) {
if (path.empty()) {
errno = EINVAL;
return nullopt;
}
if (path[0] == '\0') {
errno = ENOENT;
return nullopt;
}
// Do not use PATH_MAX because it is tricky on Linux.
// See https://eklitzke.org/path-max-is-tricky
char tmp[1024];
std::string resolved;
size_t i = 0;
struct stat sb;
if (path[0] == '/') {
resolved = "/";
i = 1;
} else {
if (!getcwd(tmp, sizeof tmp))
return nullopt;
resolved = tmp;
}
while (i < path.size()) {
auto j = path.find('/', i);
if (j == std::string::npos)
j = path.size();
auto next_token = path.substr(i, j - i);
i = j + 1;
if (resolved.back() != '/')
resolved += '/';
if (next_token.empty() || next_token == ".") {
// Handle consequential slashes and "."
continue;
} else if (next_token == "..") {
// Strip the last path component except when it is single "/"
if (resolved.size() > 1)
resolved.resize(resolved.rfind('/', resolved.size() - 2) + 1);
continue;
}
// Append the next path component.
// Here we differ from realpath(3), we use stat(2) instead of
// lstat(2) because we do not want to resolve symlinks.
resolved += next_token;
if (stat(resolved.c_str(), &sb) != 0)
return nullopt;
if (!S_ISDIR(sb.st_mode) && j < path.size()) {
errno = ENOTDIR;
return nullopt;
}
}
// Remove trailing slash except when a single "/".
if (resolved.size() > 1 && resolved.back() == '/')
resolved.pop_back();
return resolved;
}
} // namespace
struct PlatformMutexLinux : public PlatformMutex {
sem_t* sem_ = nullptr;
PlatformMutexLinux(const std::string& name) {
std::cerr << "PlatformMutexLinux name=" << name << std::endl;
sem_ = sem_open(name.c_str(), O_CREAT, 0666 /*permission*/,
1 /*initial_value*/);
}
~PlatformMutexLinux() override { sem_close(sem_); }
};
struct PlatformScopedMutexLockLinux : public PlatformScopedMutexLock {
sem_t* sem_ = nullptr;
PlatformScopedMutexLockLinux(sem_t* sem) : sem_(sem) { sem_wait(sem_); }
~PlatformScopedMutexLockLinux() override { sem_post(sem_); }
};
void* checked(void* result, const char* expr) {
if (!result) {
std::cerr << "FAIL errno=" << errno << " in |" << expr << "|" << std::endl;
std::cerr << "errno => " << strerror(errno) << std::endl;
exit(1);
}
return result;
}
int checked(int result, const char* expr) {
if (result == -1) {
std::cerr << "FAIL errno=" << errno << " in |" << expr << "|" << std::endl;
std::cerr << "errno => " << strerror(errno) << std::endl;
exit(1);
}
return result;
}
#define CHECKED(expr) checked(expr, #expr)
struct PlatformSharedMemoryLinux : public PlatformSharedMemory {
std::string name_;
size_t size_;
int fd_;
PlatformSharedMemoryLinux(const std::string& name, size_t size)
: name_(name), size_(size) {
std::cerr << "PlatformSharedMemoryLinux name=" << name << ", size=" << size
<< std::endl;
// Try to create shared memory but only if it does not already exist. Since
// we created the memory, we need to initialize it.
fd_ = shm_open(name_.c_str(), O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
if (fd_ >= 0) {
std::cerr << "Calling ftruncate fd_=" << fd_ << std::endl;
CHECKED(ftruncate(fd_, size));
}
// Otherwise, we just open existing shared memory. We don't need to
// create or initialize it.
else {
fd_ = CHECKED(shm_open(
name_.c_str(), O_RDWR, /* memory is read/write, create if needed */
S_IRUSR | S_IWUSR /* user read/write */));
}
// Map the shared memory to an address.
data = CHECKED(mmap(nullptr /*kernel assigned starting address*/, size,
PROT_READ | PROT_WRITE, MAP_SHARED, fd_, 0 /*offset*/));
capacity = size;
std::cerr << "Open shared memory name=" << name << ", fd=" << fd_
<< ", shared=" << data << ", capacity=" << capacity << std::endl;
}
~PlatformSharedMemoryLinux() override {
CHECKED(munmap(data, size_));
CHECKED(shm_unlink(name_.c_str()));
data = nullptr;
}
};
std::unique_ptr<PlatformMutex> CreatePlatformMutex(const std::string& name) {
std::string name2 = "/" + name;
return MakeUnique<PlatformMutexLinux>(name2);
}
std::unique_ptr<PlatformScopedMutexLock> CreatePlatformScopedMutexLock(
PlatformMutex* mutex) {
return MakeUnique<PlatformScopedMutexLockLinux>(
static_cast<PlatformMutexLinux*>(mutex)->sem_);
}
std::unique_ptr<PlatformSharedMemory> CreatePlatformSharedMemory(
const std::string& name,
size_t size) {
std::string name2 = "/" + name;
return MakeUnique<PlatformSharedMemoryLinux>(name2, size);
}
void PlatformInit() {}
std::string GetWorkingDirectory() {
char result[FILENAME_MAX];
if (!getcwd(result, sizeof(result)))
return "";
std::string working_dir = std::string(result, strlen(result));
EnsureEndsInSlash(working_dir);
return working_dir;
}
std::string NormalizePath(const std::string& path) {
optional<std::string> resolved = RealPathNotExpandSymlink(path);
return resolved ? *resolved : path;
}
bool TryMakeDirectory(const std::string& absolute_path) {
const mode_t kMode = 0777; // UNIX style permissions
if (mkdir(absolute_path.c_str(), kMode) == -1) {
// Success if the directory exists.
return errno == EEXIST;
}
return true;
}
void SetCurrentThreadName(const std::string& thread_name) {
loguru::set_thread_name(thread_name.c_str());
#ifndef __APPLE__
prctl(PR_SET_NAME, thread_name.c_str(), 0, 0, 0);
#endif
}
optional<int64_t> GetLastModificationTime(const std::string& absolute_path) {
struct stat buf;
if (stat(absolute_path.c_str(), &buf) != 0) {
switch (errno) {
case ENOENT:
// std::cerr << "GetLastModificationTime: unable to find file " <<
// absolute_path << std::endl;
return nullopt;
case EINVAL:
// std::cerr << "GetLastModificationTime: invalid param to _stat for
// file file " << absolute_path << std::endl;
return nullopt;
default:
// std::cerr << "GetLastModificationTime: unhandled for " <<
// absolute_path << std::endl; exit(1);
return nullopt;
}
}
return buf.st_mtime;
}
void MoveFileTo(const std::string& dest, const std::string& source) {
// TODO/FIXME - do a real move.
CopyFileTo(dest, source);
}
// See http://stackoverflow.com/q/13198627
void CopyFileTo(const std::string& dest, const std::string& source) {
int fd_from = open(source.c_str(), O_RDONLY);
if (fd_from < 0)
return;
int fd_to = open(dest.c_str(), O_WRONLY | O_CREAT, 0666);
if (fd_to < 0)
goto out_error;
char buf[4096];
ssize_t nread;
while (nread = read(fd_from, buf, sizeof buf), nread > 0) {
char* out_ptr = buf;
ssize_t nwritten;
do {
nwritten = write(fd_to, out_ptr, nread);
if (nwritten >= 0) {
nread -= nwritten;
out_ptr += nwritten;
} else if (errno != EINTR)
goto out_error;
} while (nread > 0);
}
if (nread == 0) {
if (close(fd_to) < 0) {
fd_to = -1;
goto out_error;
}
close(fd_from);
return;
}
out_error:
close(fd_from);
if (fd_to >= 0)
close(fd_to);
}
bool IsSymLink(const std::string& path) {
struct stat buf;
int result;
result = lstat(path.c_str(), &buf);
return result == 0;
}
std::vector<std::string> GetPlatformClangArguments() {
return {};
}
#undef CHECKED
void FreeUnusedMemory() {
#if defined(__linux__)
malloc_trim(0);
#endif
}
#endif