Skip to content

Conversation

@drivehappy
Copy link

The Visual Studio debugger was reporting that there was heap corruption when attempting to call Marshal.FreeHGlobal. It appears that this uses a different heap than what the native side uses for allocation with malloc. To ensure that the same heap is used, a new export from zopfli.dll was added (ZopfliFree) to perform the companion free call - and the managed side now calls into this.

Since I couldn't find the original (assumed modified) sources for the zopfli.dll, I had to re-implement the ZopfliPNGExternalOptimize exported function as well to ensure the PNG compression still worked. For future reference, the implementations are:

int ZopfliPNGExternalOptimize(const unsigned char* datain, int datainsize, unsigned char** dataout) {
	ZopfliPNGOptions opts;

	const std::vector<unsigned char> origpng_cc(datain, datain + datainsize);
	std::vector<unsigned char> resultpng_cc;

	int ret = ZopfliPNGOptimize(origpng_cc, opts, false, &resultpng_cc);
	if (ret) {
		return ret;
	}

	int size = static_cast<int>(resultpng_cc.size());
	*dataout = (unsigned char*)malloc(resultpng_cc.size());
	if (!(*dataout)) {
		return ENOMEM;
	}

	memcpy(*dataout,
		reinterpret_cast<unsigned char*>(&resultpng_cc[0]),
		resultpng_cc.size());

	return size;
}

and,

void ZopfliFree(void* mem) {
	free(mem);
}

I used the Zopfli sources from the 1.0.2 release and I rebuilt the DLL binaries in Release under VS 15.7.1, and statically linked the runtime into it.

…m the wrong heap. Since we need access to 'free', a new export was created from the zopfli.dll to perform this cleanup from the same heap the memory was allocated from with 'malloc'.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant