Skip to content

Commit 906adad

Browse files
committed
Restore stack size in child processes
Fixes #4673.
1 parent 9b9e703 commit 906adad

File tree

3 files changed

+32
-12
lines changed

3 files changed

+32
-12
lines changed

src/libutil/util.cc

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232

3333
#ifdef __linux__
3434
#include <sys/prctl.h>
35+
#include <sys/resource.h>
3536
#endif
3637

3738

@@ -1618,11 +1619,37 @@ static void restoreSignals()
16181619
throw SysError("restoring signals");
16191620
}
16201621

1622+
#if __linux__
1623+
rlim_t savedStackSize = 0;
1624+
#endif
1625+
1626+
void setStackSize(size_t stackSize)
1627+
{
1628+
#if __linux__
1629+
struct rlimit limit;
1630+
if (getrlimit(RLIMIT_STACK, &limit) == 0 && limit.rlim_cur < stackSize) {
1631+
savedStackSize = limit.rlim_cur;
1632+
limit.rlim_cur = stackSize;
1633+
setrlimit(RLIMIT_STACK, &limit);
1634+
}
1635+
#endif
1636+
}
1637+
16211638
void restoreProcessContext()
16221639
{
16231640
restoreSignals();
16241641

16251642
restoreAffinity();
1643+
1644+
#if __linux__
1645+
if (savedStackSize) {
1646+
struct rlimit limit;
1647+
if (getrlimit(RLIMIT_STACK, &limit) == 0) {
1648+
limit.rlim_cur = savedStackSize;
1649+
setrlimit(RLIMIT_STACK, &limit);
1650+
}
1651+
}
1652+
#endif
16261653
}
16271654

16281655
/* RAII helper to automatically deregister a callback. */

src/libutil/util.hh

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,10 @@ std::pair<int, std::string> runProgram(const RunOptions & options);
300300
void runProgram2(const RunOptions & options);
301301

302302

303+
/* Change the stack size. */
304+
void setStackSize(size_t stackSize);
305+
306+
303307
/* Restore the original inherited Unix process context (such as signal
304308
masks, stack size, CPU affinity). */
305309
void restoreProcessContext();

src/nix/main.cc

Lines changed: 1 addition & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,6 @@
1717
#include <netdb.h>
1818
#include <netinet/in.h>
1919

20-
#if __linux__
21-
#include <sys/resource.h>
22-
#endif
23-
2420
#include <nlohmann/json.hpp>
2521

2622
extern std::string chrootHelperName;
@@ -335,14 +331,7 @@ int main(int argc, char * * argv)
335331
{
336332
// Increase the default stack size for the evaluator and for
337333
// libstdc++'s std::regex.
338-
#if __linux__
339-
rlim_t stackSize = 64 * 1024 * 1024;
340-
struct rlimit limit;
341-
if (getrlimit(RLIMIT_STACK, &limit) == 0 && limit.rlim_cur < stackSize) {
342-
limit.rlim_cur = stackSize;
343-
setrlimit(RLIMIT_STACK, &limit);
344-
}
345-
#endif
334+
nix::setStackSize(64 * 1024 * 1024);
346335

347336
return nix::handleExceptions(argv[0], [&]() {
348337
nix::mainWrapped(argc, argv);

0 commit comments

Comments
 (0)