Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement support for the new memory allocation API #427

Merged
merged 2 commits into from
Dec 11, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
34 changes: 31 additions & 3 deletions wrapper.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,30 @@ function setupMethods (soljson) {
};
}

var alloc;
if ('_solidity_alloc' in soljson) {
alloc = soljson.cwrap('solidity_alloc', 'number', [ 'number' ]);
} else {
alloc = soljson._malloc;
axic marked this conversation as resolved.
Show resolved Hide resolved
assert(alloc, 'Expected malloc to be present.');
}

var reset;
if ('_solidity_reset' in soljson) {
reset = soljson.cwrap('solidity_reset', null, []);
}

var copyToCString = function (str, ptr) {
var length = soljson.lengthBytesUTF8(str);
// This is allocating memory using solc's allocator.
// Assuming copyToCString is only used in the context of wrapCallback, solc will free these pointers.
// See https://github.com/ethereum/solidity/blob/v0.5.13/libsolc/libsolc.h#L37-L40
var buffer = soljson._malloc(length + 1);
//
// Before 0.6.0:
// Assuming copyToCString is only used in the context of wrapCallback, solc will free these pointers.
// See https://github.com/ethereum/solidity/blob/v0.5.13/libsolc/libsolc.h#L37-L40
//
// After 0.6.0:
// The duty is on solc-js to free these pointers. We accomplish that by calling `reset` at the end.
var buffer = alloc(length + 1);
soljson.stringToUTF8(str, buffer, length + 1);
soljson.setValue(ptr, buffer, '*');
};
Expand All @@ -61,6 +79,8 @@ function setupMethods (soljson) {
var wrapCallbackWithKind = function (callback) {
assert(typeof callback === 'function', 'Invalid callback specified.');
return function (context, kind, data, contents, error) {
// Must be a null pointer.
axic marked this conversation as resolved.
Show resolved Hide resolved
assert(context === 0, 'Callback context must be null.');
var result = callback(copyFromCString(kind), copyFromCString(data));
if (typeof result.contents === 'string') {
copyToCString(result.contents, contents);
Expand Down Expand Up @@ -134,6 +154,14 @@ function setupMethods (soljson) {
throw e;
}
removeFunction(cb);
if (reset) {
// Explicitly free memory.
//
// NOTE: cwrap() of "compile" will copy the returned pointer into a
// Javascript string and it is not possible to call free() on it.
// reset() however will clear up all allocations.
reset();
}
return output;
};

Expand Down