Skip to content

WebIDL binder: Use WeakRefs in cache #9854

Open

Description

@kripken

The cache maps C pointers (integers) to JS object wrappers. It
currently keeps objects alive forever. This is normally ok as the
objects should be manually destroy()ed, however, we do allow
wrapping a class as a parent class, and then it ends up in
multiple caches, see kripken/ammo.js#284

Using WeakRefs where available could avoid this. However, until
they are present everywhere, perhaps we could analyze the
inheritance graph and clean up parent caches too, but that may
be tricky especially with multiple/virtual/etc. inheritance.

Activity

  1. stale commented on Nov 19, 2020

    @stale

    This issue has been automatically marked as stale because there has been no activity in the past year. It will be closed automatically if no further activity occurs in the next 30 days. Feel free to re-open at any time if this issue is still relevant.

  2. stale commented on Apr 17, 2022

    @stale

    This issue has been automatically marked as stale because there has been no activity in the past year. It will be closed automatically if no further activity occurs in the next 30 days. Feel free to re-open at any time if this issue is still relevant.

  3. kripken commented on Jan 28, 2025

    @kripken
    MemberAuthor

    WeakRefs are not enough here, as we want to clear out the cache entry, but a finalization callback could work:

    diff --git a/tools/webidl_binder.py b/tools/webidl_binder.py
    index 2e54f792d..7452a03e3 100644
    --- a/tools/webidl_binder.py
    +++ b/tools/webidl_binder.py
    @@ -132,6 +132,11 @@ function WrapperObject() {
     
     mid_js += build_constructor('WrapperObject')
     
    +# Wrapper caching. Caching ensures a 1:1 relationship of wrappers to C++
    +# objects, ensuring object equality works, and avoiding inefficient allocations.
    +# We use finalizer callbacks here to clean up the cache (without them, long-
    +# running programs that wrap emphemeral C++ objects can end up with lots of
    +# cached wrappers for dead objects, and C++ does not inform us of their demise).
     mid_js += ['''
     /** @suppress {duplicate} (TODO: avoid emitting this multiple times, it is redundant)
         @param {*=} __class__ */
    @@ -147,6 +152,14 @@ function wrapPointer(ptr, __class__) {
       var ret = cache[ptr];
       if (ret) return ret;
       ret = Object.create((__class__ || WrapperObject).prototype);
    +  if (typeof FinalizationRegistry !== 'undefined') {
    +    if (!cache.registry) {
    +      cache.registry = new FinalizationRegistry((ptr) => {
    +        delete cache[ptr];
    +      });
    +    }
    +    cache.registry.register(ret, ptr);
    +  }
       ret.ptr = ptr;
       return cache[ptr] = ret;
     }

    Testing this will take some work, however. I can try to get to that eventually, but posting this diff here now in case someone wants to take this forward.

  4. kripken commented on Jan 28, 2025

    @kripken
    MemberAuthor

    Note that FinalizationRegistry is supported in our default browser versions now, which is nice (but not the oldest versions we optionally support).

  5. FlorentMasson commented on Jan 30, 2025

    @FlorentMasson

    It doesn't appear to be working. I set a breakpoint on the FinalizationRegistry callback, but it's never called.
    I don't think it will ever be called if the cache retains a (non-weak) reference to the object.

  6. kripken commented on Jan 30, 2025

    @kripken
    MemberAuthor

    Thanks, good point. The patch should store new WeakRef(ref) in the cache, and we should .deref() on reads from the cache. It looks like there is more than one place that does reads and writes to the cache, but it shouldn't be hard - maybe we could refactor that first. Anyhow, as I wrote above I can try to get to it eventually but if someone else has time and interest now, that would be great.

  7. FlorentMasson commented on Feb 4, 2025

    @FlorentMasson

    Here's the patch I'm testing.
    I do not really understand the code in render_function() but that felt logical

    index 2e54f79..9d2871b 100644
    --- a/webidl_binder.py
    +++ b/webidl_binder.py
    @@ -132,6 +132,11 @@ function WrapperObject() {
    
     mid_js += build_constructor('WrapperObject')
    
    +# Wrapper caching. Caching ensures a 1:1 relationship of wrappers to C++
    +# objects, ensuring object equality works, and avoiding inefficient allocations.
    +# We use finalizer callbacks here to clean up the cache (without them, long-
    +# running programs that wrap emphemeral C++ objects can end up with lots of
    +# cached wrappers for dead objects, and C++ does not inform us of their demise).
     mid_js += ['''
     /** @suppress {duplicate} (TODO: avoid emitting this multiple times, it is redundant)
         @param {*=} __class__ */
    @@ -145,10 +150,20 @@ Module['getCache'] = getCache;
     function wrapPointer(ptr, __class__) {
       var cache = getCache(__class__);
       var ret = cache[ptr];
    +  if (ret) ret = ret.deref();
       if (ret) return ret;
       ret = Object.create((__class__ || WrapperObject).prototype);
    +  if (typeof FinalizationRegistry !== 'undefined') {
    +  if (!cache.registry) {
    +      cache.registry = new FinalizationRegistry((ptr) => {
    +        delete cache[ptr];
    +      });
    +    }
    +    cache.registry.register(ret, ptr);
    +  }
       ret.ptr = ptr;
    -  return cache[ptr] = ret;
    +  cache[ptr] = new WeakRef(ret);
    +  return ret;
     }
     Module['wrapPointer'] = wrapPointer;
    
    @@ -417,7 +432,7 @@ def render_function(class_name, func_name, sigs, return_type, non_pointer,  # no
    
       # JS
    
    -  cache = ('getCache(%s)[this.ptr] = this;' % class_name) if constructor else ''
    +  cache = ('getCache(%s)[this.ptr] = new WeakRef(this);' % class_name) if constructor else ''
       call_prefix = ''
       if constructor:
         call_prefix += 'this.ptr = '
    @@ -660,7 +675,7 @@ def render_function(class_name, func_name, sigs, return_type, non_pointer,  # no
    
             js_impl_methods.append(r'''  %s %s(%s) %s {
         %s (%s) %s({
    -      var self = Module['getCache'](Module['%s'])[$0];
    +      var self = Module['getCache'](Module['%s'])[$0].deref();
           if (!self.hasOwnProperty('%s')) throw 'a JSImplementation must implement all functions, you forgot %s::%s.';
           %sself['%s'](%s)%s;
         }, (ptrdiff_t)this%s);
    
    
  8. FlorentMasson commented on Sep 23, 2026

    @FlorentMasson

    So the patch above has been running since I posted in production for me.
    Here's a new version for the patch, also cleaning the cache from the entire hierarchy.

    --- a/tools/webidl_binder.py
    +++ b/tools/webidl_binder.py
    @@ -114,12 +114,15 @@
     
     def build_constructor(name):
       implementing_name = implements[name][0] if implements.get(name) else 'WrapperObject'
    +  # Classes are emitted parents first (see nodeHeight), so the parent's __subclasses__ already exists.
    +  register = '{implementing}.__subclasses__.push({name});\n'.format(name=name, implementing=implementing_name) if implements.get(name) else ''
       return [r'''{name}.prototype = Object.create({implementing}.prototype);
     {name}.prototype.constructor = {name};
     {name}.prototype.__class__ = {name};
     {name}.__cache__ = {{}};
    -Module['{name}'] = {name};
    -'''.format(name=name, implementing=implementing_name)]
    +{name}.__subclasses__ = [];
    +{register}Module['{name}'] = {name};
    +'''.format(name=name, implementing=implementing_name, register=register)]
     
     
     mid_js = ['''
    @@ -132,6 +135,11 @@
     
     mid_js += build_constructor('WrapperObject')
     
    +# Wrapper caching. Caching ensures a 1:1 relationship of wrappers to C++
    +# objects, ensuring object equality works, and avoiding inefficient allocations.
    +# We use finalizer callbacks here to clean up the cache (without them, long-
    +# running programs that wrap emphemeral C++ objects can end up with lots of
    +# cached wrappers for dead objects, and C++ does not inform us of their demise).
     mid_js += ['''
     /** @suppress {duplicate} (TODO: avoid emitting this multiple times, it is redundant)
         @param {*=} __class__ */
    @@ -145,10 +153,22 @@
     function wrapPointer(ptr, __class__) {
       var cache = getCache(__class__);
       var ret = cache[ptr];
    +  if (ret) ret = ret.deref();
       if (ret) return ret;
       ret = Object.create((__class__ || WrapperObject).prototype);
    +  if (typeof FinalizationRegistry !== 'undefined') {
    +    if (!cache.registry) {
    +      cache.registry = new FinalizationRegistry((ptr) => {
    +        // a newer wrapper may have been cached for this pointer after this one was collected
    +        var ref = cache[ptr];
    +        if (ref && !ref.deref()) delete cache[ptr];
    +      });
    +    }
    +    cache.registry.register(ret, ptr);
    +  }
       ret.ptr = ptr;
    -  return cache[ptr] = ret;
    +  cache[ptr] = new WeakRef(ret);
    +  return ret;
     }
     Module['wrapPointer'] = wrapPointer;
     
    @@ -161,11 +181,24 @@
     Module['NULL'] = wrapPointer(0);
     
     /** @suppress {duplicate} (TODO: avoid emitting this multiple times, it is redundant) */
    +function uncacheHierarchy(__class__, ptr) {
    +  delete __class__.__cache__[ptr];
    +  for (var i = 0; i < __class__.__subclasses__.length; i++)
    +    uncacheHierarchy(__class__.__subclasses__[i], ptr);
    +}
    +
    +/** @suppress {duplicate} (TODO: avoid emitting this multiple times, it is redundant) */
     function destroy(obj) {
       if (!obj['__destroy__']) throw 'Error: Cannot destroy object. (Did you create it yourself?)';
       obj['__destroy__']();
    -  // Remove from cache, so the object can be GC'd and refs added onto it released
    -  delete getCache(obj.__class__)[obj.ptr];
    +  // Remove from cache, so the object can be GC'd and refs added onto it released.
    +  // The pointer may also be cached under a parent, child or sibling class (castObject, upcast, getters),
    +  // where a stale wrapper would be returned for the next object allocated at this address:
    +  // clear it from every class of the hierarchy.
    +  var root = obj.__class__, parent;
    +  while ((parent = Object.getPrototypeOf(root.prototype).__class__) && parent !== WrapperObject)
    +    root = parent;
    +  uncacheHierarchy(root, obj.ptr);
     }
     Module['destroy'] = destroy;
     
    @@ -417,7 +450,7 @@
     
       # JS
     
    -  cache = ('getCache(%s)[this.ptr] = this;' % class_name) if constructor else ''
    +  cache = ('getCache(%s)[this.ptr] = new WeakRef(this);' % class_name) if constructor else ''
       call_prefix = ''
       if constructor:
         call_prefix += 'this.ptr = '
    @@ -660,7 +693,7 @@
     
             js_impl_methods.append(r'''  %s %s(%s) %s {
         %s (%s) %s({
    -      var self = Module['getCache'](Module['%s'])[$0];
    +      var self = Module['getCache'](Module['%s'])[$0].deref();
           if (!self.hasOwnProperty('%s')) throw 'a JSImplementation must implement all functions, you forgot %s::%s.';
           %sself['%s'](%s)%s;
         }, (ptrdiff_t)this%s);

    With this patch, there are still situations where wrapper objects would not be erased and could be reused:

    1. object destroyed inside C++ (not created in JS), typically btPersistentManifold
    2. members of an object, for instance m_worldTransform inside btCollisionObject. If you add properties to the m_wordlTransform's wrapper of a body, then free the body and reallocate a new one immediately, the returned m_wordlTransform's wrapper would be the old one.
      The fix for second one would be to scan the freed range and remove wrappers from all caches, which would probably be costly 😓.
      No idea for the first 1...
  9. sbc100 commented on Sep 23, 2026

    @sbc100
    Collaborator

    Would you consider this patch ready to land upstream (here)? Maybe you could send it in the form of a PR?

  10. FlorentMasson commented on Sep 23, 2026

    @FlorentMasson

    It's still untested in real conditions and my own repo has diverged... a lot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions