Skip to content

Commit 52c1938

Browse files
committed
Some lua analyzers
1 parent 2c64eb1 commit 52c1938

2 files changed

Lines changed: 704 additions & 0 deletions

File tree

Lines changed: 335 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,335 @@
1+
using Microsoft.CodeAnalysis;
2+
using Microsoft.CodeAnalysis.CSharp.Syntax;
3+
using Microsoft.CodeAnalysis.Diagnostics;
4+
using Microsoft.CodeAnalysis.FlowAnalysis;
5+
using Microsoft.CodeAnalysis.Operations;
6+
7+
using System;
8+
using System.Collections.Concurrent;
9+
using System.Collections.Generic;
10+
using System.Collections.Immutable;
11+
using System.Linq;
12+
13+
namespace Source.CodeAnalysis.Lua
14+
{
15+
[DiagnosticAnalyzer(LanguageNames.CSharp)]
16+
public sealed class LuaReferenceAnalyzer : DiagnosticAnalyzer
17+
{
18+
public const string DiagnosticId = "SRCLUA001";
19+
20+
static readonly DiagnosticDescriptor Rule = new(
21+
DiagnosticId,
22+
"LuaObject is not unreferenced",
23+
"'{0}' may reach the end of the method without UnReference() being called",
24+
"Lua",
25+
DiagnosticSeverity.Warning,
26+
isEnabledByDefault: true);
27+
28+
static readonly DiagnosticDescriptor OverwriteRule = new(
29+
"SRCLUA002",
30+
"LuaObject overwritten while still referenced",
31+
"A LuaObject is assigned over a local that may still hold a reference; UnReference() it first",
32+
"Lua",
33+
DiagnosticSeverity.Warning,
34+
isEnabledByDefault: true);
35+
36+
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule, OverwriteRule);
37+
38+
public override void Initialize(AnalysisContext context) {
39+
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
40+
context.EnableConcurrentExecution();
41+
context.RegisterCompilationStartAction(start => {
42+
Ownership ownership = new(start.Compilation);
43+
start.RegisterOperationBlockAction(block => ownership.AnalyzeBlock(block));
44+
});
45+
}
46+
47+
sealed class FlowResult
48+
{
49+
public readonly HashSet<ISymbol> Leaked = new(SymbolEqualityComparer.Default);
50+
public readonly HashSet<Location> Overwrites = new();
51+
public readonly Dictionary<ISymbol, Location> Created = new(SymbolEqualityComparer.Default);
52+
public bool ReturnsOwned;
53+
}
54+
55+
sealed class Ownership
56+
{
57+
readonly Compilation compilation;
58+
readonly ConcurrentDictionary<IMethodSymbol, bool> returnsCache = new(SymbolEqualityComparer.Default);
59+
readonly ConcurrentDictionary<IParameterSymbol, bool> takesCache = new(SymbolEqualityComparer.Default);
60+
[ThreadStatic] static HashSet<ISymbol>? inProgress;
61+
62+
public Ownership(Compilation compilation) => this.compilation = compilation;
63+
64+
public void AnalyzeBlock(OperationBlockAnalysisContext context) {
65+
HashSet<IOperation> roots = new();
66+
foreach (IOperation block in context.OperationBlocks) {
67+
IOperation root = block;
68+
while (root.Parent != null)
69+
root = root.Parent;
70+
if (!roots.Add(root))
71+
continue;
72+
ControlFlowGraph? cfg = CreateGraph(root);
73+
if (cfg != null)
74+
AnalyzeGraph(context.ReportDiagnostic, cfg);
75+
}
76+
}
77+
78+
static ControlFlowGraph? CreateGraph(IOperation root) => root switch {
79+
IMethodBodyOperation body => ControlFlowGraph.Create(body),
80+
IConstructorBodyOperation ctor => ControlFlowGraph.Create(ctor),
81+
IBlockOperation statements => ControlFlowGraph.Create(statements),
82+
_ => null,
83+
};
84+
85+
void AnalyzeGraph(Action<Diagnostic> report, ControlFlowGraph cfg) {
86+
FlowResult result = Run(cfg, null);
87+
foreach (ISymbol local in result.Leaked)
88+
if (result.Created.TryGetValue(local, out Location? location))
89+
report(Diagnostic.Create(Rule, location, local.Name));
90+
foreach (Location location in result.Overwrites)
91+
report(Diagnostic.Create(OverwriteRule, location));
92+
93+
foreach (IMethodSymbol fn in cfg.LocalFunctions)
94+
AnalyzeGraph(report, cfg.GetLocalFunctionControlFlowGraph(fn));
95+
foreach (BasicBlock block in cfg.Blocks)
96+
foreach (IOperation op in BlockOperations(block))
97+
foreach (IOperation d in op.DescendantsAndSelf())
98+
if (d is IFlowAnonymousFunctionOperation lambda)
99+
AnalyzeGraph(report, cfg.GetAnonymousFunctionControlFlowGraph(lambda));
100+
}
101+
102+
static bool IsLuaObject(ITypeSymbol? type) {
103+
for (ITypeSymbol? t = type; t != null; t = t.BaseType)
104+
if (t.Name == "LuaObject" && t.ContainingNamespace?.Name == "GarrysMod")
105+
return true;
106+
return false;
107+
}
108+
109+
static bool IsLuaObjectOrInterface(ITypeSymbol? type) =>
110+
type != null && (IsLuaObject(type) || (type.Name == "ILuaObject" && type.ContainingNamespace?.ToDisplayString() == "Source.Common.GarrysMod.Lua"));
111+
112+
static bool IsInterfaceMember(IMethodSymbol method, string interfaceName, string methodName) {
113+
if (method.Name != methodName)
114+
return false;
115+
if (method.ContainingType.Name == interfaceName && method.ContainingType.TypeKind == TypeKind.Interface)
116+
return true;
117+
foreach (INamedTypeSymbol iface in method.ContainingType.AllInterfaces)
118+
if (iface.Name == interfaceName)
119+
foreach (ISymbol member in iface.GetMembers(methodName))
120+
if (SymbolEqualityComparer.Default.Equals(method.ContainingType.FindImplementationForInterfaceMember(member), method))
121+
return true;
122+
return false;
123+
}
124+
125+
static IOperation? Unwrap(IOperation? op) {
126+
while (op is IConversionOperation conv)
127+
op = conv.Operand;
128+
return op;
129+
}
130+
131+
static ISymbol? AsTracked(IOperation? op) => Unwrap(op) switch {
132+
ILocalReferenceOperation local => local.Local,
133+
IParameterReferenceOperation parameter => parameter.Parameter,
134+
_ => null,
135+
};
136+
137+
bool IsOwnedValue(IOperation? op) => Unwrap(op) switch {
138+
IObjectCreationOperation creation => IsLuaObject(creation.Type),
139+
IInvocationOperation invocation => ReturnsOwnership(invocation.TargetMethod),
140+
_ => false,
141+
};
142+
143+
ControlFlowGraph? GraphFor(ISymbol symbol) {
144+
foreach (SyntaxReference reference in symbol.DeclaringSyntaxReferences) {
145+
SyntaxNode node = reference.GetSyntax();
146+
if (node is not BaseMethodDeclarationSyntax && node is not LocalFunctionStatementSyntax)
147+
continue;
148+
if (!compilation.ContainsSyntaxTree(node.SyntaxTree))
149+
continue;
150+
SemanticModel model = compilation.GetSemanticModel(node.SyntaxTree);
151+
IOperation? op = model.GetOperation(node);
152+
if (op != null && CreateGraph(op) is ControlFlowGraph cfg)
153+
return cfg;
154+
}
155+
return null;
156+
}
157+
158+
bool Guarded(ISymbol symbol, Func<bool> compute) {
159+
inProgress ??= new HashSet<ISymbol>(SymbolEqualityComparer.Default);
160+
if (!inProgress.Add(symbol))
161+
return false;
162+
try {
163+
return compute();
164+
}
165+
finally {
166+
inProgress.Remove(symbol);
167+
}
168+
}
169+
170+
bool ReturnsOwnership(IMethodSymbol method) {
171+
method = method.OriginalDefinition;
172+
if (IsInterfaceMember(method, "ILuaInterface", "CreateObject") || IsInterfaceMember(method, "ILuaGameCallback", "CreateLuaObject"))
173+
return true;
174+
if (!IsLuaObjectOrInterface(method.ReturnType))
175+
return false;
176+
if (returnsCache.TryGetValue(method, out bool cached))
177+
return cached;
178+
bool result = Guarded(method, () => GraphFor(method) is ControlFlowGraph cfg && Run(cfg, null).ReturnsOwned);
179+
returnsCache[method] = result;
180+
return result;
181+
}
182+
183+
bool TakesOwnership(IParameterSymbol? parameter) {
184+
if (parameter == null)
185+
return false;
186+
parameter = parameter.OriginalDefinition;
187+
if (parameter.ContainingSymbol is not IMethodSymbol method)
188+
return false;
189+
if (parameter.Ordinal == 0 && (IsInterfaceMember(method, "ILuaInterface", "DestroyObject") || IsInterfaceMember(method, "ILuaGameCallback", "DestroyLuaObject")))
190+
return true;
191+
if (!IsLuaObjectOrInterface(parameter.Type))
192+
return false;
193+
if (takesCache.TryGetValue(parameter, out bool cached))
194+
return cached;
195+
bool result = Guarded(parameter, () => {
196+
if (GraphFor(method) is not ControlFlowGraph cfg)
197+
return false;
198+
return !Run(cfg, parameter).Leaked.Contains(parameter);
199+
});
200+
takesCache[parameter] = result;
201+
return result;
202+
}
203+
204+
FlowResult Run(ControlFlowGraph cfg, IParameterSymbol? parameter) {
205+
FlowResult result = new();
206+
foreach (BasicBlock block in cfg.Blocks)
207+
foreach (IOperation op in BlockOperations(block))
208+
foreach (IOperation d in op.DescendantsAndSelf())
209+
if (d is ISimpleAssignmentOperation assign && Unwrap(assign.Target) is ILocalReferenceOperation local && !result.Created.ContainsKey(local.Local) && IsOwnedValue(assign.Value))
210+
result.Created[local.Local] = assign.Value.Syntax.GetLocation();
211+
212+
if (parameter != null)
213+
result.Created[parameter] = Location.None;
214+
215+
if (result.Created.Count == 0) {
216+
foreach (BasicBlock block in cfg.Blocks)
217+
if (block.FallThroughSuccessor?.Semantics == ControlFlowBranchSemantics.Return && IsOwnedValue(block.BranchValue))
218+
result.ReturnsOwned = true;
219+
return result;
220+
}
221+
222+
HashSet<ISymbol>?[] input = new HashSet<ISymbol>?[cfg.Blocks.Length];
223+
input[0] = new HashSet<ISymbol>(SymbolEqualityComparer.Default);
224+
if (parameter != null)
225+
input[0]!.Add(parameter);
226+
Queue<int> work = new();
227+
work.Enqueue(0);
228+
229+
while (work.Count > 0) {
230+
int ordinal = work.Dequeue();
231+
BasicBlock block = cfg.Blocks[ordinal];
232+
HashSet<ISymbol> state = new(input[ordinal]!, SymbolEqualityComparer.Default);
233+
234+
foreach (IOperation op in BlockOperations(block))
235+
foreach (IOperation d in op.DescendantsAndSelf())
236+
Transfer(d, state, result);
237+
238+
if (block.Kind == BasicBlockKind.Exit) {
239+
result.Leaked.UnionWith(state);
240+
continue;
241+
}
242+
243+
if (block.FallThroughSuccessor?.Semantics == ControlFlowBranchSemantics.Return) {
244+
if (AsTracked(block.BranchValue) is ISymbol returned && result.Created.ContainsKey(returned)) {
245+
if (state.Remove(returned))
246+
result.ReturnsOwned = true;
247+
}
248+
else if (IsOwnedValue(block.BranchValue))
249+
result.ReturnsOwned = true;
250+
}
251+
252+
Propagate(cfg, result, block.FallThroughSuccessor, state, input, work);
253+
Propagate(cfg, result, block.ConditionalSuccessor, state, input, work);
254+
}
255+
return result;
256+
}
257+
258+
static IEnumerable<IOperation> BlockOperations(BasicBlock block) {
259+
foreach (IOperation op in block.Operations)
260+
yield return op;
261+
if (block.BranchValue != null)
262+
yield return block.BranchValue;
263+
}
264+
265+
void Propagate(ControlFlowGraph cfg, FlowResult result, ControlFlowBranch? branch, HashSet<ISymbol> state, HashSet<ISymbol>?[] input, Queue<int> work) {
266+
if (branch?.Destination == null || branch.Semantics == ControlFlowBranchSemantics.Throw || branch.Semantics == ControlFlowBranchSemantics.Rethrow)
267+
return;
268+
if (!branch.FinallyRegions.IsEmpty) {
269+
state = new HashSet<ISymbol>(state, SymbolEqualityComparer.Default);
270+
foreach (ControlFlowRegion region in branch.FinallyRegions)
271+
for (int i = region.FirstBlockOrdinal; i <= region.LastBlockOrdinal; i++)
272+
foreach (IOperation op in BlockOperations(cfg.Blocks[i]))
273+
foreach (IOperation d in op.DescendantsAndSelf())
274+
Transfer(d, state, result);
275+
}
276+
int dest = branch.Destination.Ordinal;
277+
if (input[dest] == null) {
278+
input[dest] = new HashSet<ISymbol>(state, SymbolEqualityComparer.Default);
279+
work.Enqueue(dest);
280+
return;
281+
}
282+
int before = input[dest]!.Count;
283+
input[dest]!.UnionWith(state);
284+
if (input[dest]!.Count != before)
285+
work.Enqueue(dest);
286+
}
287+
288+
void ReleaseArguments(ImmutableArray<IArgumentOperation> arguments, HashSet<ISymbol> state) {
289+
foreach (IArgumentOperation arg in arguments)
290+
if (AsTracked(arg.Value) is ISymbol owned && state.Contains(owned) && TakesOwnership(arg.Parameter))
291+
state.Remove(owned);
292+
}
293+
294+
void Transfer(IOperation op, HashSet<ISymbol> state, FlowResult result) {
295+
switch (op) {
296+
case ISimpleAssignmentOperation assign: {
297+
if (AsTracked(assign.Target) is ISymbol target && result.Created.ContainsKey(target) && IsOwnedValue(assign.Value)) {
298+
if (!state.Add(target))
299+
result.Overwrites.Add(assign.Value.Syntax.GetLocation());
300+
break;
301+
}
302+
if (AsTracked(assign.Value) is ISymbol value && result.Created.ContainsKey(value))
303+
state.Remove(value);
304+
break;
305+
}
306+
case ITupleOperation tuple: {
307+
foreach (IOperation element in tuple.Elements)
308+
if (AsTracked(element) is ISymbol tracked)
309+
state.Remove(tracked);
310+
break;
311+
}
312+
case IInvocationOperation invocation: {
313+
if (invocation.TargetMethod.GetAttributes().Any(a => a.AttributeClass?.Name == "DoesNotReturnAttribute")) {
314+
state.Clear();
315+
break;
316+
}
317+
if (invocation.TargetMethod.Name == "UnReference" && AsTracked(invocation.Instance) is ISymbol instance)
318+
state.Remove(instance);
319+
ReleaseArguments(invocation.Arguments, state);
320+
break;
321+
}
322+
case IObjectCreationOperation ctor: {
323+
ReleaseArguments(ctor.Arguments, state);
324+
break;
325+
}
326+
case IFlowAnonymousFunctionOperation lambda: {
327+
HashSet<string> names = new(lambda.Syntax.DescendantNodes().OfType<IdentifierNameSyntax>().Select(id => id.Identifier.ValueText));
328+
state.RemoveWhere(tracked => names.Contains(tracked.Name));
329+
break;
330+
}
331+
}
332+
}
333+
}
334+
}
335+
}

0 commit comments

Comments
 (0)