2023-10-20 10:16:19 +03:00
|
|
|
// Many build systems attempt to invoke as many linker processes as there
|
|
|
|
// are cores, based on the assumption that the linker is single-threaded.
|
|
|
|
// However, since mold is multi-threaded, such build systems' behavior is
|
|
|
|
// not beneficial and just increases the overall peak memory usage.
|
|
|
|
// On machines with limited memory, this could lead to an out-of-memory
|
|
|
|
// error.
|
|
|
|
//
|
|
|
|
// This file implements a feature that limits the number of concurrent
|
|
|
|
// mold processes to just 1 for each user. It is intended to be used as
|
|
|
|
// `MOLD_JOBS=1 ninja` or `MOLD_JOBS=1 make -j$(nproc)`.
|
|
|
|
|
2024-03-18 09:30:13 +03:00
|
|
|
#include "common.h"
|
2023-03-17 09:32:12 +03:00
|
|
|
|
2024-03-18 09:30:13 +03:00
|
|
|
#include <fcntl.h>
|
|
|
|
#include <pwd.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
#include <sys/stat.h>
|
|
|
|
#include <sys/types.h>
|
|
|
|
#include <unistd.h>
|
2023-03-17 09:32:12 +03:00
|
|
|
|
2024-03-18 09:30:13 +03:00
|
|
|
namespace mold {
|
2023-03-17 09:32:12 +03:00
|
|
|
|
2024-03-18 09:30:13 +03:00
|
|
|
static int lock_fd = -1;
|
|
|
|
|
|
|
|
void acquire_global_lock() {
|
2024-07-11 07:34:08 +03:00
|
|
|
char *jobs = getenv("MOLD_JOBS");
|
|
|
|
if (!jobs || jobs != "1"s)
|
2023-03-17 09:32:12 +03:00
|
|
|
return;
|
|
|
|
|
2023-10-22 07:28:13 +03:00
|
|
|
std::string path;
|
|
|
|
if (char *dir = getenv("XDG_RUNTIME_DIR"))
|
2024-07-11 07:34:08 +03:00
|
|
|
path = dir + "/mold-lock"s;
|
2023-10-22 07:28:13 +03:00
|
|
|
else
|
2024-07-11 07:34:08 +03:00
|
|
|
path = "/tmp/mold-lock-"s + getpwuid(getuid())->pw_name;
|
2023-03-17 09:32:12 +03:00
|
|
|
|
2024-07-11 07:34:08 +03:00
|
|
|
int fd = open(path.c_str(), O_WRONLY | O_CREAT | O_CLOEXEC, 0600);
|
|
|
|
if (fd == -1)
|
2023-03-17 09:32:12 +03:00
|
|
|
return;
|
|
|
|
|
2024-07-11 07:34:08 +03:00
|
|
|
if (lockf(fd, F_LOCK, 0) == -1)
|
|
|
|
return;
|
|
|
|
lock_fd = fd;
|
2023-03-17 09:32:12 +03:00
|
|
|
}
|
|
|
|
|
2024-03-18 09:30:13 +03:00
|
|
|
void release_global_lock() {
|
2024-07-11 07:34:08 +03:00
|
|
|
if (lock_fd != -1)
|
|
|
|
close(lock_fd);
|
2023-03-17 09:32:12 +03:00
|
|
|
}
|
|
|
|
|
2024-03-18 09:30:13 +03:00
|
|
|
} // namespace mold
|