Merge pull request #3144 from Unity-Technologies/fix-recursive-property-call
[mono.git] / mcs / class / referencesource / System.Web / Util / ExecutionContextUtil.cs
1 //------------------------------------------------------------------------------
2 // <copyright file="ExecutionContextUtil.cs" company="Microsoft">
3 //     Copyright (c) Microsoft Corporation.  All rights reserved.
4 // </copyright>                                                                
5 //------------------------------------------------------------------------------
6
7 namespace System.Web.Util {
8     using System;
9     using System.Reflection;
10     using System.Security.Permissions;
11     using System.Threading;
12
13     // This class contains utility methods for dealing with security contexts when crossing AppDomain boundaries.
14
15     [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)]
16     internal static class ExecutionContextUtil {
17
18         private static readonly ContextCallback s_actionToActionObjShunt = obj => ((Action)obj)();
19         private static readonly ExecutionContext s_dummyDefaultEC = GetDummyDefaultEC();
20
21         [ReflectionPermission(SecurityAction.Assert, MemberAccess = true)]
22         private static ExecutionContext GetDummyDefaultEC() {
23             // The ExecutionContext.PreAllocatedDefault property is special-cased by ExecutionContext to be a blank context and to allow multiple invocation.
24             PropertyInfo propInfo = typeof(ExecutionContext).GetProperty("PreAllocatedDefault", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
25
26             if (propInfo == null) {
27                 throw new Exception(SR.GetString(SR.Type_doesnt_have_property, typeof(ExecutionContext).FullName, "PreAllocatedDefault"));
28             }
29
30             return (ExecutionContext) propInfo.GetValue(null, null);
31         }
32
33         // Removes all context associated with the current thread (call context, IPrincipal, etc.) and invokes the provided callback.
34         // The intent of this method is to get any user-provided context off the current thread before crossing an AppDomain boundary,
35         // as the existence of that context could lead to behavioral problems (see DevDiv #205764) or security problems (see DevDiv #206598).
36         internal static void RunInNullExecutionContext(Action callback) {
37             ExecutionContext.Run(s_dummyDefaultEC, s_actionToActionObjShunt, callback);
38         }
39
40     }
41 }