-
Notifications
You must be signed in to change notification settings - Fork 107
/
GuidGenerator.cs
357 lines (304 loc) · 13.5 KB
/
GuidGenerator.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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
using WinRT.Interop;
namespace WinRT
{
#if EMBED
internal
#else
public
#endif
static class GuidGenerator
{
#if NET
[UnconditionalSuppressMessage("Trimming", "IL2067", Justification = "This method only accesses 'Type.GUID', no fields are ever needed.")]
#endif
public static Guid GetGUID(Type type)
{
type = type.GetGuidType();
// Only check the WUX/MUX types if the feature switch is set, to avoid introducing
// performance regressions in the standard case where MUX is targeted (default).
if (FeatureSwitches.UseWindowsUIXamlProjections)
{
if (TryGetWindowsUIXamlIID(type, out Guid iid))
{
return iid;
}
}
return type.GUID;
}
public static Guid GetIID(
#if NET
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)]
#endif
Type type)
{
type = type.GetGuidType();
// Same optional check as above
if (FeatureSwitches.UseWindowsUIXamlProjections)
{
if (TryGetWindowsUIXamlIID(type, out Guid iid))
{
return iid;
}
}
if (!type.IsGenericType)
{
return type.GUID;
}
return (Guid)type.GetField("PIID").GetValue(null);
}
internal static bool TryGetWindowsUIXamlIID(Type type, out Guid iid)
{
if (type == typeof(global::ABI.System.Collections.Specialized.INotifyCollectionChanged))
{
iid = IID.IID_WUX_INotifyCollectionChanged;
return true;
}
if (type == typeof(global::ABI.System.ComponentModel.INotifyPropertyChanged))
{
iid = IID.IID_WUX_INotifyPropertyChanged;
return true;
}
if (type == typeof(global::ABI.System.Collections.Specialized.NotifyCollectionChangedEventArgs))
{
iid = IID.IID_WUX_INotifyCollectionChangedEventArgs;
return true;
}
if (type == typeof(global::ABI.System.Collections.Specialized.NotifyCollectionChangedEventHandler))
{
iid = IID.IID_WUX_NotifyCollectionChangedEventHandler;
return true;
}
if (type == typeof(global::ABI.System.ComponentModel.PropertyChangedEventHandler))
{
iid = IID.IID_WUX_PropertyChangedEventHandler;
return true;
}
iid = default;
return false;
}
public static string GetSignature(
#if NET
// This '[DynamicallyAccessedMembers]' annotation is here just for backwards-compatibility with old projections. Those are
// not trim-safe, but we didn't want to break existing consumers that had code that happened to still work in this case.
// The only case where 'GetSignature' actually uses reflection is in that scenario, but when using updated projections, the
// generated attributes are always used instead, which are trim-safe. Therefore, it's safe to call this method suppressing
// the trim warning for the 'type' parameter if legacy projections are not a concern, or for a "best effort" support there.
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)]
#endif
Type type)
{
if (type == typeof(object))
{
return "cinterface(IInspectable)";
}
if (type == typeof(string))
{
return "string";
}
if (type == typeof(Type))
{
return ABI.System.Type.GetGuidSignature();
}
if (type.IsGenericType)
{
#if NET
[UnconditionalSuppressMessage("Trimming", "IL2062", Justification = "Fallback path for old projections, not trim-safe by design.")]
#endif
static string[] SelectSignaturesForTypes(Type[] types)
{
string[] signatures = new string[types.Length];
for (int i = 0; i < types.Length; i++)
{
signatures[i] = GetSignature(types[i]);
}
return signatures;
}
var args = SelectSignaturesForTypes(type.GetGenericArguments());
var genericHelperType = type.GetGenericTypeDefinition().FindHelperType() ?? type;
return "pinterface({" + genericHelperType.GUID + "};" + string.Join(";", args) + ")";
}
var helperType = type.FindHelperType();
if (helperType != null)
{
var sigMethod = helperType.GetMethod("GetGuidSignature", BindingFlags.Static | BindingFlags.Public);
if (sigMethod != null)
{
return (string)sigMethod.Invoke(null, null);
}
}
if (type.IsValueType)
{
switch (type.Name)
{
case "SByte": return "i1";
case "Byte": return "u1";
case "Int16": return "i2";
case "UInt16": return "u2";
case "Int32": return "i4";
case "UInt32": return "u4";
case "Int64": return "i8";
case "UInt64": return "u8";
case "Single": return "f4";
case "Double": return "f8";
case "Boolean": return "b1";
case "Char": return "c2";
case "Guid": return "g16";
default:
{
if (type.IsEnum)
{
var isFlags = type.IsDefined(typeof(FlagsAttribute));
return "enum(" + type.FullName + ";" + (isFlags ? "u4" : "i4") + ")";
}
if (!type.IsPrimitive)
{
var winrtTypeAttribute = type.GetCustomAttribute<WindowsRuntimeTypeAttribute>();
if (winrtTypeAttribute != null && !string.IsNullOrEmpty(winrtTypeAttribute.GuidSignature))
{
return winrtTypeAttribute.GuidSignature;
}
if (winrtTypeAttribute == null &&
(winrtTypeAttribute = type.GetAuthoringMetadataType()?.GetCustomAttribute<WindowsRuntimeTypeAttribute>()) != null &&
!string.IsNullOrEmpty(winrtTypeAttribute.GuidSignature))
{
return winrtTypeAttribute.GuidSignature;
}
#if NET
if (!RuntimeFeature.IsDynamicCodeCompiled)
{
throw new InvalidOperationException(
$"Cannot compute signature for type '{type}', as doing so requires a fallback path that is not trim/AOT " +
$"compatible. Using AOT requires all referenced projections to be up to date. Make sure to only reference " +
$"WinRT projections that have been generated by a version of CsWinRT supported for AOT.");
}
[UnconditionalSuppressMessage("Trimming", "IL2072", Justification = "Fallback path for old projections, not trim-safe by design.")]
#endif
static string[] SelectSignaturesForFields(FieldInfo[] fields)
{
string[] signatures = new string[fields.Length];
for (int i = 0; i < fields.Length; i++)
{
signatures[i] = GetSignature(fields[i].FieldType);
}
return signatures;
}
var args = SelectSignaturesForFields(type.GetFields(BindingFlags.Instance | BindingFlags.Public));
return "struct(" + type.FullName + ";" + string.Join(";", args) + ")";
}
throw new InvalidOperationException("Unsupported value type.");
}
}
}
// For authoring interfaces, we can use the metadata type or the helper type to get the guid.
// For built-in system interfaces that are custom type mapped, we use the helper type to get the guid.
// For others, either the type itself or the helper type has the same guid and can be used.
type = type.IsInterface ? (helperType ?? type) : type;
if (type.IsDelegate())
{
return "delegate({" + GetGUID(type) + "})";
}
#if NET
[UnconditionalSuppressMessage("Trimming", "IL2067", Justification = "'GetSignature' will only actually use reflection when using old projections.")]
#endif
static bool TryGetSignatureFromDefaultInterfaceTypeForRuntimeClassType(Type type, out string signature)
{
if (type.IsClass && Projections.TryGetDefaultInterfaceTypeForRuntimeClassType(type, out Type iface))
{
signature = "rc(" + type.FullName + ";" + GetSignature(iface) + ")";
return true;
}
signature = null;
return false;
}
if (TryGetSignatureFromDefaultInterfaceTypeForRuntimeClassType(type, out string signature))
{
return signature;
}
return "{" + type.GUID.ToString() + "}";
}
private static Guid encode_guid(Span<byte> data)
{
if (BitConverter.IsLittleEndian)
{
// swap bytes of int a
byte t = data[0];
data[0] = data[3];
data[3] = t;
t = data[1];
data[1] = data[2];
data[2] = t;
// swap bytes of short b
t = data[4];
data[4] = data[5];
data[5] = t;
// swap bytes of short c and encode rfc time/version field
t = data[6];
data[6] = data[7];
data[7] = (byte)((t & 0x0f) | (5 << 4));
// encode rfc clock/reserved field
data[8] = (byte)((data[8] & 0x3f) | 0x80);
}
#if !NET
return new Guid(data.Slice(0, 16).ToArray());
#else
return new Guid(data[0..16]);
#endif
}
private static readonly Guid wrt_pinterface_namespace = new(0xd57af411, 0x737b, 0xc042, 0xab, 0xae, 0x87, 0x8b, 0x1e, 0x16, 0xad, 0xee);
public static Guid CreateIID(
#if NET
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)]
#endif
Type type)
{
var sig = GetSignature(type);
if (!type.IsGenericType)
{
return new Guid(sig);
}
else
{
return CreateIIDForGenericType(sig);
}
}
/// <summary>
/// Gets the IID of a given type, just like <see cref="CreateIID(Type)"/>, but without rooting reflection metadata
/// for all public fields of that type. It can be used internally where we know that extra info is not actually needed.
/// </summary>
/// <param name="type">The type to get the IID for.</param>
/// <returns>The IID for <paramref name="type"/>.</returns>
#if NET
[UnconditionalSuppressMessage("Trimming", "IL2067", Justification = "This method is only used for types (eg. generics) where fields aren't needed.")]
#endif
internal static Guid CreateIIDUnsafe(Type type)
{
return CreateIID(type);
}
internal static Guid CreateIIDForGenericType(string signature)
{
#if !NET
var data = System.Linq.Enumerable.ToArray(System.Linq.Enumerable.Concat(wrt_pinterface_namespace.ToByteArray(), Encoding.UTF8.GetBytes(signature)));
using (SHA1 sha = new SHA1CryptoServiceProvider())
{
return encode_guid(sha.ComputeHash(data));
}
#else
var maxBytes = UTF8Encoding.UTF8.GetMaxByteCount(signature.Length);
var data = new byte[16 /* Number of bytes in a GUID */ + maxBytes];
Span<byte> dataSpan = data;
wrt_pinterface_namespace.TryWriteBytes(dataSpan);
var numBytes = UTF8Encoding.UTF8.GetBytes(signature, dataSpan[16..]);
data = data[..(16 + numBytes)];
return encode_guid(SHA1.HashData(data));
#endif
}
}
}