Hi,

I'm trying to investigate an out-of-memory issue in a WebWorker that uses a 
Emscripten compiled JS library.
For this, I would like to profile the memory usage / track memory 
allocations.
I checked out the memory profiler from: 
https://groups.google.com/forum/#!topic/emscripten-discuss/HtAzVposlX4.
It tries to hook into _malloc and _free by using a preRun callback.
However, this doesn't work anymore. Here is what it tries to do:

*Webworker script*
importScripts("memoryprofiler-webworker.js");
//...import Emscripten library through AMD loader...


*memoryprofiler-webworker.js*
//see https://groups.google.com/forum/#!topic/emscripten-discuss/HtAzVposlX4
function memoryprofiler_add_hooks(){
  var prevMalloc = _malloc;
  //wrap prevMalloc in hookedMalloc
  _malloc = hookedMalloc;
  Module['_malloc'] = hookedMalloc;
  //same with _free
}


*EmscriptenLibrary.js*
Module['preRun'] = [memoryprofiler_add_hooks];

The problem is that _malloc and _free are not in scope when entering the 
memoryprofiler_add_hooks function.

I've tried to pass the Module and asm objects to the 
memoryprofiler_add_hooks function:

*EmscriptenLibrary.js*
Module['preRun'] = [];
//...
//later on in the file, after asm object has been constructed (but before 
the call to run()):
Module['preRun'].push({func: memoryprofiler_add_hooks, arg: {Module: Module, 
asm: asm}});

*memoryprofiler-webworker.js*
function memoryprofiler_add_hooks(args) {
  var prevMalloc = args.asm._malloc;
  function hookedMalloc(size) {
    //.. track memory statistics etc. and delegate to prevMalloc
  }
  args.asm['_malloc'] = hookedMalloc;
  args.Module['_malloc'] = hookedMalloc;
  //same with free
}

This works as expected when you call asm._malloc or Module._malloc (or 
EmscriptenLibrary._malloc from the webworker). It is hookedMalloc that gets 
called instead of the asm _malloc. However, because compiled ASM code 
refers to _malloc from inside of the asm object, the original asm._malloc 
is still used by compiled ASM code.

*EmscriptenLibrary.js*
// EMSCRIPTEN_START_ASM
var asm = (function(global, env, buffer) {
  ...
  function _malloc($bytes) {
   ...
  }
  
  function compiled_library_function(){
   ...
   _malloc(...); //calls original _malloc, not hookedMalloc, no statistics 
are tracked
   ...
   }
}


My question is: Is there any way to hook _malloc or _free? Can I do it from 
an external JS with minimal modifications to Emscripten's output? Is it 
possible by other means (e.g. linking a JS library)? An Emscripten memory 
profiler would be great for developing Emscripten-based JS libraries.

Kind regards,
Glenn





-- 
You received this message because you are subscribed to the Google Groups 
"emscripten-discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
For more options, visit https://groups.google.com/d/optout.

Reply via email to