-
Notifications
You must be signed in to change notification settings - Fork 147
/
Copy pathCallSitesGenerator.cs
328 lines (284 loc) · 15.6 KB
/
CallSitesGenerator.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Mono.Cecil;
using Nuke.Common.IO;
using Logger = Serilog.Log;
namespace CodeGenerators
{
internal static class CallSitesGenerator
{
private const string NullLiteral = "null";
public static void GenerateCallSites(IEnumerable<TargetFramework> targetFrameworks, Func<string, string> getDllPath, AbsolutePath outputPath)
{
Logger.Debug("Generating CallSite definitions file ...");
var aspectClasses = new Dictionary<string, AspectClass>();
foreach(var tfm in targetFrameworks)
{
var dllPath = getDllPath(tfm);
RetrieveCallSites(aspectClasses, dllPath, tfm);
}
GenerateFile(aspectClasses, outputPath);
}
internal static void RetrieveCallSites(Dictionary<string, AspectClass> aspectClasses, string dllPath, TargetFramework tfm)
{
// We check if the assembly file exists.
if (!File.Exists(dllPath))
{
throw new FileNotFoundException($"Error extracting types for CallSite generation. Assembly file was not found. Path: {dllPath}", dllPath);
}
var tfmCategory = GetCategory(tfm);
// Open dll to extract all AspectsClass attributes.
using var asmDefinition = AssemblyDefinition.ReadAssembly(dllPath);
foreach (var type in asmDefinition.MainModule.Types)
{
var aspectClassAttribute = type.CustomAttributes.FirstOrDefault(IsAspectClass);
if (aspectClassAttribute is null)
{
continue;
}
var aspectClassLine = $"{GetAspectLine(aspectClassAttribute, out var category)} {type.FullName}";
if (!aspectClasses.TryGetValue(aspectClassLine, out var aspectClass))
{
aspectClass = new AspectClass();
aspectClass.Categories |= category;
aspectClasses[aspectClassLine] = aspectClass;
}
// Retrieve aspects
foreach(var method in type.Methods)
{
foreach(var aspectAttribute in method.CustomAttributes.Where(IsAspect))
{
var aspectLine = $"{GetAspectLine(aspectAttribute, out _)} {GetMethodName(method)}";
if (!aspectClass.Aspects.TryGetValue(aspectLine, out var aspect))
{
aspect = new Aspect();
}
aspect.Tfms |= tfmCategory;
aspectClass.Aspects[aspectLine] = aspect;
}
}
}
static string GetMethodName(MethodDefinition method)
{
var parameters = string.Join(",", method.Parameters.Select(GetParameter));
var fullName = $"{method.FullName.Substring(0, method.FullName.IndexOf('('))}({parameters})";
var methodNameStart = fullName.IndexOf("::");
if (methodNameStart < 0)
{
throw new InvalidOperationException("Could not find '::' in method name " + fullName);
}
return fullName.Substring(methodNameStart + 2).Replace("<T>", "<!!0>").Replace("&", "");
static string GetParameter(ParameterDefinition parameter)
{
var paramType = parameter.ParameterType.FullName;
return paramType switch
{
"T" => "!!0",
_ => paramType.Replace("<T>", "<!!0>"),
};
}
}
static bool IsAspectClass(Mono.Cecil.CustomAttribute attribute)
{
return attribute.AttributeType.FullName.StartsWith("Datadog.Trace.Iast.Dataflow.AspectClass");
}
static bool IsAspect(Mono.Cecil.CustomAttribute attribute)
{
return attribute.AttributeType.FullName.StartsWith("Datadog.Trace.Iast.Dataflow.Aspect");
}
static string GetAspectLine(Mono.Cecil.CustomAttribute data, out InstrumentationCategory category)
{
category = InstrumentationCategory.Iast;
var arguments = data.ConstructorArguments.Select(GetArgument).ToList();
var name = data.AttributeType.Name;
var version = string.Empty;
if (name.EndsWith("FromVersionAttribute"))
{
// Aspect with version limitation
name = name.Replace("FromVersionAttribute", "Attribute");
version = ";V" + arguments[0].Trim('"');
arguments.RemoveAt(0);
}
if (name == "AspectClassAttribute")
{
if (arguments.Count == 2)
{
category = (InstrumentationCategory)Enum.Parse(typeof(InstrumentationCategory), arguments[1]);
return $"[AspectClass({arguments[0]},[None],Propagation,[]){version}]";
}
else if (arguments.Count == 3)
{
return $"[AspectClass({arguments[0]},[None],{arguments[1]},{Check(arguments[2])}){version}]";
}
else if (arguments.Count == 4)
{
category = (InstrumentationCategory)Enum.Parse(typeof(InstrumentationCategory), arguments[1]);
return $"[AspectClass({arguments[0]},[None],{arguments[2]},{Check(arguments[3])}){version}]";
}
else if (arguments.Count == 5)
{
category = (InstrumentationCategory)Enum.Parse(typeof(InstrumentationCategory), arguments[2]);
return $"[AspectClass({arguments[0]},{arguments[1]},{arguments[3]},{Check(arguments[4])}){version}]";
}
throw new ArgumentException($"Could not find AspectClassAttribute overload with {arguments.Count} parameters");
}
return name switch
{
// AspectAttribute(string targetMethod, string targetType, int[] paramShift, bool[] boxParam, AspectFilter[] filters, AspectType aspectType = AspectType.Propagation, VulnerabilityType[] vulnerabilityTypes)
"AspectCtorReplaceAttribute" => arguments.Count switch
{
// AspectCtorReplaceAttribute(string targetMethod)
1 => $"[AspectCtorReplace({arguments[0]},\"\",[0],[False],[None],Default,[]){version}]",
// AspectCtorReplaceAttribute(string targetMethod, params AspectFilter[] filters)
2 => $"[AspectCtorReplace({arguments[0]},\"\",[0],[False],{Check(arguments[1])},Default,[]){version}]",
// AspectCtorReplaceAttribute(string targetMethod, AspectType aspectType = AspectType.Default, params VulnerabilityType[] vulnerabilityTypes)
3 => $"[AspectCtorReplace({arguments[0]},\"\",[0],[False],[None],{arguments[1]},{Check(arguments[2])}){version}]",
// AspectCtorReplaceAttribute(string targetMethod, AspectFilter[] filters, AspectType aspectType = AspectType.Default, params VulnerabilityType[] vulnerabilityTypes)
4 => $"[AspectCtorReplace({arguments[0]},\"\",[0],[False],[{arguments[1]}],{arguments[2]},{Check(arguments[3])}){version}]",
_ => throw new ArgumentException($"Could not find AspectCtorReplaceAttribute overload with {arguments.Count} parameters")
},
"AspectMethodReplaceAttribute" => arguments.Count switch
{
// AspectMethodReplaceAttribute(string targetMethod)
1 => $"[AspectMethodReplace({arguments[0]},\"\",[0],[False],[None],Default,[]){version}]",
// AspectMethodReplaceAttribute(string targetMethod, params AspectFilter[] filters)
2 => $"[AspectMethodReplace({arguments[0]},\"\",[0],[False],{Check(arguments[1], "[None]")},Default,[]){version}]",
// AspectMethodReplaceAttribute(string targetMethod, string targetType, params AspectFilter[] filters)
3 => arguments[1] switch
{
{ } when arguments[1].StartsWith("[") => $"[AspectMethodReplace({arguments[0]},\"\",{arguments[1]},{arguments[2]},[None],Default,[]){version}]",
// AspectMethodReplaceAttribute(string targetMethod, string targetType, params AspectFilter[] filters)
_ => $"[AspectMethodReplace({arguments[0]},{arguments[1]},[0],[False],{Check(arguments[2], "[None]")},Default,[]){version}]",
},
_ => throw new ArgumentException($"Could not find AspectMethodReplaceAttribute overload with {arguments.Count} parameters")
},
"AspectMethodInsertBeforeAttribute" => arguments.Count switch
{
// AspectMethodInsertBeforeAttribute(string targetMethod, params int[] paramShift)
2 => $"[AspectMethodInsertBefore({arguments[0]},\"\",{MakeSameSize(Check(arguments[1]))},[None],Default,[]){version}]",
// AspectMethodInsertBeforeAttribute(string targetMethod, int[] paramShift, bool[] boxParam)
3 => $"[AspectMethodInsertBefore({arguments[0]},\"\",[{arguments[1]}],[{arguments[2]}],[None],Default,[]){version}]",
_ => throw new ArgumentException($"Could not find AspectMethodInsertBeforeAttribute overload with {arguments.Count} parameters")
},
"AspectMethodInsertAfterAttribute" => arguments.Count switch
{
// AspectMethodInsertAfterAttribute(string targetMethod)
1 => $"[AspectMethodInsertAfter({arguments[0]},\"\",[0],[False],[None],Default,[]){version}]",
// AspectMethodInsertAfterAttribute(string targetMethod, AspectType aspectType, params VulnerabilityType[] vulnerabilityTypes)
3 => $"[AspectMethodInsertAfter({arguments[0]},\"\",[0],[False],[None],{arguments[1]},{Check(arguments[2])}){version}]",
_ => throw new ArgumentException($"Could not find AspectMethodInsertAfterAttribute overload with {arguments.Count} parameters")
},
_ => throw new Exception()
};
static string Check(string val, string ifEmpty = "[]")
{
return (string.IsNullOrEmpty(val) || val == NullLiteral || val == "[]") ? ifEmpty : val;
}
static string MakeSameSize(string val, string ifEmpty = "[0]", string defaultValue = "False")
{
val = Check(val, ifEmpty);
int count = val.Count(c => c == ',');
string values = string.Empty;
for (int x = 0; x < count + 1; x++)
{
values += defaultValue;
if (x < count) { values += ","; }
}
return $"{val},[{values}]";
}
static string GetArgument(Mono.Cecil.CustomAttributeArgument customAttributeArgument)
{
if (customAttributeArgument.Value is null)
{
return NullLiteral;
}
else if (customAttributeArgument.Type.IsPrimitive)
{
return customAttributeArgument.Value?.ToString() ?? NullLiteral;
}
else if (customAttributeArgument.Type.FullName == "System.String")
{
return $"\"{customAttributeArgument.Value}\"";
}
else
{
var type = customAttributeArgument.Type.Resolve();
if (customAttributeArgument.Value is CustomAttributeArgument[] argArray)
{
return $"[{string.Join(",", argArray.Select(GetArgument))}]";
}
else if (type.IsEnum)
{
var value = type.Fields.FirstOrDefault(f => customAttributeArgument.Value.Equals(f.Constant));
return value.Name;
}
}
return string.Empty;
}
}
}
internal static void GenerateFile(Dictionary<string, AspectClass> aspectClasses, AbsolutePath outputPath)
{
var sb = new StringBuilder();
sb.AppendLine("""
// <copyright company="Datadog">
// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License.
// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc.
// </copyright>
// <auto-generated/>
#pragma once
#include "generated_definitions.h"
namespace trace
{
std::vector<WCHAR*> g_callSites=
{
""");
foreach (var aspectClass in aspectClasses.OrderBy(static k => k.Key.ToString(), StringComparer.OrdinalIgnoreCase))
{
sb.AppendLine(Format(aspectClass.Key + aspectClass.Value.Subfix()));
foreach (var method in aspectClass.Value.Aspects.OrderBy(static k => k.Key.ToString(), StringComparer.OrdinalIgnoreCase))
{
sb.AppendLine(Format(" " + method.Key + method.Value.Subfix()));
}
}
sb.AppendLine("""
};
}
""");
if (!Directory.Exists(outputPath)) { Directory.CreateDirectory(outputPath); }
var fileName = outputPath / "generated_callsites.g.h";
File.WriteAllText(fileName, sb.ToString());
Logger.Information("CallSite definitions File saved: {File}", fileName);
string Format(string line)
{
return $"(WCHAR*)WStr(\"{line.Replace("\"", "\\\"")}\"),";
}
}
internal static TargetFrameworks GetCategory(TargetFramework tfm)
{
return (TargetFrameworks)Enum.Parse<TargetFrameworks>(tfm.ToString().ToUpper().Replace('.', '_'));
}
internal record AspectClass
{
public AspectClass() {}
public Dictionary<string, Aspect> Aspects = new Dictionary<string, Aspect>();
public InstrumentationCategory Categories = InstrumentationCategory.Iast;
public string Subfix()
{
return $" {((long)Categories).ToString()}";
}
}
internal record Aspect
{
public Aspect() { }
public TargetFrameworks Tfms = TargetFrameworks.None;
public string Subfix()
{
return $" {((long)Tfms).ToString()}";
}
}
}
}