1
1
Fork 0
mirror of https://github.com/NixOS/nix.git synced 2025-11-16 07:22:43 +01:00

Fix thread-safety issue with ptsname() usage

Replace non-thread-safe ptsname() calls with a new getPtsName() helper
function that:
- Uses thread-safe ptsname_r() on Linux/BSD platforms
- Uses mutex-protected ptsname() on macOS (which lacks ptsname_r())
This commit is contained in:
Jörg Thalheim 2025-09-29 12:01:45 +02:00
parent 7cbc0f97e7
commit a9ffa42dda
3 changed files with 39 additions and 3 deletions

View file

@ -1,6 +1,7 @@
#include "nix/util/terminal.hh"
#include "nix/util/environment-variables.hh"
#include "nix/util/sync.hh"
#include "nix/util/error.hh"
#ifdef _WIN32
# include <io.h>
@ -12,6 +13,8 @@
#endif
#include <unistd.h>
#include <widechar_width.h>
#include <mutex>
#include <cstdlib> // for ptsname and ptsname_r
namespace {
@ -176,4 +179,29 @@ std::pair<unsigned short, unsigned short> getWindowSize()
return *windowSize.lock();
}
std::string getPtsName(int fd)
{
#ifdef __APPLE__
static std::mutex ptsnameMutex;
// macOS doesn't have ptsname_r, use mutex-protected ptsname
std::lock_guard<std::mutex> lock(ptsnameMutex);
const char * name = ptsname(fd);
if (!name) {
throw SysError("getting pseudoterminal slave name");
}
return name;
#else
// Use thread-safe ptsname_r on platforms that support it
// PTY names are typically short:
// - Linux: /dev/pts/N (where N is usually < 1000)
// - FreeBSD: /dev/pts/N
// 64 bytes is more than sufficient for any Unix PTY name
char buf[64];
if (ptsname_r(fd, buf, sizeof(buf)) != 0) {
throw SysError("getting pseudoterminal slave name");
}
return buf;
#endif
}
} // namespace nix