1 /* GIO - GLib Input, Output and Streaming Library
2 *
3 * Copyright 2022 Red Hat, Inc.
4 *
5 * SPDX-License-Identifier: LGPL-2.1-or-later
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General
18 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "config.h"
22
23 #include "gmemorymonitor.h"
24 #include "gioerror.h"
25 #include "ginitable.h"
26 #include "giomodule-priv.h"
27 #include "glibintl.h"
28 #include "glib/gstdio.h"
29 #include "gcancellable.h"
30
31 #include <windows.h>
32
33 #define G_TYPE_MEMORY_MONITOR_WIN32 (g_memory_monitor_win32_get_type ())
34 G_DECLARE_FINAL_TYPE (GMemoryMonitorWin32, g_memory_monitor_win32, G, MEMORY_MONITOR_WIN32, GObject)
35
36 #define G_MEMORY_MONITOR_WIN32_GET_INITABLE_IFACE(o) (G_TYPE_INSTANCE_GET_INTERFACE ((o), G_TYPE_INITABLE, GInitable))
37
38 static void g_memory_monitor_win32_iface_init (GMemoryMonitorInterface *iface);
39 static void g_memory_monitor_win32_initable_iface_init (GInitableIface *iface);
40
41 struct _GMemoryMonitorWin32
42 {
43 GObject parent_instance;
44
45 HANDLE event;
46 HANDLE mem;
47 HANDLE thread;
48 };
49
50 G_DEFINE_TYPE_WITH_CODE (GMemoryMonitorWin32, g_memory_monitor_win32, G_TYPE_OBJECT,
51 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
52 g_memory_monitor_win32_initable_iface_init)
53 G_IMPLEMENT_INTERFACE (G_TYPE_MEMORY_MONITOR,
54 g_memory_monitor_win32_iface_init)
55 _g_io_modules_ensure_extension_points_registered ();
56 g_io_extension_point_implement (G_MEMORY_MONITOR_EXTENSION_POINT_NAME,
57 g_define_type_id,
58 "win32",
59 30))
60
61 static void
62 g_memory_monitor_win32_init (GMemoryMonitorWin32 *win32)
63 {
64 }
65
66 static gboolean
67 watch_handler (gpointer user_data)
68 {
69 GMemoryMonitorWin32 *win32 = user_data;
70
71 g_signal_emit_by_name (win32, "low-memory-warning",
72 G_MEMORY_MONITOR_WARNING_LEVEL_LOW);
73
74 return G_SOURCE_REMOVE;
75 }
76
77 /* Thread which watches for win32 memory resource events */
78 static DWORD WINAPI
79 watch_thread_function (LPVOID parameter)
80 {
81 GWeakRef *weak_ref = parameter;
82 GMemoryMonitorWin32 *win32 = NULL;
83 HANDLE handles[2] = { 0, };
84 DWORD result;
85 BOOL low_memory_state;
86
87 win32 = g_weak_ref_get (weak_ref);
88 if (!win32)
89 goto end;
90
91 if (!DuplicateHandle (GetCurrentProcess (),
92 win32->event,
93 GetCurrentProcess (),
94 &handles[0],
95 0,
96 FALSE,
97 DUPLICATE_SAME_ACCESS))
98 {
99 gchar *emsg;
100
101 emsg = g_win32_error_message (GetLastError ());
102 g_debug ("DuplicateHandle failed: %s", emsg);
103 g_free (emsg);
104 goto end;
105 }
106
107 if (!DuplicateHandle (GetCurrentProcess (),
108 win32->mem,
109 GetCurrentProcess (),
110 &handles[1],
111 0,
112 FALSE,
113 DUPLICATE_SAME_ACCESS))
114 {
115 gchar *emsg;
116
117 emsg = g_win32_error_message (GetLastError ());
118 g_debug ("DuplicateHandle failed: %s", emsg);
119 g_free (emsg);
120 goto end;
121 }
122
123 g_clear_object (&win32);
124
125 while (1)
126 {
127 if (!QueryMemoryResourceNotification (handles[1], &low_memory_state))
128 {
129 gchar *emsg;
130
131 emsg = g_win32_error_message (GetLastError ());
132 g_debug ("QueryMemoryResourceNotification failed: %s", emsg);
133 g_free (emsg);
134 break;
135 }
136
137 win32 = g_weak_ref_get (weak_ref);
138 if (!win32)
139 break;
140
141 if (low_memory_state)
142 {
143 g_idle_add_full (G_PRIORITY_DEFAULT,
144 watch_handler,
145 g_steal_pointer (&win32),
146 g_object_unref);
147 /* throttle a bit the loop */
148 g_usleep (G_USEC_PER_SEC);
149 continue;
150 }
151
152 g_clear_object (&win32);
153
154 result = WaitForMultipleObjects (G_N_ELEMENTS (handles), handles, FALSE, INFINITE);
155 switch (result)
156 {
157 case WAIT_OBJECT_0 + 1:
158 continue;
159
160 case WAIT_FAILED:
161 {
162 gchar *emsg;
163
164 emsg = g_win32_error_message (GetLastError ());
165 g_debug ("WaitForMultipleObjects failed: %s", emsg);
166 g_free (emsg);
167 }
168 G_GNUC_FALLTHROUGH;
169 default:
170 goto end;
171 }
172 }
173
174 end:
175 if (handles[0])
176 CloseHandle (handles[0]);
177 if (handles[1])
178 CloseHandle (handles[1]);
179 g_clear_object (&win32);
180 g_weak_ref_clear (weak_ref);
181 g_free (weak_ref);
182 return 0;
183 }
184
185 static gboolean
186 g_memory_monitor_win32_initable_init (GInitable *initable,
187 GCancellable *cancellable,
188 GError **error)
189 {
190 GMemoryMonitorWin32 *win32 = G_MEMORY_MONITOR_WIN32 (initable);
191 GWeakRef *weak_ref = NULL;
192
193 win32->event = CreateEvent (NULL, FALSE, FALSE, NULL);
194 if (win32->event == NULL)
195 {
196 g_set_error_literal (error, G_IO_ERROR, g_io_error_from_errno (GetLastError ()),
197 "Failed to create event");
198 return FALSE;
199 }
200
201 win32->mem = CreateMemoryResourceNotification (LowMemoryResourceNotification);
202 if (win32->mem == NULL)
203 {
204 g_set_error_literal (error, G_IO_ERROR, g_io_error_from_errno (GetLastError ()),
205 "Failed to create resource notification handle");
206 return FALSE;
207 }
208
209 weak_ref = g_new0 (GWeakRef, 1);
210 g_weak_ref_init (weak_ref, win32);
211 /* Use CreateThread (not GThread) with a small stack to make it more lightweight. */
212 win32->thread = CreateThread (NULL, 1024, watch_thread_function, weak_ref, 0, NULL);
213 if (win32->thread == NULL)
214 {
215 g_set_error_literal (error, G_IO_ERROR, g_io_error_from_errno (GetLastError ()),
216 "Failed to create memory resource notification thread");
217 g_weak_ref_clear (weak_ref);
218 g_free (weak_ref);
219 return FALSE;
220 }
221
222 return TRUE;
223 }
224
225 static void
226 g_memory_monitor_win32_finalize (GObject *object)
227 {
228 GMemoryMonitorWin32 *win32 = G_MEMORY_MONITOR_WIN32 (object);
229
230 if (win32->thread)
231 {
232 SetEvent (win32->event);
233 WaitForSingleObject (win32->thread, INFINITE);
234 CloseHandle (win32->thread);
235 }
236
237 if (win32->event)
238 CloseHandle (win32->event);
239
240 if (win32->mem)
241 CloseHandle (win32->mem);
242
243 G_OBJECT_CLASS (g_memory_monitor_win32_parent_class)->finalize (object);
244 }
245
246 static void
247 g_memory_monitor_win32_class_init (GMemoryMonitorWin32Class *nl_class)
248 {
249 GObjectClass *gobject_class = G_OBJECT_CLASS (nl_class);
250
251 gobject_class->finalize = g_memory_monitor_win32_finalize;
252 }
253
254 static void
255 g_memory_monitor_win32_iface_init (GMemoryMonitorInterface *monitor_iface)
256 {
257 }
258
259 static void
260 g_memory_monitor_win32_initable_iface_init (GInitableIface *iface)
261 {
262 iface->init = g_memory_monitor_win32_initable_init;
263 }