Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 22 additions & 8 deletions src/passes/SafeHeap.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
namespace wasm {

const Name DYNAMICTOP_PTR_IMPORT("DYNAMICTOP_PTR");
const Name GET_SBRK_PTR_IMPORT("emscripten_get_sbrk_ptr");
const Name SEGFAULT_IMPORT("segfault");
const Name ALIGNFAULT_IMPORT("alignfault");

Expand Down Expand Up @@ -111,19 +112,27 @@ struct SafeHeap : public Pass {
addGlobals(module, module->features);
}

Name dynamicTopPtr, segfault, alignfault;
Name dynamicTopPtr, getSbrkPtr, segfault, alignfault;

void addImports(Module* module) {
ImportInfo info(*module);
// Older emscripten imports env.DYNAMICTOP_PTR.
// Newer emscripten imports emscripten_get_sbrk_ptr(), which is later
// optimized to have the number in the binary.
if (auto* existing = info.getImportedGlobal(ENV, DYNAMICTOP_PTR_IMPORT)) {
dynamicTopPtr = existing->name;
} else if (auto* existing =
info.getImportedFunction(ENV, GET_SBRK_PTR_IMPORT)) {
getSbrkPtr = existing->name;
} else {
auto* import = new Global;
import->name = dynamicTopPtr = DYNAMICTOP_PTR_IMPORT;
auto* import = new Function;
import->name = getSbrkPtr = GET_SBRK_PTR_IMPORT;
import->module = ENV;
import->base = DYNAMICTOP_PTR_IMPORT;
import->type = i32;
module->addGlobal(import);
import->base = GET_SBRK_PTR_IMPORT;
auto* functionType = ensureFunctionType("i", module);
import->type = functionType->name;
FunctionTypeUtils::fillFunction(import, functionType);
module->addFunction(import);
}
if (auto* existing = info.getImportedFunction(ENV, SEGFAULT_IMPORT)) {
segfault = existing->name;
Expand Down Expand Up @@ -315,6 +324,12 @@ struct SafeHeap : public Pass {
makeBoundsCheck(Type type, Builder& builder, Index local, Index bytes) {
auto upperOp = options.lowMemoryUnused ? LtUInt32 : EqInt32;
auto upperBound = options.lowMemoryUnused ? PassOptions::LowMemoryBound : 0;
Expression* sbrkPtr;
if (dynamicTopPtr.is()) {
sbrkPtr = builder.makeGlobalGet(dynamicTopPtr, i32);
} else {
sbrkPtr = builder.makeCall(getSbrkPtr, {}, i32);
}
return builder.makeIf(
builder.makeBinary(
OrInt32,
Expand All @@ -326,8 +341,7 @@ struct SafeHeap : public Pass {
builder.makeBinary(AddInt32,
builder.makeLocalGet(local, i32),
builder.makeConst(Literal(int32_t(bytes)))),
builder.makeLoad(
4, false, 0, 4, builder.makeGlobalGet(dynamicTopPtr, i32), i32))),
builder.makeLoad(4, false, 0, 4, sbrkPtr, i32))),
builder.makeCall(segfault, {}, none));
}
};
Expand Down
Loading