• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2013 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "base/process/process_handle.h"
6 
7 #include <windows.h>
8 
9 #include <tlhelp32.h>
10 
11 #include <ostream>
12 
13 #include "base/win/scoped_handle.h"
14 #include "base/win/windows_version.h"
15 
16 namespace base {
17 
GetCurrentProcId()18 ProcessId GetCurrentProcId() {
19   return ::GetCurrentProcessId();
20 }
21 
GetCurrentProcessHandle()22 ProcessHandle GetCurrentProcessHandle() {
23   return ::GetCurrentProcess();
24 }
25 
GetProcId(ProcessHandle process)26 ProcessId GetProcId(ProcessHandle process) {
27   if (process == base::kNullProcessHandle)
28     return 0;
29   // This returns 0 if we have insufficient rights to query the process handle.
30   // Invalid handles or non-process handles will cause a hard failure.
31   ProcessId result = GetProcessId(process);
32   CHECK(result != 0 || GetLastError() != ERROR_INVALID_HANDLE)
33       << "process handle = " << process;
34   return result;
35 }
36 
GetParentProcessId(ProcessHandle process)37 ProcessId GetParentProcessId(ProcessHandle process) {
38   ProcessId child_pid = GetProcId(process);
39   PROCESSENTRY32 process_entry;
40       process_entry.dwSize = sizeof(PROCESSENTRY32);
41 
42   win::ScopedHandle snapshot(CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0));
43   if (snapshot.is_valid() && Process32First(snapshot.get(), &process_entry)) {
44     do {
45       if (process_entry.th32ProcessID == child_pid)
46         return process_entry.th32ParentProcessID;
47     } while (Process32Next(snapshot.get(), &process_entry));
48   }
49 
50   // TODO(zijiehe): To match other platforms, -1 (UINT32_MAX) should be returned
51   // if |child_id| cannot be found in the |snapshot|.
52   return 0u;
53 }
54 
55 }  // namespace base
56