Skip to content

Commit e4b400d

Browse files
committed
src: assert available memory can be calculated for max-old-space-size-percentage
Add validation to ensure that --max-old-space-size-percentage cannot be used when available memory cannot be calculated, preventing undefined behavior when memory detection fails. Also enhance test-process-constrained-memory.js to support testing in constrained environments where memory calculation may fail.
1 parent f7a2ba7 commit e4b400d

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

src/node_options.cc

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,11 @@ void PerIsolateOptions::HandleMaxOldSpaceSizePercentage(
138138
? constrained_memory
139139
: total_memory;
140140

141+
if (available_memory == 0) {
142+
errors->push_back("the available memory can not be calculated");
143+
return;
144+
}
145+
141146
// Convert to MB and calculate the percentage
142147
uint64_t memory_mb = available_memory / (1024 * 1024);
143148
uint64_t calculated_mb = static_cast<size_t>(memory_mb * percentage / 100.0);

test/parallel/test-max-old-space-size-percentage.js

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -119,14 +119,18 @@ assert(
119119

120120
// Validate heap sizes against system memory
121121
const totalMemoryMB = Math.floor(os.totalmem() / 1024 / 1024);
122-
const margin = 10; // 5% margin
122+
const uint64Max = 2 ** 64 - 1;
123+
const constrainedMemory = process.constrainedMemory();
124+
const constrainedMemoryMB = Math.floor(constrainedMemory / 1024 / 1024);
125+
const effectiveMemoryMB = constrainedMemory > 0 && constrainedMemory !== uint64Max ? constrainedMemoryMB : totalMemoryMB;
126+
const margin = 10; // 10% margin
123127
testPercentages.forEach((percentage) => {
124-
const upperLimit = totalMemoryMB * ((percentage + margin) / 100);
128+
const upperLimit = effectiveMemoryMB * ((percentage + margin) / 100);
125129
assert(
126130
heapSizes[percentage] <= upperLimit,
127131
`Heap size for ${percentage}% (${heapSizes[percentage]} MB) should not exceed upper limit (${upperLimit} MB)`
128132
);
129-
const lowerLimit = totalMemoryMB * ((percentage - margin) / 100);
133+
const lowerLimit = effectiveMemoryMB * ((percentage - margin) / 100);
130134
assert(
131135
heapSizes[percentage] >= lowerLimit,
132136
`Heap size for ${percentage}% (${heapSizes[percentage]} MB) should not be less than lower limit (${lowerLimit} MB)`

0 commit comments

Comments
 (0)