Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix memory leak in ProjectRootElement.Reload #6457

Merged
merged 2 commits into from
May 24, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions src/Build.OM.UnitTests/Construction/ProjectRootElement_Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using System.Security.AccessControl;
using System.Security.Principal;
#endif
using System.Reflection;
using System.Text;
using System.Threading;
using System.Xml;
Expand All @@ -18,6 +19,7 @@

using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException;
using ProjectCollection = Microsoft.Build.Evaluation.ProjectCollection;
using Shouldly;
using Xunit;

namespace Microsoft.Build.UnitTests.OM.Construction
Expand Down Expand Up @@ -1854,6 +1856,31 @@ public void ReloadCanOverwriteUnsavedChanges()
AssertReload(SimpleProject, ComplexProject, true, true, true, act);
}

[Fact]
public void ReloadDoesNotLeakCachedXmlDocuments()
{
using var env = TestEnvironment.Create();
var testFiles = env.CreateTestProjectWithFiles("", new[] { "build.proj" });
var projectFile = testFiles.CreatedFiles.First();

var projectElement = ObjectModelHelpers.CreateInMemoryProjectRootElement(SimpleProject);
projectElement.Save(projectFile);

int originalDocumentCount = GetNumberOfDocumentsInProjectStringCache(projectElement);

// Test successful reload.
projectElement.Reload(false);
GetNumberOfDocumentsInProjectStringCache(projectElement).ShouldBe(originalDocumentCount);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm wondering if we should verify that the project is the new one the first time and the old one the second time. Not directly related to your change, though.

More related, I'd be in favor of reloading 3-4 times just in case there's something unexpected.


// Test failed reload.
using (StreamWriter sw = new StreamWriter(projectFile))
{
sw.WriteLine("<XXX />"); // Invalid root element
}
Should.Throw<InvalidProjectFileException>(() => projectElement.Reload(false));
GetNumberOfDocumentsInProjectStringCache(projectElement).ShouldBe(originalDocumentCount);
}

private void AssertReload(
string initialContents,
string changedContents,
Expand Down Expand Up @@ -1986,5 +2013,17 @@ private void VerifyAssertLineByLine(string expected, string actual)
{
Helpers.VerifyAssertLineByLine(expected, actual, false);
}

/// <summary>
/// Returns the number of documents retained by the project string cache.
/// Peeks at it via reflection since internals are not visible to these tests.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there any reason internals aren't visible to these tests? That seems like something we'd want for other tests later, too.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe it's by design. These tests should be testing the public surface (or Object Model, as in Build.OM.UnitTests). I'm not confident that this test case belongs here. It is testing a public method but needs an internal hook to verify the expected behavior.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It sounds a little better to me to move it to Build.UnitTests, but it isn't too important.

/// </summary>
private int GetNumberOfDocumentsInProjectStringCache(ProjectRootElement project)
{
var bindingFlags = BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetProperty;
object document = typeof(ProjectRootElement).InvokeMember("XmlDocument", bindingFlags, null, project, Array.Empty<object>());
object cache = document.GetType().InvokeMember("StringCache", bindingFlags, null, document, Array.Empty<object>());
return (int)cache.GetType().InvokeMember("DocumentCount", bindingFlags, null, cache, Array.Empty<object>());
}
}
}
36 changes: 25 additions & 11 deletions src/Build/Construction/ProjectRootElement.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1677,19 +1677,33 @@ private void ReloadFrom(Func<bool, XmlDocumentWithLocation> documentProducer, bo
{
ThrowIfUnsavedChanges(throwIfUnsavedChanges);

XmlDocumentWithLocation document = documentProducer(preserveFormatting ?? PreserveFormatting);

// Reload should only mutate the state if there are no parse errors.
ThrowIfDocumentHasParsingErrors(document);

// Do not clear the string cache.
// Based on the assumption that Projects are reloaded repeatedly from their file with small increments,
// and thus most strings would get reused
//this.XmlDocument.ClearAnyCachedStrings();
var oldDocument = XmlDocument;
XmlDocumentWithLocation newDocument = documentProducer(preserveFormatting ?? PreserveFormatting);
try
{
// Reload should only mutate the state if there are no parse errors.
ThrowIfDocumentHasParsingErrors(newDocument);

RemoveAllChildren();
RemoveAllChildren();

ProjectParser.Parse(document, this);
ProjectParser.Parse(newDocument, this);
}
finally
{
// Whichever document didn't become this element's document must be removed from the string cache.
// We do it after the fact based on the assumption that Projects are reloaded repeatedly from their
// file with small increments, and thus most strings would get reused avoiding unnecessary churn in
// the string cache.
var currentDocument = XmlDocument;
if (!object.ReferenceEquals(currentDocument, oldDocument))
{
oldDocument.ClearAnyCachedStrings();
cdmihai marked this conversation as resolved.
Show resolved Hide resolved
}
if (!object.ReferenceEquals(currentDocument, newDocument))
{
newDocument.ClearAnyCachedStrings();
}
}

MarkDirty("Project reloaded", null);
}
Expand Down
14 changes: 14 additions & 0 deletions src/Build/Evaluation/ProjectStringCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,20 @@ internal int Count
}
}

/// <summary>
/// Obtain the number of documents contained in the cache.
/// </summary>
internal int DocumentCount
{
get
{
lock (_locker)
{
return _documents.Count;
}
}
}

/// <summary>
/// Add the given string to the cache or return the existing string if it is already
/// in the cache.
Expand Down