public TlsContents()
{
int error = 0;
int cachingError = 0;
bool success = true;
if (processHandle.IsInvalid)
{
lock (syncRoot)
{
if (processHandle.IsInvalid)
{
SafeTokenHandle localProcessHandle;
if (false == Interop.mincore.OpenProcessToken(
Interop.mincore.GetCurrentProcess(),
TokenAccessLevels.Duplicate,
out localProcessHandle))
{
cachingError = Marshal.GetLastWin32Error();
success = false;
}
processHandle = localProcessHandle;
}
}
}
try
{
// Make the sequence non-interruptible
}
finally
{
try
{
//
// Open the thread token; if there is no thread token, get one from
// the process token by impersonating self.
//
SafeTokenHandle threadHandleBefore = this.threadHandle;
error = FCall.OpenThreadToken(
TokenAccessLevels.Query | TokenAccessLevels.AdjustPrivileges,
WinSecurityContext.Process,
out this.threadHandle);
unchecked { error &= ~(int)0x80070000; }
if (error != 0)
{
if (success == true)
{
this.threadHandle = threadHandleBefore;
if (error != Interop.mincore.Errors.ERROR_NO_TOKEN)
{
success = false;
}
System.Diagnostics.Debug.Assert(this.isImpersonating == false, "Incorrect isImpersonating state");
if (success == true)
{
error = 0;
if (false == Interop.mincore.DuplicateTokenEx(
processHandle,
TokenAccessLevels.Impersonate | TokenAccessLevels.Query | TokenAccessLevels.AdjustPrivileges,
IntPtr.Zero,
Interop.mincore.SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation,
System.Security.Principal.TokenType.TokenImpersonation,
ref this.threadHandle))
{
error = Marshal.GetLastWin32Error();
success = false;
}
}
if (success == true)
{
error = FCall.SetThreadToken(this.threadHandle);
unchecked { error &= ~(int)0x80070000; }
if (error != 0)
{
success = false;
}
}
if (success == true)
{
this.isImpersonating = true;
}
}
else
{
error = cachingError;
}
}
else
{
success = true;
}
}
finally
{
if (!success)
{
Dispose();
}
}
}
if (error == Interop.mincore.Errors.ERROR_NOT_ENOUGH_MEMORY)
{
throw new OutOfMemoryException();
}
else if (error == Interop.mincore.Errors.ERROR_ACCESS_DENIED ||
error == Interop.mincore.Errors.ERROR_CANT_OPEN_ANONYMOUS)
{
throw new UnauthorizedAccessException();
}
else if (error != 0)
{
System.Diagnostics.Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "WindowsIdentity.GetCurrentThreadToken() failed with unrecognized error code {0}", error));
throw new InvalidOperationException();
}
}