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 torn write of struct causing crash in symbol finder. #69927

Merged
merged 10 commits into from
Sep 13, 2023
Merged
Show file tree
Hide file tree
Changes from 7 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
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,15 @@
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Utilities;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.FindSymbols
Expand Down Expand Up @@ -70,16 +69,10 @@ public MultiDictionary<string, ExtensionMethodInfo>.ValueSet GetExtensionMethodI

public bool ContainsExtensionMethod => _receiverTypeNameToExtensionMethodMap?.Count > 0;

private SpellChecker? _spellChecker;
private SpellChecker SpellChecker
{
get
{
_spellChecker ??= CreateSpellChecker(Checksum, _nodes);
Copy link
Member Author

Choose a reason for hiding this comment

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

SpellChecker? was a Nullable<SpellChecker>. This is just a pure struct which can have torn writes. By moving to a StrongBox<SpellChecker> we have teh runtime guarantee that if _spllChecker is not null then _spellChecker.Value is 'completely written'.


return _spellChecker.Value;
}
}
/// <summary>
/// Explicitly boxed so that we can safely initialize/read this across threads without the need for a lock.
/// </summary>
private StrongBox<SpellChecker>? _spellChecker;
Copy link
Member

Choose a reason for hiding this comment

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

❗ Since _spellChecker.Value is never written after construction, and there are no other instantiations of the SpellChecker type, this change is functionally equivalent to (but much more complicated than) just making SpellChecker a reference type. You could further simplify things by using the helpers from #69017 to initialize the field on first use.

Copy link
Member

@sharwell sharwell Sep 13, 2023

Choose a reason for hiding this comment

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

The other option if you want to keep this a value type is to use this helper:

public static T EnsureInitialized<T>([NotNull] ref T? target, ref bool initialized, [NotNullIfNotNull(nameof(syncLock))] ref object? syncLock, Func<T> valueFactory)
=> LazyInitializer.EnsureInitialized<T>(ref target!, ref initialized, ref syncLock, valueFactory);

The implementation of EnsureInitialized contains a lock-free fast path for the case where initialized is true (set at the end of initialization). You may need to use PooledDelegates to avoid a delegate allocation on the fast path as well.

Copy link
Member Author

Choose a reason for hiding this comment

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

Thanks. Moved to just be a refernece type. That fits best here for me :)


private SymbolTreeInfo(
Checksum checksum,
Expand All @@ -96,7 +89,7 @@ private SymbolTreeInfo(
private SymbolTreeInfo(
Checksum checksum,
ImmutableArray<Node> sortedNodes,
SpellChecker? spellChecker,
StrongBox<SpellChecker>? spellChecker,
OrderPreservingMultiDictionary<int, int> inheritanceMap,
MultiDictionary<string, ExtensionMethodInfo>? receiverTypeNameToExtensionMethodMap)
{
Expand Down Expand Up @@ -181,11 +174,15 @@ private async Task<ImmutableArray<ISymbol>> FuzzyFindAsync(
using var similarNames = TemporaryArray<string>.Empty;
using var result = TemporaryArray<ISymbol>.Empty;

SpellChecker.FindSimilarWords(ref similarNames.AsRef(), name, substringsAreSimilar: false);
// Ensure the spell checker is initialized. This is concurrency safe. Technically multiple threads may end
// up overwriting the field, but even if that happens, we are sure to see a fully written spell checker as
// the runtime guarantees that the strongbox .Value field will be completely written when we read out field.
_spellChecker ??= CreateSpellChecker(Checksum, _nodes);
_spellChecker.Value.FindSimilarWords(ref similarNames.AsRef(), name, substringsAreSimilar: false);

foreach (var similarName in similarNames)
{
var symbols = await FindAsync(lazyAssembly, similarName, ignoreCase: true, cancellationToken: cancellationToken).ConfigureAwait(false);
var symbols = await FindAsync(lazyAssembly, similarName, ignoreCase: true, cancellationToken).ConfigureAwait(false);
result.AddRange(symbols);
}

Expand Down Expand Up @@ -302,8 +299,8 @@ private static int BinarySearch(ImmutableArray<Node> nodes, string name)

#region Construction

private static SpellChecker CreateSpellChecker(Checksum checksum, ImmutableArray<Node> sortedNodes)
=> new(checksum, sortedNodes.Select(n => n.Name));
private static StrongBox<SpellChecker> CreateSpellChecker(Checksum checksum, ImmutableArray<Node> sortedNodes)
=> new(new(checksum, sortedNodes.Select(n => n.Name)));

private static ImmutableArray<Node> SortNodes(ImmutableArray<BuilderNode> unsortedNodes)
{
Expand Down
Loading
Loading