Skip to content

Commit

Permalink
Clear interop identity tracking ConditionalWeakTable in Engine.Dispose (
Browse files Browse the repository at this point in the history
  • Loading branch information
lahma committed Jan 18, 2023
1 parent 81cfbc0 commit 57d1429
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
18 changes: 15 additions & 3 deletions Jint/Engine.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Runtime.CompilerServices;
using Esprima;
using Esprima.Ast;
using Jint.Native;
Expand Down Expand Up @@ -53,7 +54,7 @@ public sealed partial class Engine : IDisposable
internal readonly Dictionary<string, Type?> TypeCache = new();

// cache for already wrapped CLR objects to keep object identity
internal readonly ConditionalWeakTable<object, ObjectInstance> _objectWrapperCache = new();
internal ConditionalWeakTable<object, ObjectInstance>? _objectWrapperCache;

internal readonly JintCallStack CallStack;

Expand Down Expand Up @@ -1426,7 +1427,18 @@ ObjectInstance Callback()

public void Dispose()
{
// no-op for now
if (_objectWrapperCache is null)
{
return;
}

#if NETSTANDARD2_1_OR_GREATER
_objectWrapperCache.Clear();
#else
// we can expect that reflection is OK as we've been generating object wrappers already
var clearMethod = _objectWrapperCache.GetType().GetMethod("Clear", BindingFlags.Instance | BindingFlags.NonPublic);
clearMethod?.Invoke(_objectWrapperCache, Array.Empty<object>());
#endif
}
}
}
5 changes: 4 additions & 1 deletion Jint/Runtime/Interop/DefaultObjectConverter.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Threading;
using Jint.Native;
using Jint.Native.Object;
using Jint.Runtime;
using Jint.Runtime.Interop;

Expand Down Expand Up @@ -101,7 +103,7 @@ public static bool TryConvert(Engine engine, object value, [NotNullWhen(true)] o
else
{
// check global cache, have we already wrapped the value?
if (engine._objectWrapperCache.TryGetValue(value, out var cached))
if (engine._objectWrapperCache?.TryGetValue(value, out var cached) == true)
{
result = cached;
}
Expand All @@ -112,6 +114,7 @@ public static bool TryConvert(Engine engine, object value, [NotNullWhen(true)] o

if (engine.Options.Interop.TrackObjectWrapperIdentity && wrapped is not null)
{
engine._objectWrapperCache ??= new ConditionalWeakTable<object, ObjectInstance>();
engine._objectWrapperCache.Add(value, wrapped);
}
}
Expand Down

0 comments on commit 57d1429

Please sign in to comment.