Skip to content

Commit 1f18166

Browse files
authored
fix memory leak when not setting data (#104)
1 parent 13fc1cd commit 1f18166

File tree

2 files changed

+10
-3
lines changed

2 files changed

+10
-3
lines changed

core/src/main/java/com/styra/opa/wasm/OpaPolicy.java

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,6 @@ public class OpaPolicy {
2929
private int dataHeapPtr = -1;
3030
private int dataAddr = -1;
3131
private int inputAddr = -1;
32-
private int resultAddr = -1;
3332
private int entrypoint;
3433

3534
private OpaPolicy(OpaWasm wasm) {
@@ -78,6 +77,10 @@ private String dumpJson(int addr) {
7877
// data MUST be a serializable object or ArrayBuffer, which assumed to be a well-formed
7978
// stringified JSON
8079
public OpaPolicy data(String data) {
80+
if (this.dataAddr != -1) {
81+
wasm.exports().opaValueFree(this.dataAddr);
82+
}
83+
8184
wasm.exports().opaHeapPtrSet(this.baseHeapPtr);
8285
this.dataAddr = loadJson(data);
8386
this.dataHeapPtr = wasm.exports().opaHeapPtrGet();
@@ -96,6 +99,9 @@ public OpaPolicy input(String input) {
9699
if (this.dataAddr == -1) {
97100
// to keep the ordering: data - input - evaluate
98101
data("");
102+
} else {
103+
// Reset the heap pointer before each evaluation
104+
wasm.exports().opaHeapPtrSet(this.dataHeapPtr);
99105
}
100106

101107
var inputLen = input.getBytes().length;
@@ -152,8 +158,9 @@ public String evaluate() {
152158
"Error evaluating the Opa Policy, returned code is: " + evalResult);
153159
}
154160

155-
this.resultAddr = wasm.exports().opaEvalCtxGetResult(ctxAddr);
161+
var resultAddr = wasm.exports().opaEvalCtxGetResult(ctxAddr);
156162
var result = dumpJson(resultAddr);
163+
wasm.exports().opaFree(resultAddr);
157164
return result;
158165
}
159166

core/src/test/java/com/styra/opa/wasm/MemoryTest.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ public void doesNotLeakMemoryEvaluatingTheSamePolicyMultipleTimes() {
6464
.withPolicy(wasmFile)
6565
.build();
6666
var input = new String(new char[2 * 65536]).replace("\0", "a");
67-
for (int i = 0; i < 16; i++) {
67+
for (int i = 0; i < 100000; i++) {
6868
assertDoesNotThrow(() -> policy.evaluate(input));
6969
}
7070
}

0 commit comments

Comments
 (0)