runtime icon indicating copy to clipboard operation
runtime copied to clipboard

AssemblyLoadContext Unload does not release assembly lock on Windows

Open uffebjorklund opened this issue 7 years ago • 26 comments

This is a question about how things are supposed to work, but if my suspicion is right I will file a sample project where I reproduce the issue I am experiencing.

Background

I have a project that downloads zip files with assemblies. These assemblies are then loaded into a custom assembly load context. Later on the ALC will be unloaded and then the Unloading event fires (and all assemblies loaded will be unloaded).

I see no increase in memory when repeating this scenario so I guess that the assemblies are unloaded. A weird thing (not important here) is that the global tool dotnet-counters never decrease the number of assemblies loaded. The count increases for every time I create a new ALC, I thought that unloading would make the count decrease.

The Issue

When the Unloading of a ALC is completed my assumption was that the assemblies would be released/unlocked on windows so that I actually can remove them form the file system. However, this is not the case. If assemblies can be unloaded it would make sense to also let us delete the plugins since we might update the plugins later on and on windows we get exceptions since we cant delete the locked assemblies loaded by the ALC even though the ALC is long gone and the assemblies unloaded from dotnet core.

The be more specific the assemblies are written to a shared docker volume, since we want to persist these assemblies between if the container restarts.

Workaround

I have solved this temporary by only storing a zip with the actual assemblies in the shared volume, and then I load the assemblies inside the container so that windows cant lock them. However, this will probably not work when we later on will use windows containers since my guess is that they will be locked inside the container by windows then.

Environment

Host: Win10 Enterprise 1903 Docker Desktop Base Image: mcr.microsoft.com/dotnet/core/runtime-deps:3.0-alpine Application: dotnet core 3 preview9

The issue only occurs when running containers on windows (Mac/Linux works just fine).

uffebjorklund avatar Sep 06 '19 14:09 uffebjorklund

Im starting to think that this might be something within our application. Will try to reproduce in a simple example. I added WeakReference and it stays alive for ever in our application, so I guess we have some reference to the ALC that we to not dispose of in a correct way.

Will update this issue and hopefully close it if I get a simple example to work as expected.

uffebjorklund avatar Sep 09 '19 06:09 uffebjorklund

@uffebjorklund you should be able to delete the assemblies if the unload succeeded, so it seems there is really some issue blocking the unloading. The following article I have written in the past may help you to debug your issue: https://docs.microsoft.com/en-us/dotnet/standard/assembly/unloadability-howto

janvorli avatar Sep 09 '19 08:09 janvorli

@janvorli thanks! I found that article this weekend, it made me think that we have another issue. My guess is that we have to change the way we use the ALC. Today we have a few services injected into our custom ALC. Guessing that we cant do it that way since all examples I can find showing unloading use ALC in a more isolated way than we do.

uffebjorklund avatar Sep 09 '19 10:09 uffebjorklund

Managed to create a simpler ALC and successfully unloaded assemblies. Did not try it on windows yet, but I saw that the number of loaded assemblies decreased in dotnet-counters.

Will close this and hopefully get everything working on windows as well.

uffebjorklund avatar Sep 11 '19 16:09 uffebjorklund

Hi, I'm not sure if it's a good idea to comment on a closed topic, but it seemed a better idea than to create a duplicate.

Similar to @uffebjorklund I'm struggling with the actual releasing of the DLL-files so they can be deleted after unloading.

My code is based on the article @janvorli mentioned earlier in this thread ( https://docs.microsoft.com/en-us/dotnet/standard/assembly/unloadability ) and when debugging in VS2019 I can see in the 'Modules' window that the assemblies are in fact unloaded nicely. But, when I try to delete the DLL (after verifying in the modules window that it has been unloaded) I still get the 'File in use' message from Windows Explorer. Unlike VS2019, SysInternals ProcessExplorer does show that the module is still loaded.

Just for testing purposes, I added a destructor in the plugin and it is indeed called when the GC kicks in, which means (in my understanding) that there is nothing that keeps this instance from being disposed of.

I tried the troubleshooting sequence with WinDbg as described in the mentioned article but the '!dumpheap -type ...' command doesn't list any of my plugin types, indicating that they are indeed unloaded?

So, it seems that the assemblies are loaded and unloaded just fine, but somehow somewhere there's something that keeps a lock to the assembly DLL-files.

I'm experiencing this on: Windows 10 Pro 2004 VS2019 Version 16.8.0 Preview 1.0 .Net 5.0 Preview 7

Cheers, Richard

rkuiper1 avatar Aug 14 '20 09:08 rkuiper1

@rkuiper1, can you share a minimal version of your stuff that reproduces the issue? I also have a couple of questions / suggestions:

  • When you ran the !dumpheap -type LoaderAllocator, did it dump anything?
  • Can you try to modify the code to return a WeakReference for the loaded plugin Assembly in addition to the WeakReference to the AssemblyLoadContext and then spin in the loop with GC.Collect until both weak references become invalid?

janvorli avatar Aug 14 '20 10:08 janvorli

@janvorli ,

This is the output from !dumpheap -type LoaderAllocator

0:020> !dumpheap -type LoaderAllocator
         Address               MT     Size
000001fbd86f90e8 00007ff83548ca28       24     

Statistics:
              MT    Count    TotalSize Class Name
00007ff83548ca28        1           24 System.Reflection.LoaderAllocatorScout
Total 1 objects

My code already uses the WeakReference to the ALC to check if it has unloaded successfully (which it does) using the GC.Collect() loop. I'm not currently using a WeakReference for the assembly, so I will try to implement that first to see if that makes a difference. I will let you know. If it's still the same, I will prepare this minimal version of my 'production' code asap.

Thanks

rkuiper1 avatar Aug 14 '20 10:08 rkuiper1

@janvorli , Preliminary results of adding the WeakReference for the assembly show that after a few spins both the WeakReference for the alc and the assembly the IsAlive property is false. This is the loop:

GC.WaitForPendingFinalizers();
int i = 0;
while ((hostAlcWeakRef.IsAlive || asmWeakRef.IsAlive) && i++ < 10)
{
	GC.Collect();
	GC.WaitForPendingFinalizers();
}

Of course I need to actually instantiate and use the assembly reference, so I used the asmWeakRef.Target. I also tried the WeakReference<T> variant because the Finalize() method looked promising, but that method only seems to exist in the documentation.

I will continue to extract the code into a minimal sample solution .

Cheers

rkuiper1 avatar Aug 14 '20 11:08 rkuiper1

TestCollectibleLoadContext.zip @janvorli , Here's the minimal solution that reproduces the behavior. The solution consists of 3 projects:

  • PluginHost
  • Interfaces
  • Plugin

The purpose of this test program is to load a plugin, retrieve the 'header info', unload the plugin and display the header info. The console program will wait for Console.ReadLine() and at that point the Plugin should be unloaded and the dll-file should be released so it can be removed. The observed behavior is that the plugin is indeed unloaded according to the Modules debug window in VS2019, but the file remains locked. I hope I'm doing something wrong. If you need more information or have any other questions, please let me know.

Thanks

rkuiper1 avatar Aug 14 '20 13:08 rkuiper1

@rkuiper1 thank you for the repro, I'll try it locally and get back to you after.

janvorli avatar Aug 14 '20 14:08 janvorli

@rkuiper1 Your example works as expected for me when executed from the command line using the dotnet tool: From the root of your sample:

dotnet build
dotnet run --project PluginHost\PluginHost.csproj

I was able to rename or delete the plugin dll just fine when the test app was waiting in the ReadLine. So I assume that the problem when debugging under VS is that the reference is being held by the Visual Studio debugger.

janvorli avatar Aug 14 '20 14:08 janvorli

@janvorli , Ok... that's strange. I never (consciously) use the dotnet cli, but for testing purposes I just did exactly what you did (after first removing all existing binaries of course).

D:\Projects\.NET5\TestCollectibleLoadContext>dotnet build
Microsoft (R) Build Engine version 16.7.0-preview-20360-03+188921e2f for .NET
Copyright (C) Microsoft Corporation. All rights reserved.

  Determining projects to restore...
  All projects are up-to-date for restore.
  You are using a preview version of .NET. See: https://aka.ms/dotnet-core-preview
  You are using a preview version of .NET. See: https://aka.ms/dotnet-core-preview
  You are using a preview version of .NET. See: https://aka.ms/dotnet-core-preview
  Interfaces -> D:\Projects\.NET5\TestCollectibleLoadContext\Interfaces\bin\Debug\net5.0\Interfaces.dll
  Plugin -> D:\Projects\.NET5\TestCollectibleLoadContext\Plugin\bin\Debug\net5.0\Plugin.dll
CollectibleLoadContext.cs(10,47): warning CS0169: The field 'CollectibleLoadContext._resolver' is never used [D:\Projects\.NET5\TestCollectibleLoadContext\PluginHost\PluginHost.csproj]
  PluginHost -> D:\Projects\.NET5\TestCollectibleLoadContext\PluginHost\bin\Debug\net5.0\PluginHost.dll

Build succeeded.

CollectibleLoadContext.cs(10,47): warning CS0169: The field 'CollectibleLoadContext._resolver' is never used [D:\Projects\.NET5\TestCollectibleLoadContext\PluginHost\PluginHost.csproj]
    1 Warning(s)
    0 Error(s)

Time Elapsed 00:00:03.70

D:\Projects\.NET5\TestCollectibleLoadContext>dotnet run --project PluginHost\PluginHost.csproj
ID: 1a204a34-2429-43d7-86f0-e4b6e5ee2777
Name: PluginName
Description: Test plugin
Version: 1.0.0

At this point the program is waiting for the ReadLine.

In another console window I tried to delete the plugin:

D:\Projects\.NET5\TestCollectibleLoadContext\Plugin\bin\Debug\net5.0>del Plugin.dll
D:\Projects\.NET5\TestCollectibleLoadContext\Plugin\bin\Debug\net5.0\Plugin.dll
Access is denied.

D:\Projects\.NET5\TestCollectibleLoadContext\Plugin\bin\Debug\net5.0>

After I pressed enter in the first console window I get this:

D:\Projects\.NET5\TestCollectibleLoadContext\Plugin\bin\Debug\net5.0>del Plugin.dll

D:\Projects\.NET5\TestCollectibleLoadContext\Plugin\bin\Debug\net5.0>

And the file is gone...

I mentioned in my first comment that I'm running:

  • VS2019 Version 16.8.0 Preview 1.0
  • .Net 5.0 Preview 7

As you and I experience different behavior with identical code, could it be that .Net 5.0 Preview 7 makes this difference?

rkuiper1 avatar Aug 14 '20 14:08 rkuiper1

Let me check which version of .NET 5.0 I have currently installed.

janvorli avatar Aug 14 '20 15:08 janvorli

Ah, I am sorry, deleting doesn't work for me either. I've tried to rename the file and move the file before and that works. That's quite strange. Anyways, let me debug.

janvorli avatar Aug 14 '20 15:08 janvorli

FYI I did not get this to work either so I ended up running my AssemblyLoadContext in another process and did some IPC... This way I can delete the assemblies after execution. Probably not what you are looking for @rkuiper1 but thats how I solved my problems.

uffebjorklund avatar Aug 14 '20 16:08 uffebjorklund

Somehow runtime is holding the file open. Under WinDbg, I can see that the unload is completed. I'll investigate it further.

janvorli avatar Aug 14 '20 16:08 janvorli

@uffebjorklund , I'm porting from .Net Framework where the AppDomain does these things perfectly, so I was glad to see .Net Core has a somewhat similar solution that allows loading and unloading components. So, I hope we can get things to work with the AssemblyLoadContext. The separate process with IPC will be my plan-b if time runs out. Cheers

rkuiper1 avatar Aug 15 '20 11:08 rkuiper1

@janvorli , You're probably way ahead of me, but just out of curiosity, I did the following:

  • changed the framework from net5.0 to netcoreapp3.1
  • made sure that the PluginHost tries to load the Plugin.dll from the new output folder
  • repeated the two dotnet commands

This time I can delete the Plugin.dll file while the PluginHost is waiting for user input. So, with identical code, there seems to be a difference in behavior between .net core 3.1 and .net 5.0 preview 7.

rkuiper1 avatar Aug 16 '20 10:08 rkuiper1

@rkuiper1 thank you for trying that! I was thinking that it is likely a regression in .NET 5, since I was pretty sure I have tested that scenario in 3.1, so it is helpful to know it is really the case. I've got quite far debugging the problem in the meanwhile, I can see that there is a refcounting problem in the data structures representing the PE files with Assemblies, but I have not located the exact source of that problem.

janvorli avatar Aug 17 '20 09:08 janvorli

@rkuiper1 I've finished debugging it - it is actually a dup of #39609, it was fixed about 3 weeks ago, so it should be working again in .NET 5 Preview 8.

janvorli avatar Aug 17 '20 11:08 janvorli