forked from microsoft/CsWinRT
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExceptionHelpers.cs
More file actions
531 lines (477 loc) · 21.4 KB
/
ExceptionHelpers.cs
File metadata and controls
531 lines (477 loc) · 21.4 KB
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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using WinRT.Interop;
namespace WinRT
{
#if EMBED
internal
#else
public
#endif
static unsafe class ExceptionHelpers
{
private const int COR_E_OBJECTDISPOSED = unchecked((int)0x80131622);
private const int RO_E_CLOSED = unchecked((int)0x80000013);
internal const int E_BOUNDS = unchecked((int)0x8000000b);
internal const int E_CHANGED_STATE = unchecked((int)0x8000000c);
private const int E_ILLEGAL_STATE_CHANGE = unchecked((int)0x8000000d);
private const int E_ILLEGAL_METHOD_CALL = unchecked((int)0x8000000e);
private const int E_ILLEGAL_DELEGATE_ASSIGNMENT = unchecked((int)0x80000018);
private const int APPMODEL_ERROR_NO_PACKAGE = unchecked((int)0x80073D54);
internal const int E_XAMLPARSEFAILED = unchecked((int)0x802B000A);
internal const int E_LAYOUTCYCLE = unchecked((int)0x802B0014);
internal const int E_ELEMENTNOTENABLED = unchecked((int)0x802B001E);
internal const int E_ELEMENTNOTAVAILABLE = unchecked((int)0x802B001F);
internal const int ERROR_INVALID_WINDOW_HANDLE = unchecked((int)0x80070578);
[DllImport("oleaut32.dll")]
private static extern int SetErrorInfo(uint dwReserved, IntPtr perrinfo);
private static delegate* unmanaged[Stdcall]<out IntPtr, int> getRestrictedErrorInfo;
private static delegate* unmanaged[Stdcall]<IntPtr, int> setRestrictedErrorInfo;
private static delegate* unmanaged[Stdcall]<int, IntPtr, IntPtr, int> roOriginateLanguageException;
private static delegate* unmanaged[Stdcall]<IntPtr, int> roReportUnhandledError;
private static readonly bool initialized = Initialize();
private static bool Initialize()
{
IntPtr winRTErrorModule = Platform.LoadLibraryExW("api-ms-win-core-winrt-error-l1-1-1.dll", IntPtr.Zero, (uint)DllImportSearchPath.System32);
if (winRTErrorModule != IntPtr.Zero)
{
roOriginateLanguageException = (delegate* unmanaged[Stdcall]<int, IntPtr, IntPtr, int>)Platform.GetProcAddress(winRTErrorModule, "RoOriginateLanguageException");
roReportUnhandledError = (delegate* unmanaged[Stdcall]<IntPtr, int>)Platform.GetProcAddress(winRTErrorModule, "RoReportUnhandledError");
}
else
{
winRTErrorModule = Platform.LoadLibraryExW("api-ms-win-core-winrt-error-l1-1-0.dll", IntPtr.Zero, (uint)DllImportSearchPath.System32);
}
if (winRTErrorModule != IntPtr.Zero)
{
getRestrictedErrorInfo = (delegate* unmanaged[Stdcall]<out IntPtr, int>)Platform.GetProcAddress(winRTErrorModule, "GetRestrictedErrorInfo");
setRestrictedErrorInfo = (delegate* unmanaged[Stdcall]<IntPtr, int>)Platform.GetProcAddress(winRTErrorModule, "SetRestrictedErrorInfo");
}
return true;
}
public static void ThrowExceptionForHR(int hr)
{
if (hr < 0)
{
Throw(hr);
}
static void Throw(int hr)
{
Exception ex = GetExceptionForHR(hr, useGlobalErrorState: true, out bool restoredExceptionFromGlobalState);
if (restoredExceptionFromGlobalState)
{
ExceptionDispatchInfo.Capture(ex).Throw();
}
else
{
throw ex;
}
}
}
public static Exception GetExceptionForHR(int hr) => hr >= 0 ? null : GetExceptionForHR(hr, true, out _);
private static Exception GetExceptionForHR(int hr, bool useGlobalErrorState, out bool restoredExceptionFromGlobalState)
{
restoredExceptionFromGlobalState = false;
ObjectReference<ABI.WinRT.Interop.IErrorInfo.Vftbl> iErrorInfo = null;
IObjectReference restrictedErrorInfoToSave = null;
Exception ex;
string description = null;
string restrictedError = null;
string restrictedErrorReference = null;
string restrictedCapabilitySid = null;
bool hasOtherLanguageException = false;
if (useGlobalErrorState && getRestrictedErrorInfo != null)
{
Marshal.ThrowExceptionForHR(getRestrictedErrorInfo(out IntPtr restrictedErrorInfoPtr));
if (restrictedErrorInfoPtr != IntPtr.Zero)
{
IObjectReference restrictedErrorInfoRef = ObjectReference<ABI.WinRT.Interop.IRestrictedErrorInfo.Vftbl>.Attach(ref restrictedErrorInfoPtr);
restrictedErrorInfoToSave = restrictedErrorInfoRef.As<ABI.WinRT.Interop.IRestrictedErrorInfo.Vftbl>();
ABI.WinRT.Interop.IRestrictedErrorInfo restrictedErrorInfo = new ABI.WinRT.Interop.IRestrictedErrorInfo(restrictedErrorInfoRef);
restrictedErrorInfo.GetErrorDetails(out description, out int hrLocal, out restrictedError, out restrictedCapabilitySid);
restrictedErrorReference = restrictedErrorInfo.GetReference();
if (restrictedErrorInfoRef.TryAs<ABI.WinRT.Interop.ILanguageExceptionErrorInfo.Vftbl>(out var languageErrorInfoRef) >= 0)
{
ILanguageExceptionErrorInfo languageErrorInfo = new ABI.WinRT.Interop.ILanguageExceptionErrorInfo(languageErrorInfoRef);
using IObjectReference languageException = languageErrorInfo.GetLanguageException();
if (languageException is object)
{
if (languageException.IsReferenceToManagedObject)
{
ex = ComWrappersSupport.FindObject<Exception>(languageException.ThisPtr);
if (GetHRForException(ex) == hr)
{
restoredExceptionFromGlobalState = true;
return ex;
}
}
else
{
hasOtherLanguageException = true;
}
}
}
else
{
if (hr == hrLocal)
{
restrictedErrorInfoRef.TryAs<ABI.WinRT.Interop.IErrorInfo.Vftbl>(out iErrorInfo);
}
}
}
}
using (iErrorInfo)
{
switch (hr)
{
case E_ILLEGAL_STATE_CHANGE:
case E_ILLEGAL_METHOD_CALL:
case E_ILLEGAL_DELEGATE_ASSIGNMENT:
case APPMODEL_ERROR_NO_PACKAGE:
ex = new InvalidOperationException(description);
break;
case E_XAMLPARSEFAILED:
ex = new Microsoft.UI.Xaml.Markup.XamlParseException();
break;
case E_LAYOUTCYCLE:
ex = new Microsoft.UI.Xaml.LayoutCycleException();
break;
case E_ELEMENTNOTAVAILABLE:
ex = new Microsoft.UI.Xaml.Automation.ElementNotAvailableException();
break;
case E_ELEMENTNOTENABLED:
ex = new Microsoft.UI.Xaml.Automation.ElementNotEnabledException();
break;
case ERROR_INVALID_WINDOW_HANDLE:
ex = new System.Runtime.InteropServices.COMException(
@"Invalid window handle. (0x80070578)
Consider WindowNative, InitializeWithWindow
See https://aka.ms/cswinrt/interop#windows-sdk",
ERROR_INVALID_WINDOW_HANDLE);
break;
default:
ex = Marshal.GetExceptionForHR(hr, iErrorInfo?.ThisPtr ?? (IntPtr)(-1));
break;
}
}
ex.AddExceptionDataForRestrictedErrorInfo(
description,
restrictedError,
restrictedErrorReference,
restrictedCapabilitySid,
restrictedErrorInfoToSave,
hasOtherLanguageException);
return ex;
}
public static unsafe void SetErrorInfo(Exception ex)
{
if (getRestrictedErrorInfo != null && setRestrictedErrorInfo != null && roOriginateLanguageException != null)
{
// If the exception has information for an IRestrictedErrorInfo, use that
// as our error so as to propagate the error through WinRT end-to-end.
if (ex.TryGetRestrictedLanguageErrorObject(out var restrictedErrorObject))
{
using (restrictedErrorObject)
{
setRestrictedErrorInfo(restrictedErrorObject.ThisPtr);
}
}
else
{
string message = ex.Message;
if (string.IsNullOrEmpty(message))
{
message = ex.GetType().FullName;
}
IntPtr hstring;
if (Platform.WindowsCreateString(message, message.Length, &hstring) != 0)
{
hstring = IntPtr.Zero;
}
using var managedExceptionWrapper = ComWrappersSupport.CreateCCWForObject(ex);
roOriginateLanguageException(GetHRForException(ex), hstring, managedExceptionWrapper.ThisPtr);
}
}
else
{
using var iErrorInfo = ComWrappersSupport.CreateCCWForObject(new ManagedExceptionErrorInfo(ex));
SetErrorInfo(0, iErrorInfo.ThisPtr);
}
}
public static void ReportUnhandledError(Exception ex)
{
SetErrorInfo(ex);
if (getRestrictedErrorInfo != null && roReportUnhandledError != null)
{
Marshal.ThrowExceptionForHR(getRestrictedErrorInfo(out IntPtr ppRestrictedErrorInfo));
using var restrictedErrorRef = ObjectReference<IUnknownVftbl>.Attach(ref ppRestrictedErrorInfo);
roReportUnhandledError(restrictedErrorRef.ThisPtr);
}
}
public static int GetHRForException(Exception ex)
{
int hr = ex.HResult;
if (ex.TryGetRestrictedLanguageErrorObject(out var restrictedErrorObject))
{
restrictedErrorObject.AsType<ABI.WinRT.Interop.IRestrictedErrorInfo>().GetErrorDetails(out _, out hr, out _, out _);
}
if (hr == COR_E_OBJECTDISPOSED)
{
return RO_E_CLOSED;
}
return hr;
}
//
// Exception requires anything to be added into Data dictionary is serializable
// This wrapper is made serializable to satisfy this requirement but does NOT serialize
// the object and simply ignores it during serialization, because we only need
// the exception instance in the app to hold the error object alive.
//
[Serializable]
internal sealed class __RestrictedErrorObject
{
// Hold the error object instance but don't serialize/deserialize it
[NonSerialized]
private readonly IObjectReference _realErrorObject;
internal __RestrictedErrorObject(IObjectReference errorObject)
{
_realErrorObject = errorObject;
}
public IObjectReference RealErrorObject
{
get
{
return _realErrorObject;
}
}
}
internal static void AddExceptionDataForRestrictedErrorInfo(
this Exception ex,
string description,
string restrictedError,
string restrictedErrorReference,
string restrictedCapabilitySid,
IObjectReference restrictedErrorObject,
bool hasRestrictedLanguageErrorObject = false)
{
IDictionary dict = ex.Data;
if (dict != null)
{
dict.Add("Description", description);
dict.Add("RestrictedDescription", restrictedError);
dict.Add("RestrictedErrorReference", restrictedErrorReference);
dict.Add("RestrictedCapabilitySid", restrictedCapabilitySid);
// Keep the error object alive so that user could retrieve error information
// using Data["RestrictedErrorReference"]
dict.Add("__RestrictedErrorObjectReference", restrictedErrorObject == null ? null : new __RestrictedErrorObject(restrictedErrorObject));
dict.Add("__HasRestrictedLanguageErrorObject", hasRestrictedLanguageErrorObject);
}
}
internal static bool TryGetRestrictedLanguageErrorObject(
this Exception ex,
out IObjectReference restrictedErrorObject)
{
restrictedErrorObject = null;
IDictionary dict = ex.Data;
if (dict != null && dict.Contains("__HasRestrictedLanguageErrorObject"))
{
if (dict.Contains("__RestrictedErrorObjectReference"))
{
if (dict["__RestrictedErrorObjectReference"] is __RestrictedErrorObject restrictedObject)
restrictedErrorObject = restrictedObject.RealErrorObject;
}
return (bool)dict["__HasRestrictedLanguageErrorObject"]!;
}
return false;
}
public static Exception AttachRestrictedErrorInfo(Exception e)
{
// If there is no exception, then the restricted error info doesn't apply to it
if (e != null)
{
try
{
// Get the restricted error info for this thread and see if it may correlate to the current
// exception object. Note that in general the thread's IRestrictedErrorInfo is not meant for
// exceptions that are marshaled Windows.Foundation.HResults and instead are intended for
// HRESULT ABI return values. However, in many cases async APIs will set the thread's restricted
// error info as a convention in order to provide extended debugging information for the ErrorCode
// property.
Marshal.ThrowExceptionForHR(getRestrictedErrorInfo(out IntPtr restrictedErrorInfoPtr));
if (restrictedErrorInfoPtr != IntPtr.Zero)
{
IObjectReference restrictedErrorInfoRef = ObjectReference<ABI.WinRT.Interop.IRestrictedErrorInfo.Vftbl>.Attach(ref restrictedErrorInfoPtr);
ABI.WinRT.Interop.IRestrictedErrorInfo restrictedErrorInfo = new ABI.WinRT.Interop.IRestrictedErrorInfo(restrictedErrorInfoRef);
restrictedErrorInfo.GetErrorDetails(out string description,
out int restrictedErrorInfoHResult,
out string restrictedDescription,
out string capabilitySid);
// Since this is a special case where by convention there may be a correlation, there is not a
// guarantee that the restricted error info does belong to the async error code. In order to
// reduce the risk that we associate incorrect information with the exception object, we need
// to apply a heuristic where we attempt to match the current exception's HRESULT with the
// HRESULT the IRestrictedErrorInfo belongs to. If it is a match we will assume association
// for the IAsyncInfo case.
if (e.HResult == restrictedErrorInfoHResult)
{
e.AddExceptionDataForRestrictedErrorInfo(description,
restrictedDescription,
restrictedErrorInfo.GetReference(),
capabilitySid,
restrictedErrorInfoRef.As<ABI.WinRT.Interop.IRestrictedErrorInfo.Vftbl>());
}
}
}
catch
{
// If we can't get the restricted error info, then proceed as if it isn't associated with this
// error.
}
}
return e;
}
}
#if EMBED
internal
#else
public
#endif
static class ExceptionExtensions
{
public static void SetHResult(this Exception ex, int value)
{
ex.GetType().GetProperty("HResult").SetValue(ex, value);
}
internal static Exception GetExceptionForHR(this Exception innerException, int hresult, string messageResource)
{
Exception e;
if (innerException != null)
{
string message = innerException.Message ?? messageResource;
e = new Exception(message, innerException);
}
else
{
e = new Exception(messageResource);
}
e.SetHResult(hresult);
return e;
}
}
}
namespace Microsoft.UI.Xaml
{
using System.Runtime.Serialization;
namespace Automation
{
[Serializable]
#if EMBED
internal
#else
public
#endif
class ElementNotAvailableException : Exception
{
public ElementNotAvailableException()
: base("The element is not available.")
{
HResult = WinRT.ExceptionHelpers.E_ELEMENTNOTAVAILABLE;
}
public ElementNotAvailableException(string message)
: base(message)
{
HResult = WinRT.ExceptionHelpers.E_ELEMENTNOTAVAILABLE;
}
public ElementNotAvailableException(string message, Exception innerException)
: base(message, innerException)
{
HResult = WinRT.ExceptionHelpers.E_ELEMENTNOTAVAILABLE;
}
protected ElementNotAvailableException(SerializationInfo serializationInfo, StreamingContext streamingContext)
: base(serializationInfo, streamingContext)
{
}
}
#if EMBED
internal
#else
public
#endif
class ElementNotEnabledException : Exception
{
public ElementNotEnabledException()
: base("The element is not enabled.")
{
HResult = WinRT.ExceptionHelpers.E_ELEMENTNOTENABLED;
}
public ElementNotEnabledException(string message)
: base(message)
{
HResult = WinRT.ExceptionHelpers.E_ELEMENTNOTENABLED;
}
public ElementNotEnabledException(string message, Exception innerException)
: base(message, innerException)
{
HResult = WinRT.ExceptionHelpers.E_ELEMENTNOTENABLED;
}
}
}
namespace Markup
{
#if EMBED
internal
#else
public
#endif
class XamlParseException : Exception
{
public XamlParseException()
: base("XAML parsing failed.")
{
HResult = WinRT.ExceptionHelpers.E_XAMLPARSEFAILED;
}
public XamlParseException(string message)
: base(message)
{
HResult = WinRT.ExceptionHelpers.E_XAMLPARSEFAILED;
}
public XamlParseException(string message, Exception innerException)
: base(message, innerException)
{
HResult = WinRT.ExceptionHelpers.E_XAMLPARSEFAILED;
}
}
}
[Serializable]
#if EMBED
internal
#else
public
#endif
class LayoutCycleException : Exception
{
public LayoutCycleException()
: base("A cycle occurred while laying out the GUI.")
{
HResult = WinRT.ExceptionHelpers.E_LAYOUTCYCLE;
}
public LayoutCycleException(string message)
: base(message)
{
HResult = WinRT.ExceptionHelpers.E_LAYOUTCYCLE;
}
public LayoutCycleException(string message, Exception innerException)
: base(message, innerException)
{
HResult = WinRT.ExceptionHelpers.E_LAYOUTCYCLE;
}
protected LayoutCycleException(SerializationInfo serializationInfo, StreamingContext streamingContext)
: base(serializationInfo, streamingContext)
{
}
}
}