title: WinAPI: OpenProcess() returns error 5 with SeDebugPrivilege enabled for host process
body: <p>I've got a routine where I process-walk to obtain the <code>HANDLE</code> of each process as I 'walk' down the list (which works fine), but my issue lies when I do:</p>
  
  <p><code>HANDLE h = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe32.th32ProcessID)</code> where <code>PROCESS_ALL_ACCESS</code> is the access token, handle inheritance is set to <code>FALSE</code>, and pe32 is a <code>PROCESSENTRY32</code> </p>
  
  <p><code>GetLastError()</code> returns error code 5, and all the handles that are made are addresses which do not correspond to any appropriate process in Spy++32/64 (I've tried building the application under both platform targets, but as you'd expect, the result is the same).</p>
  
  <hr>
  
  <p>The code for setting SeDebugPrivilege for the host process which I'm using is:</p>
  
  <pre><code>BOOL EnableDebugPrivilege(BOOL bEnable)
  {
      HANDLE hToken = nullptr;
      LUID luid;
  
      if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &amp;hToken)) return FALSE;
      if (!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &amp;luid)) return FALSE;
  
      TOKEN_PRIVILEGES tokenPriv;
      tokenPriv.PrivilegeCount = 1;
      tokenPriv.Privileges[0].Luid = luid;
      tokenPriv.Privileges[0].Attributes = bEnable ? SE_PRIVILEGE_ENABLED : 0;
  
      if (!AdjustTokenPrivileges(hToken, FALSE, &amp;tokenPriv, sizeof(TOKEN_PRIVILEGES), NULL, NULL)) return FALSE;
  
      return TRUE;
  }
  </code></pre>
  
  <hr>
  
  <p>Some questions that would be helpful to you:</p>
  
  <ol>
  <li>I'm running Windows 7 x64 Professional.</li>
  <li>Yes, devenv.exe is started with "Run as Administrator" privileges, which means that the debugger and the application itself are started under the same affinity. </li>
  <li>I have tried toggling UAC or running the application with UAC off altogether. Still error code 5.</li>
  <li>I just attempted doing it with <code>PROCESS_QUERY_LIMITED_INFORMATION</code> and I receive error code 6, or <code>ERROR_INVALID_HANDLE</code>. Also attempted with <code>PROCESS_QUERY_INFORMATION | PROCESS_VM_READ</code>, result is error 5 again.</li>
  <li><code>SeDebugPrivilege</code> is enabled, verified with SysInternals' Process Explorer. Additionally, all processes that spawn from devenv/whatever the debugger is called inherit SeDebugPrivilege so...this is weird. </li>
  </ol>
  
  <p>Thank you all very much for your time, I'm reaching wits end with this issue :S</p>