You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Assembly.Load opens /dev/zero in linux and does not close it #47859
After several hours of work web application on cent os 7 gets error "Too many files open"
General
After each request to my application the system opens and keep open a lot of /dev/zero files.
I run command lsof | grep zero | wc -l and looking out that count of files increase and increase.
System Info
OS LINUX X64 Linux 3.10.0-1062.4.1.el7.x86_64 dotnet/core#1 SMP Fri Oct 18 17:15:30 UTC 2019 Cent OS 7
.NET Core 3.0.0
We do not open /dev/zero stream in our code.
What I found out.
Clear (dotnet new mvc) application do not reproduce this issue (it seems to me)
We have custom fileproviders for razor and static files, and autofac with specific lifetime model. File providers use FileInfo, PhysicalFileInfo and FileWatchers.
It reproduce only when Razor processes the request. In case of Json result - everything is ok, static file is ok too
And it very strange that Razor asks and opens new stream of Shared files (like layout, viewimport etc) several times due one page.
We can not share the code, because it is very big corporate system. We try to determinate place in code. Will touch you on progress.
We have custom fileproviders for razor and static files, and autofac with specific lifetime model. File providers use FileInfo, PhysicalFileInfo and FileWatchers.
Are you properly closing the file handles (disposing the file handling objects) after using them?
After the long time of investigation we found out the reason.
We do not precompile views on publish and use runtime compilation, so .net tries find (I guess) *.views.dll, cant find it and redirect stream to /dev/zero and doesn't close it.
Is there any progress on this issue? We are using Assembly.Load to load results of Roslyn compilation for thousands of small assemblies, and things get really ugly with all FD pool is wasted on /dev/zero (
Nope, while the return type seems incorrect, that is not the reason for the leak. Fixing that does no fix the problem.
We are leaking actual handles somewhere.
Opening \dev\zero is currently by-design. It is used in the pattern that creates anonymous memory mappings without relying on MAP_ANONYMOUS. It is likely something that was done long ago for portability.
I think it is no longer needed and should be removed to avoid running into fd limits.
The main reason for the leak though is that assemblies loaded via Assembly.Load are not unloadable.
If you load a lot you will see resource consumption going up. That part is by-design.
The following example, which uses unloadable context, does not have the issue.
usingSystem;usingSystem.Collections.Concurrent;usingSystem.Collections.Generic;usingSystem.Diagnostics;usingSystem.IO;usingSystem.Reflection;usingSystem.Runtime.Loader;usingSystem.Text;usingMicrosoft.CodeAnalysis;usingMicrosoft.CodeAnalysis.CSharp;usingMicrosoft.CodeAnalysis.Emit;usingMicrosoft.CodeAnalysis.Text;namespaceTestAssemblyLoad{classProgram{privatestaticreadonlyEncodingEncoding=Encoding.UTF8;privatestaticreadonlyCSharpParseOptionsParseOptions=CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Latest);privatestaticreadonlyCSharpCompilationOptionsCompilationOptions=newCSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);privatestaticreadonlyConcurrentDictionary<string,MetadataReference>References=newConcurrentDictionary<string,MetadataReference>();staticProgram(){varreferencedAssemblies=Assembly.GetEntryAssembly().GetReferencedAssemblies();foreach(varreferencedAssemblyinreferencedAssemblies)AddReference(referencedAssembly);}privatestaticvoidAddReference(AssemblyNameassemblyName){varassembly=Assembly.Load(assemblyName);References.TryAdd(assembly.Location,MetadataReference.CreateFromFile(assembly.Location));varreferencedAssemblyNames=assembly.GetReferencedAssemblies();foreach(varreferencedAssemblyNameinreferencedAssemblyNames){varreferencedAssembly=Assembly.Load(referencedAssemblyName);References.TryAdd(referencedAssembly.Location,MetadataReference.CreateFromFile(referencedAssembly.Location));}}staticvoidMain(string[]args){Console.WriteLine("PID: "+Process.GetCurrentProcess().Id);Console.ReadKey();Run(@"using System;public class SubProgram{ public static void Main() { Console.Write("".""); }}");Console.WriteLine("The end...");Console.ReadKey();}publicstaticvoidRun(stringcode){varassemblyName=nameof(Assembly)+"_"+Guid.NewGuid().ToString("N");varsyntaxTrees=newList<SyntaxTree>();varembeddedTexts=newList<EmbeddedText>();varfilePath=$"{nameof(Assembly)}_file_{Guid.NewGuid():N}.cs";varbuffer=Encoding.GetBytes(code);varsourceText=SourceText.From(buffer,buffer.Length,Encoding,canBeEmbedded:true);varsyntaxTree=CSharpSyntaxTree.ParseText(sourceText,ParseOptions,filePath);varembeddedText=EmbeddedText.FromSource(filePath,sourceText);syntaxTrees.Add(syntaxTree);embeddedTexts.Add(embeddedText);varcompilation=CSharpCompilation.Create(assemblyName,syntaxTrees:syntaxTrees,references:References.Values,options:CompilationOptions);varemitOptions=newEmitOptions(debugInformationFormat:DebugInformationFormat.PortablePdb,pdbFilePath:Path.ChangeExtension(assemblyName,"pdb"));usingvarstream=newMemoryStream();usingvarsymbolsStream=newMemoryStream();varemitResult=compilation.Emit(stream,symbolsStream,embeddedTexts:embeddedTexts,options:emitOptions);if(emitResult.Success){stream.Seek(0,SeekOrigin.Begin);symbolsStream.Seek(0,SeekOrigin.Begin);}varstreamArr=stream.ToArray();varsymbolsStreamArr=symbolsStream.ToArray();varassembly=Assembly.Load(streamArr,symbolsStreamArr);for(inti=0;i<100000000;i++){// THIS WOULD NOT UNLOAD !!!// Assembly.Load(streamArr, symbolsStreamArr);stream.Seek(0,SeekOrigin.Begin);symbolsStream.Seek(0,SeekOrigin.Begin);varalc=newAssemblyLoadContext(null,isCollectible:true);Assemblya=alc.LoadFromStream(stream,symbolsStream);ProcessStartInfopi=newProcessStartInfo();pi.UseShellExecute=true;pi.FileName="/usr/bin/lsof";pi.Arguments=" /dev/zero";Process.Start(pi);Console.ReadKey();vartype=assembly.GetType("SubProgram");varmethod=type.GetMethod("Main");method.Invoke(null,null);alc.Unload();GC.Collect();GC.WaitForPendingFinalizers();GC.Collect();GC.WaitForPendingFinalizers();GC.Collect();GC.WaitForPendingFinalizers();Process.Start(pi);}stream.Dispose();symbolsStream.Dispose();}}}
Activity
scalablecory commentedon Nov 7, 2019
Are you opening /dev/zero, or do you think it is being opened by something within .NET?
Can you share your code?
for7raid commentedon Nov 8, 2019
We do not open /dev/zero stream in our code.
What I found out.
dotnet new mvc) application do not reproduce this issue (it seems to me)And it very strange that Razor asks and opens new stream of Shared files (like layout, viewimport etc) several times due one page.
We can not share the code, because it is very big corporate system. We try to determinate place in code. Will touch you on progress.
carlossanlop commentedon Nov 19, 2019
Are you properly closing the file handles (disposing the file handling objects) after using them?
for7raid commentedon Nov 20, 2019
After the long time of investigation we found out the reason.
We do not precompile views on publish and use runtime compilation, so .net tries find (I guess) *.views.dll, cant find it and redirect stream to /dev/zero and doesn't close it.
Steps to reproduce:
dotnet new mvcMicrosoft.AspNetCore.Mvc.Razor.RuntimeCompilationdotnet {fileName}.dlllsof | grep zero | wc -lP.S. May be we should move this issue to asp repo?
scalablecory commentedon Nov 21, 2019
Thanks, that's helpful.
@Pilchie can you help route
Pilchie commentedon Nov 25, 2019
This issue was moved to dotnet/aspnetcore#17395
for7raid commentedon Dec 9, 2019
Hi @Pilchie @carlossanlop
We think this is not asp issue, but core.
Assemly.Load opens /dev/zero stream
Here code to reproduce
after line
var assembly = Assembly.Load(streamArr, symbolsStreamArr);count of /dev/zero stream increased.We deepened to code inside the framework, file
\src\System.Private.CoreLib\src\System\Runtime\Loader\AssemblyLoadContext.CoreCLR.cshas methodand dll import
The LoadFromStream opens IntPtr and does not close it.
May be it should be void, like
AspRuntimeCompilation loads assembly with the same way while processing and compile views.
[-]too many files open error in linux[/-][+]Assembly.Load opens /dev/zero in linux and does not close it[/+]BineG commentedon Feb 19, 2020
Another code snippet to observe the issue. Memory consumption just keeps climbing.
Also, when calling context.Unload() I get an ExecutionEngineException?
`
class Program
{
static void Main(string[] args)
{
AssemblyExecutor executor = new AssemblyExecutor();
`
mikhail-barg commentedon Feb 4, 2021
Is there any progress on this issue? We are using
Assembly.Loadto load results of Roslyn compilation for thousands of small assemblies, and things get really ugly with all FD pool is wasted on /dev/zero (mikhail-barg commentedon Feb 4, 2021
Would you mind please reopening this issue for it does not seem to be aspnet-related? We are not using aspnet, but are affected by this problem still
2 remaining items
Pilchie commentedon Feb 4, 2021
@jeffschwMSFT - can you help route within runtime?
VSadov commentedon Feb 5, 2021
I can reproduce this. Yes
LoadFromStreamleaksdev\zerohandles.Mismatch in the qcall return type is the likely reason.
VSadov commentedon Feb 5, 2021
Nope, while the return type seems incorrect, that is not the reason for the leak. Fixing that does no fix the problem.
We are leaking actual handles somewhere.
VSadov commentedon Feb 10, 2021
Opening
\dev\zerois currently by-design. It is used in the pattern that creates anonymous memory mappings without relying onMAP_ANONYMOUS. It is likely something that was done long ago for portability.I think it is no longer needed and should be removed to avoid running into fd limits.
The main reason for the leak though is that assemblies loaded via
Assembly.Loadare not unloadable.If you load a lot you will see resource consumption going up. That part is by-design.
VSadov commentedon Feb 10, 2021
The following example, which uses unloadable context, does not have the issue.
VSadov commentedon Feb 10, 2021
I think we still need to get rid of opening
/dev/zero- just to avoid running into fd limits, which could be a relatively small number.VSadov commentedon Feb 17, 2021
fixed in #48140