aboutsummaryrefslogtreecommitdiff
path: root/src/zenutil/openprocesscache.cpp
blob: 88bbce8a6d3d99a5fa6032cbc07bf455dc8f1c84 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
// Copyright Epic Games, Inc. All Rights Reserved.

#include "zenutil/openprocesscache.h"
#include <zencore/fmtutils.h>
#include <zencore/logging.h>
#include <zencore/memory/llm.h>

#if ZEN_PLATFORM_WINDOWS
#	include <zencore/windows.h>
#else
#	include <sys/mman.h>
#endif

//////////////////////////////////////////////////////////////////////////

namespace zen {

const FLLMTag&
GetProcCacheTag()
{
	static FLLMTag CacheHttpTag("proccache");

	return CacheHttpTag;
}

OpenProcessCache::OpenProcessCache()
#if ZEN_PLATFORM_WINDOWS
: m_GcThread(&OpenProcessCache::GcWorker, this)
#endif	// ZEN_PLATFORM_WINDOWS
{
}

OpenProcessCache::~OpenProcessCache()
{
#if ZEN_PLATFORM_WINDOWS
	try
	{
		m_GcExitEvent.Set();
		if (m_GcThread.joinable())
		{
			m_GcThread.join();
		}
		RwLock::ExclusiveLockScope Lock(m_SessionsLock);
		for (const auto& It : m_Sessions)
		{
			if (It.second.ProcessHandle == nullptr)
			{
				continue;
			}
			CloseHandle(It.second.ProcessHandle);
		}
		m_Sessions.clear();
	}
	catch (const std::exception& Ex)
	{
		ZEN_ERROR("OpenProcessCache destructor failed with reason: `{}`", Ex.what());
	}
#endif	// ZEN_PLATFORM_WINDOWS
}

void*
OpenProcessCache::GetProcessHandle(Oid SessionId, int ProcessPid)
{
	if (ProcessPid == 0)
	{
		return nullptr;
	}
	if (SessionId == Oid::Zero)
	{
		return nullptr;
	}

	ZEN_MEMSCOPE(GetProcCacheTag());

#if ZEN_PLATFORM_WINDOWS
	ZEN_ASSERT(ProcessPid != 0);
	{
		RwLock::SharedLockScope Lock(m_SessionsLock);

		if (auto It = m_Sessions.find(SessionId); It != m_Sessions.end())
		{
			if (ProcessPid == It->second.ProcessPid)
			{
				void* ProcessHandle = It->second.ProcessHandle;
				if (ProcessHandle == nullptr)
				{
					// Session is stale, just ignore it
					return nullptr;
				}
				DWORD ExitCode = 0;
				GetExitCodeProcess(ProcessHandle, &ExitCode);
				if (ExitCode == STILL_ACTIVE)
				{
					return ProcessHandle;
				}
			}
		}
	}
	void* ProcessHandle = nullptr;
	void* DeadHandle	= nullptr;
	{
		// Add/replace the session

		RwLock::ExclusiveLockScope Lock(m_SessionsLock);
		if (auto It = m_Sessions.find(SessionId); It != m_Sessions.end())
		{
			// Check to see if someone beat us to it...
			if ((It->second.ProcessHandle != nullptr) && (ProcessPid == It->second.ProcessPid))
			{
				DWORD ExitCode = 0;
				GetExitCodeProcess(It->second.ProcessHandle, &ExitCode);
				if (ExitCode == STILL_ACTIVE)
				{
					return It->second.ProcessHandle;
				}
			}

			ZEN_INFO("Purging stale target process pid {} for session: {}", It->second.ProcessPid, SessionId, It->second.ProcessHandle);
			DeadHandle = It->second.ProcessHandle;
			m_Sessions.erase(It);
		}

		// Cache new handle
		ProcessHandle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_DUP_HANDLE, FALSE, ProcessPid);
		ZEN_INFO("Opened target process pid {} for session {}: {}", ProcessPid, SessionId, ProcessHandle == nullptr ? "failed" : "success");
		m_Sessions.insert_or_assign(SessionId, Process{.ProcessPid = ProcessPid, .ProcessHandle = ProcessHandle});
	}

	if (DeadHandle != nullptr)
	{
		CloseHandle(DeadHandle);
	}
	return ProcessHandle;

#else	// ZEN_PLATFORM_WINDOWS
	ZEN_UNUSED(SessionId);
	return nullptr;
#endif	// ZEN_PLATFORM_WINDOWS
}

#if ZEN_PLATFORM_WINDOWS
void
OpenProcessCache::GCHandles()
{
	std::vector<void*> DeadHandles;
	{
		std::vector<Oid>		   DeadSessions;
		RwLock::ExclusiveLockScope Lock(m_SessionsLock);
		for (auto& It : m_Sessions)
		{
			if (It.second.ProcessHandle == nullptr)
			{
				// Stale session, remove it on second pass of GC
				DeadSessions.push_back(It.first);
				continue;
			}
			ZEN_ASSERT(It.second.ProcessPid != 0);
			DWORD ExitCode = 0;
			GetExitCodeProcess(It.second.ProcessHandle, &ExitCode);
			if (ExitCode == STILL_ACTIVE)
			{
				continue;
			}
			ZEN_INFO("GC stale target process pid {} for session {}: {}", It.second.ProcessPid, It.first, It.second.ProcessHandle);
			DeadHandles.push_back(It.second.ProcessHandle);

			// We just mark the session as "dead" for one GC pass to avoid re-opening a stale process
			It.second.ProcessHandle = nullptr;
		}
		for (auto SessionId : DeadSessions)
		{
			ZEN_INFO("Purging stale target process cache for session: {}", SessionId);
			m_Sessions.erase(SessionId);
		}
	}

	for (auto Handle : DeadHandles)
	{
		CloseHandle(Handle);
	}
}

void
OpenProcessCache::GcWorker()
{
	ZEN_MEMSCOPE(GetProcCacheTag());

	SetCurrentThreadName("ProcessCache_GC");

	while (!m_GcExitEvent.Wait(500))
	{
		try
		{
			GCHandles();
		}
		catch (const std::exception& Ex)
		{
			ZEN_ERROR("gc of open process cache failed with reason: `{}`", Ex.what());
		}
	}
}
#endif	// ZEN_PLATFORM_WINDOWS

}  // namespace zen