xref: /aosp_15_r20/external/cronet/base/process/process_handle_win.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
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 <winternl.h>
10 
11 #include <ostream>
12 
13 #include "base/check.h"
14 
15 namespace base {
16 
GetCurrentProcId()17 ProcessId GetCurrentProcId() {
18   return ::GetCurrentProcessId();
19 }
20 
GetCurrentProcessHandle()21 ProcessHandle GetCurrentProcessHandle() {
22   return ::GetCurrentProcess();
23 }
24 
GetProcId(ProcessHandle process)25 ProcessId GetProcId(ProcessHandle process) {
26   if (process == base::kNullProcessHandle)
27     return 0;
28   // This returns 0 if we have insufficient rights to query the process handle.
29   // Invalid handles or non-process handles will cause a hard failure.
30   ProcessId result = GetProcessId(process);
31   CHECK(result != 0 || GetLastError() != ERROR_INVALID_HANDLE)
32       << "process handle = " << process;
33   return result;
34 }
35 
36 // Local definition to include InheritedFromUniqueProcessId which contains a
37 // unique identifier for the parent process. See documentation at:
38 // https://learn.microsoft.com/en-us/windows/win32/api/winternl/nf-winternl-ntqueryinformationprocess
39 typedef struct _PROCESS_BASIC_INFORMATION {
40   PVOID Reserved1;
41   PPEB PebBaseAddress;
42   PVOID Reserved2[2];
43   ULONG_PTR UniqueProcessId;
44   ULONG_PTR InheritedFromUniqueProcessId;
45 } PROCESS_BASIC_INFORMATION;
46 
GetParentProcessId(ProcessHandle process)47 ProcessId GetParentProcessId(ProcessHandle process) {
48   HINSTANCE ntdll = GetModuleHandle(L"ntdll.dll");
49   decltype(NtQueryInformationProcess)* nt_query_information_process =
50       reinterpret_cast<decltype(NtQueryInformationProcess)*>(
51           GetProcAddress(ntdll, "NtQueryInformationProcess"));
52   if (!nt_query_information_process) {
53     return 0u;
54   }
55 
56   PROCESS_BASIC_INFORMATION pbi = {};
57   // TODO(zijiehe): To match other platforms, -1 (UINT32_MAX) should be returned
58   // if the parent process id cannot be found.
59   ProcessId pid = 0u;
60   if (NT_SUCCESS(nt_query_information_process(process, ProcessBasicInformation,
61                                               &pbi, sizeof(pbi), nullptr))) {
62     pid = static_cast<ProcessId>(pbi.InheritedFromUniqueProcessId);
63   }
64 
65   return pid;
66 }
67 
68 }  // namespace base
69