这段代码有时会引发以下异常:
"尝试读取或写入受保护的内存。这通常是其他内存已损坏的指示"
private static TOKEN_GROUPS GetTokenGroups(IntPtr tokenHandle)
{
var groups = new TOKEN_GROUPS();
uint tokenInfoLength = 0;
uint returnLength;
var res = GetTokenInformation(tokenHandle, TOKEN_INFORMATION_CLASS.TokenGroups, IntPtr.Zero,
tokenInfoLength, out returnLength);
if (!res && returnLength > 0)
{
tokenInfoLength = returnLength;
var tokenInfo = Marshal.AllocHGlobal((int) tokenInfoLength);
res = GetTokenInformation(tokenHandle,
TOKEN_INFORMATION_CLASS.TokenGroups,
tokenInfo,
tokenInfoLength,
out returnLength);
if(res)
{
groups = (TOKEN_GROUPS)Marshal.PtrToStructure(tokenInfo, typeof (TOKEN_GROUPS));
}
Marshal.FreeHGlobal(tokenInfo);
CloseHandle(tokenHandle);
}
else
{
var error = new Win32Exception(Marshal.GetLastWin32Error());
_log.WarnFormat("Failed evaluate the call to get process token information. {0}", error.Message);
}
return groups;
}
出错的代码行是groups = (TOKEN_GROUPS)Marshal.PtrToStructure(tokenInfo, typeof (TOKEN_GROUPS));
我会说异常在每20次调用此方法时发生一次。一旦开始发生,之后的每次调用都会抛出异常。重新启动进程会使错误消失。
IntPtr tokenHandle
的结果是:
var processId = GetCurrentProcess();
_log.InfoFormat("Process ID [{0}]", processId.ToString());
if (processId != IntPtr.Zero)
{
IntPtr tokenHandle;
if (OpenProcessToken(processId, TOKEN_READ, out tokenHandle))
{
groups = GetTokenGroups(tokenHandle);
}
编辑 希望这不会是信息过载,以下是pinvoke声明:
struct TOKEN_GROUPS
{
public uint GroupCount;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4000)]
public SID_AND_ATTRIBUTES[] Groups;
}
[StructLayout(LayoutKind.Sequential)]
struct SID_AND_ATTRIBUTES
{
public IntPtr SID;
public uint Attributes;
}
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool GetTokenInformation(
IntPtr TokenHandle,
TOKEN_INFORMATION_CLASS TokenInformationClass,
IntPtr TokenInformation,
uint TokenInformationLength,
out uint ReturnLength);
[DllImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool OpenProcessToken(IntPtr ProcessHandle,
UInt32 DesiredAccess, out IntPtr TokenHandle);
[DllImport("kernel32.dll")]
static extern IntPtr GetCurrentProcess();
enum TOKEN_INFORMATION_CLASS
{
TokenUser = 1,
TokenGroups,
TokenPrivileges,
TokenOwner,
TokenPrimaryGroup,
TokenDefaultDacl,
TokenSource,
TokenType,
TokenImpersonationLevel,
TokenStatistics,
TokenRestrictedSids,
TokenSessionId,
TokenGroupsAndPrivileges,
TokenSessionReference,
TokenSandBoxInert,
TokenAuditPolicy,
TokenOrigin
}