blob: 1b85d7dd7ee97f64ec0ad991c54f0d87510d6c89 [file] [log] [blame]
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001/*
2 * Support routines from the Windows API
3 *
4 * This module was originally created by merging PC/_subprocess.c with
5 * Modules/_multiprocessing/win32_functions.c.
6 *
7 * Copyright (c) 2004 by Fredrik Lundh <fredrik@pythonware.com>
8 * Copyright (c) 2004 by Secret Labs AB, http://www.pythonware.com
9 * Copyright (c) 2004 by Peter Astrand <astrand@lysator.liu.se>
10 *
11 * By obtaining, using, and/or copying this software and/or its
12 * associated documentation, you agree that you have read, understood,
13 * and will comply with the following terms and conditions:
14 *
15 * Permission to use, copy, modify, and distribute this software and
16 * its associated documentation for any purpose and without fee is
17 * hereby granted, provided that the above copyright notice appears in
18 * all copies, and that both that copyright notice and this permission
19 * notice appear in supporting documentation, and that the name of the
20 * authors not be used in advertising or publicity pertaining to
21 * distribution of the software without specific, written prior
22 * permission.
23 *
24 * THE AUTHORS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
25 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
26 * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
27 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
28 * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
29 * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
30 * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
31 *
32 */
33
34/* Licensed to PSF under a Contributor Agreement. */
35/* See http://www.python.org/2.4/license for licensing details. */
36
37#include "Python.h"
Victor Stinnercdad2722021-04-22 00:52:52 +020038#include "pycore_moduleobject.h" // _PyModule_GetState()
Victor Stinner4a21e572020-04-15 02:35:41 +020039#include "structmember.h" // PyMemberDef
Antoine Pitrou23bba4c2012-04-18 20:51:15 +020040
Mohamed Koubaae087f7c2020-08-13 09:22:48 -050041
Antoine Pitrou23bba4c2012-04-18 20:51:15 +020042#define WINDOWS_LEAN_AND_MEAN
43#include "windows.h"
44#include <crtdbg.h>
Tim Golden0321cf22014-05-05 19:46:17 +010045#include "winreparse.h"
Antoine Pitrou23bba4c2012-04-18 20:51:15 +020046
47#if defined(MS_WIN32) && !defined(MS_WIN64)
48#define HANDLE_TO_PYNUM(handle) \
49 PyLong_FromUnsignedLong((unsigned long) handle)
50#define PYNUM_TO_HANDLE(obj) ((HANDLE)PyLong_AsUnsignedLong(obj))
51#define F_POINTER "k"
52#define T_POINTER T_ULONG
53#else
54#define HANDLE_TO_PYNUM(handle) \
55 PyLong_FromUnsignedLongLong((unsigned long long) handle)
56#define PYNUM_TO_HANDLE(obj) ((HANDLE)PyLong_AsUnsignedLongLong(obj))
57#define F_POINTER "K"
58#define T_POINTER T_ULONGLONG
59#endif
60
61#define F_HANDLE F_POINTER
62#define F_DWORD "k"
Antoine Pitrou23bba4c2012-04-18 20:51:15 +020063
64#define T_HANDLE T_POINTER
65
66/* Grab CancelIoEx dynamically from kernel32 */
67static int has_CancelIoEx = -1;
68static BOOL (CALLBACK *Py_CancelIoEx)(HANDLE, LPOVERLAPPED);
69
70static int
71check_CancelIoEx()
72{
73 if (has_CancelIoEx == -1)
74 {
75 HINSTANCE hKernel32 = GetModuleHandle("KERNEL32");
76 * (FARPROC *) &Py_CancelIoEx = GetProcAddress(hKernel32,
77 "CancelIoEx");
78 has_CancelIoEx = (Py_CancelIoEx != NULL);
79 }
80 return has_CancelIoEx;
81}
82
Mohamed Koubaae087f7c2020-08-13 09:22:48 -050083typedef struct {
84 PyTypeObject *overlapped_type;
85} WinApiState;
86
87static inline WinApiState*
88winapi_get_state(PyObject *module)
89{
Victor Stinnercdad2722021-04-22 00:52:52 +020090 void *state = _PyModule_GetState(module);
Mohamed Koubaae087f7c2020-08-13 09:22:48 -050091 assert(state != NULL);
92 return (WinApiState *)state;
93}
Antoine Pitrou23bba4c2012-04-18 20:51:15 +020094
95/*
96 * A Python object wrapping an OVERLAPPED structure and other useful data
97 * for overlapped I/O
98 */
99
100typedef struct {
101 PyObject_HEAD
102 OVERLAPPED overlapped;
103 /* For convenience, we store the file handle too */
104 HANDLE handle;
105 /* Whether there's I/O in flight */
106 int pending;
107 /* Whether I/O completed successfully */
108 int completed;
109 /* Buffer used for reading (optional) */
110 PyObject *read_buffer;
111 /* Buffer used for writing (optional) */
112 Py_buffer write_buffer;
113} OverlappedObject;
114
Ken Jin0d399512021-05-29 01:47:15 +0800115/*
116Note: tp_clear (overlapped_clear) is not implemented because it
117requires cancelling the IO operation if it's pending and the cancellation is
118quite complex and can fail (see: overlapped_dealloc).
119*/
120static int
121overlapped_traverse(OverlappedObject *self, visitproc visit, void *arg)
122{
123 Py_VISIT(self->read_buffer);
124 Py_VISIT(self->write_buffer.obj);
125 Py_VISIT(Py_TYPE(self));
126 return 0;
127}
128
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200129static void
130overlapped_dealloc(OverlappedObject *self)
131{
132 DWORD bytes;
133 int err = GetLastError();
Richard Oudkerk633db6f2013-11-17 13:15:51 +0000134
Ken Jin0d399512021-05-29 01:47:15 +0800135 PyObject_GC_UnTrack(self);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200136 if (self->pending) {
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200137 if (check_CancelIoEx() &&
Richard Oudkerk633db6f2013-11-17 13:15:51 +0000138 Py_CancelIoEx(self->handle, &self->overlapped) &&
139 GetOverlappedResult(self->handle, &self->overlapped, &bytes, TRUE))
140 {
141 /* The operation is no longer pending -- nothing to do. */
142 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600143 else if (_Py_IsFinalizing())
Richard Oudkerk633db6f2013-11-17 13:15:51 +0000144 {
145 /* The operation is still pending -- give a warning. This
146 will probably only happen on Windows XP. */
147 PyErr_SetString(PyExc_RuntimeError,
148 "I/O operations still in flight while destroying "
149 "Overlapped object, the process may crash");
150 PyErr_WriteUnraisable(NULL);
151 }
152 else
153 {
154 /* The operation is still pending, but the process is
155 probably about to exit, so we need not worry too much
156 about memory leaks. Leaking self prevents a potential
157 crash. This can happen when a daemon thread is cleaned
158 up at exit -- see #19565. We only expect to get here
159 on Windows XP. */
160 CloseHandle(self->overlapped.hEvent);
161 SetLastError(err);
162 return;
163 }
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200164 }
Richard Oudkerk633db6f2013-11-17 13:15:51 +0000165
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200166 CloseHandle(self->overlapped.hEvent);
167 SetLastError(err);
168 if (self->write_buffer.obj)
169 PyBuffer_Release(&self->write_buffer);
170 Py_CLEAR(self->read_buffer);
Mohamed Koubaae087f7c2020-08-13 09:22:48 -0500171 PyTypeObject *tp = Py_TYPE(self);
172 tp->tp_free(self);
173 Py_DECREF(tp);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200174}
175
Zachary Waref2244ea2015-05-13 01:22:54 -0500176/*[clinic input]
177module _winapi
178class _winapi.Overlapped "OverlappedObject *" "&OverlappedType"
179[clinic start generated code]*/
180/*[clinic end generated code: output=da39a3ee5e6b4b0d input=c13d3f5fd1dabb84]*/
181
182/*[python input]
183def create_converter(type_, format_unit):
184 name = type_ + '_converter'
185 # registered upon creation by CConverter's metaclass
186 type(name, (CConverter,), {'type': type_, 'format_unit': format_unit})
187
188# format unit differs between platforms for these
189create_converter('HANDLE', '" F_HANDLE "')
190create_converter('HMODULE', '" F_HANDLE "')
191create_converter('LPSECURITY_ATTRIBUTES', '" F_POINTER "')
Davin Pottse895de32019-02-23 22:08:16 -0600192create_converter('LPCVOID', '" F_POINTER "')
Zachary Waref2244ea2015-05-13 01:22:54 -0500193
194create_converter('BOOL', 'i') # F_BOOL used previously (always 'i')
195create_converter('DWORD', 'k') # F_DWORD is always "k" (which is much shorter)
196create_converter('LPCTSTR', 's')
Zachary Waref2244ea2015-05-13 01:22:54 -0500197create_converter('UINT', 'I') # F_UINT used previously (always 'I')
198
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +0300199class LPCWSTR_converter(Py_UNICODE_converter):
200 type = 'LPCWSTR'
201
Zachary Waref2244ea2015-05-13 01:22:54 -0500202class HANDLE_return_converter(CReturnConverter):
203 type = 'HANDLE'
204
205 def render(self, function, data):
206 self.declare(data)
207 self.err_occurred_if("_return_value == INVALID_HANDLE_VALUE", data)
208 data.return_conversion.append(
Serhiy Storchaka5dee6552016-06-09 16:16:06 +0300209 'if (_return_value == NULL) {\n Py_RETURN_NONE;\n}\n')
Zachary Waref2244ea2015-05-13 01:22:54 -0500210 data.return_conversion.append(
211 'return_value = HANDLE_TO_PYNUM(_return_value);\n')
212
213class DWORD_return_converter(CReturnConverter):
214 type = 'DWORD'
215
216 def render(self, function, data):
217 self.declare(data)
Victor Stinner850a18e2017-10-24 16:53:32 -0700218 self.err_occurred_if("_return_value == PY_DWORD_MAX", data)
Zachary Waref2244ea2015-05-13 01:22:54 -0500219 data.return_conversion.append(
220 'return_value = Py_BuildValue("k", _return_value);\n')
Davin Pottse895de32019-02-23 22:08:16 -0600221
222class LPVOID_return_converter(CReturnConverter):
223 type = 'LPVOID'
224
225 def render(self, function, data):
226 self.declare(data)
227 self.err_occurred_if("_return_value == NULL", data)
228 data.return_conversion.append(
229 'return_value = HANDLE_TO_PYNUM(_return_value);\n')
Zachary Waref2244ea2015-05-13 01:22:54 -0500230[python start generated code]*/
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +0300231/*[python end generated code: output=da39a3ee5e6b4b0d input=011ee0c3a2244bfe]*/
Zachary Waref2244ea2015-05-13 01:22:54 -0500232
233#include "clinic/_winapi.c.h"
234
235/*[clinic input]
236_winapi.Overlapped.GetOverlappedResult
237
238 wait: bool
239 /
240[clinic start generated code]*/
241
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200242static PyObject *
Zachary Waref2244ea2015-05-13 01:22:54 -0500243_winapi_Overlapped_GetOverlappedResult_impl(OverlappedObject *self, int wait)
244/*[clinic end generated code: output=bdd0c1ed6518cd03 input=194505ee8e0e3565]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200245{
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200246 BOOL res;
247 DWORD transferred = 0;
248 DWORD err;
249
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200250 Py_BEGIN_ALLOW_THREADS
251 res = GetOverlappedResult(self->handle, &self->overlapped, &transferred,
252 wait != 0);
253 Py_END_ALLOW_THREADS
254
255 err = res ? ERROR_SUCCESS : GetLastError();
256 switch (err) {
257 case ERROR_SUCCESS:
258 case ERROR_MORE_DATA:
259 case ERROR_OPERATION_ABORTED:
260 self->completed = 1;
261 self->pending = 0;
262 break;
263 case ERROR_IO_INCOMPLETE:
264 break;
265 default:
266 self->pending = 0;
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +0300267 return PyErr_SetExcFromWindowsErr(PyExc_OSError, err);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200268 }
269 if (self->completed && self->read_buffer != NULL) {
270 assert(PyBytes_CheckExact(self->read_buffer));
271 if (transferred != PyBytes_GET_SIZE(self->read_buffer) &&
272 _PyBytes_Resize(&self->read_buffer, transferred))
273 return NULL;
274 }
275 return Py_BuildValue("II", (unsigned) transferred, (unsigned) err);
276}
277
Zachary Waref2244ea2015-05-13 01:22:54 -0500278/*[clinic input]
279_winapi.Overlapped.getbuffer
280[clinic start generated code]*/
281
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200282static PyObject *
Zachary Waref2244ea2015-05-13 01:22:54 -0500283_winapi_Overlapped_getbuffer_impl(OverlappedObject *self)
284/*[clinic end generated code: output=95a3eceefae0f748 input=347fcfd56b4ceabd]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200285{
286 PyObject *res;
287 if (!self->completed) {
288 PyErr_SetString(PyExc_ValueError,
289 "can't get read buffer before GetOverlappedResult() "
290 "signals the operation completed");
291 return NULL;
292 }
293 res = self->read_buffer ? self->read_buffer : Py_None;
294 Py_INCREF(res);
295 return res;
296}
297
Zachary Waref2244ea2015-05-13 01:22:54 -0500298/*[clinic input]
299_winapi.Overlapped.cancel
300[clinic start generated code]*/
301
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200302static PyObject *
Zachary Waref2244ea2015-05-13 01:22:54 -0500303_winapi_Overlapped_cancel_impl(OverlappedObject *self)
304/*[clinic end generated code: output=fcb9ab5df4ebdae5 input=cbf3da142290039f]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200305{
306 BOOL res = TRUE;
307
308 if (self->pending) {
309 Py_BEGIN_ALLOW_THREADS
310 if (check_CancelIoEx())
311 res = Py_CancelIoEx(self->handle, &self->overlapped);
312 else
313 res = CancelIo(self->handle);
314 Py_END_ALLOW_THREADS
315 }
316
317 /* CancelIoEx returns ERROR_NOT_FOUND if the I/O completed in-between */
318 if (!res && GetLastError() != ERROR_NOT_FOUND)
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +0300319 return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200320 self->pending = 0;
321 Py_RETURN_NONE;
322}
323
324static PyMethodDef overlapped_methods[] = {
Zachary Waref2244ea2015-05-13 01:22:54 -0500325 _WINAPI_OVERLAPPED_GETOVERLAPPEDRESULT_METHODDEF
326 _WINAPI_OVERLAPPED_GETBUFFER_METHODDEF
327 _WINAPI_OVERLAPPED_CANCEL_METHODDEF
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200328 {NULL}
329};
330
331static PyMemberDef overlapped_members[] = {
332 {"event", T_HANDLE,
333 offsetof(OverlappedObject, overlapped) + offsetof(OVERLAPPED, hEvent),
334 READONLY, "overlapped event handle"},
335 {NULL}
336};
337
Mohamed Koubaae087f7c2020-08-13 09:22:48 -0500338static PyType_Slot winapi_overlapped_type_slots[] = {
Ken Jin0d399512021-05-29 01:47:15 +0800339 {Py_tp_traverse, overlapped_traverse},
Mohamed Koubaae087f7c2020-08-13 09:22:48 -0500340 {Py_tp_dealloc, overlapped_dealloc},
341 {Py_tp_doc, "OVERLAPPED structure wrapper"},
342 {Py_tp_methods, overlapped_methods},
343 {Py_tp_members, overlapped_members},
344 {0,0}
345};
346
347static PyType_Spec winapi_overlapped_type_spec = {
348 .name = "_winapi.Overlapped",
349 .basicsize = sizeof(OverlappedObject),
Ken Jin0d399512021-05-29 01:47:15 +0800350 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_DISALLOW_INSTANTIATION |
Miss Islington (bot)7297d742021-06-17 03:19:44 -0700351 Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_IMMUTABLETYPE),
Mohamed Koubaae087f7c2020-08-13 09:22:48 -0500352 .slots = winapi_overlapped_type_slots,
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200353};
354
355static OverlappedObject *
Mohamed Koubaae087f7c2020-08-13 09:22:48 -0500356new_overlapped(PyObject *module, HANDLE handle)
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200357{
Mohamed Koubaae087f7c2020-08-13 09:22:48 -0500358 WinApiState *st = winapi_get_state(module);
Ken Jin0d399512021-05-29 01:47:15 +0800359 OverlappedObject *self = PyObject_GC_New(OverlappedObject, st->overlapped_type);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200360 if (!self)
361 return NULL;
Mohamed Koubaae087f7c2020-08-13 09:22:48 -0500362
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200363 self->handle = handle;
364 self->read_buffer = NULL;
365 self->pending = 0;
366 self->completed = 0;
367 memset(&self->overlapped, 0, sizeof(OVERLAPPED));
368 memset(&self->write_buffer, 0, sizeof(Py_buffer));
369 /* Manual reset, initially non-signalled */
370 self->overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
Ken Jin0d399512021-05-29 01:47:15 +0800371
372 PyObject_GC_Track(self);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200373 return self;
374}
375
376/* -------------------------------------------------------------------- */
377/* windows API functions */
378
Zachary Waref2244ea2015-05-13 01:22:54 -0500379/*[clinic input]
380_winapi.CloseHandle
381
382 handle: HANDLE
383 /
384
385Close handle.
386[clinic start generated code]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200387
388static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300389_winapi_CloseHandle_impl(PyObject *module, HANDLE handle)
390/*[clinic end generated code: output=7ad37345f07bd782 input=7f0e4ac36e0352b8]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200391{
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200392 BOOL success;
393
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200394 Py_BEGIN_ALLOW_THREADS
Zachary Waref2244ea2015-05-13 01:22:54 -0500395 success = CloseHandle(handle);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200396 Py_END_ALLOW_THREADS
397
398 if (!success)
399 return PyErr_SetFromWindowsErr(0);
400
401 Py_RETURN_NONE;
402}
403
Zachary Waref2244ea2015-05-13 01:22:54 -0500404/*[clinic input]
405_winapi.ConnectNamedPipe
406
407 handle: HANDLE
Serhiy Storchaka202fda52017-03-12 10:10:47 +0200408 overlapped as use_overlapped: bool(accept={int}) = False
Zachary Waref2244ea2015-05-13 01:22:54 -0500409[clinic start generated code]*/
410
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200411static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300412_winapi_ConnectNamedPipe_impl(PyObject *module, HANDLE handle,
Zachary Ware77772c02015-05-13 10:58:35 -0500413 int use_overlapped)
Serhiy Storchaka202fda52017-03-12 10:10:47 +0200414/*[clinic end generated code: output=335a0e7086800671 input=34f937c1c86e5e68]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200415{
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200416 BOOL success;
417 OverlappedObject *overlapped = NULL;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200418
419 if (use_overlapped) {
Mohamed Koubaae087f7c2020-08-13 09:22:48 -0500420 overlapped = new_overlapped(module, handle);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200421 if (!overlapped)
422 return NULL;
423 }
424
425 Py_BEGIN_ALLOW_THREADS
Zachary Waref2244ea2015-05-13 01:22:54 -0500426 success = ConnectNamedPipe(handle,
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200427 overlapped ? &overlapped->overlapped : NULL);
428 Py_END_ALLOW_THREADS
429
430 if (overlapped) {
431 int err = GetLastError();
432 /* Overlapped ConnectNamedPipe never returns a success code */
433 assert(success == 0);
434 if (err == ERROR_IO_PENDING)
435 overlapped->pending = 1;
436 else if (err == ERROR_PIPE_CONNECTED)
437 SetEvent(overlapped->overlapped.hEvent);
438 else {
439 Py_DECREF(overlapped);
440 return PyErr_SetFromWindowsErr(err);
441 }
442 return (PyObject *) overlapped;
443 }
444 if (!success)
445 return PyErr_SetFromWindowsErr(0);
446
447 Py_RETURN_NONE;
448}
449
Zachary Waref2244ea2015-05-13 01:22:54 -0500450/*[clinic input]
451_winapi.CreateFile -> HANDLE
452
453 file_name: LPCTSTR
454 desired_access: DWORD
455 share_mode: DWORD
456 security_attributes: LPSECURITY_ATTRIBUTES
457 creation_disposition: DWORD
458 flags_and_attributes: DWORD
459 template_file: HANDLE
460 /
461[clinic start generated code]*/
462
463static HANDLE
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300464_winapi_CreateFile_impl(PyObject *module, LPCTSTR file_name,
Zachary Ware77772c02015-05-13 10:58:35 -0500465 DWORD desired_access, DWORD share_mode,
466 LPSECURITY_ATTRIBUTES security_attributes,
467 DWORD creation_disposition,
468 DWORD flags_and_attributes, HANDLE template_file)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300469/*[clinic end generated code: output=417ddcebfc5a3d53 input=6423c3e40372dbd5]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200470{
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200471 HANDLE handle;
472
Steve Dowerb82e17e2019-05-23 08:45:22 -0700473 if (PySys_Audit("_winapi.CreateFile", "uIIII",
474 file_name, desired_access, share_mode,
475 creation_disposition, flags_and_attributes) < 0) {
476 return INVALID_HANDLE_VALUE;
477 }
478
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200479 Py_BEGIN_ALLOW_THREADS
Zachary Waref2244ea2015-05-13 01:22:54 -0500480 handle = CreateFile(file_name, desired_access,
481 share_mode, security_attributes,
482 creation_disposition,
483 flags_and_attributes, template_file);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200484 Py_END_ALLOW_THREADS
485
486 if (handle == INVALID_HANDLE_VALUE)
Zachary Waref2244ea2015-05-13 01:22:54 -0500487 PyErr_SetFromWindowsErr(0);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200488
Zachary Waref2244ea2015-05-13 01:22:54 -0500489 return handle;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200490}
491
Zachary Waref2244ea2015-05-13 01:22:54 -0500492/*[clinic input]
Davin Pottse895de32019-02-23 22:08:16 -0600493_winapi.CreateFileMapping -> HANDLE
494
495 file_handle: HANDLE
496 security_attributes: LPSECURITY_ATTRIBUTES
497 protect: DWORD
498 max_size_high: DWORD
499 max_size_low: DWORD
500 name: LPCWSTR
501 /
502[clinic start generated code]*/
503
504static HANDLE
505_winapi_CreateFileMapping_impl(PyObject *module, HANDLE file_handle,
506 LPSECURITY_ATTRIBUTES security_attributes,
507 DWORD protect, DWORD max_size_high,
508 DWORD max_size_low, LPCWSTR name)
509/*[clinic end generated code: output=6c0a4d5cf7f6fcc6 input=3dc5cf762a74dee8]*/
510{
511 HANDLE handle;
512
513 Py_BEGIN_ALLOW_THREADS
514 handle = CreateFileMappingW(file_handle, security_attributes,
515 protect, max_size_high, max_size_low,
516 name);
517 Py_END_ALLOW_THREADS
518
519 if (handle == NULL) {
Zackery Spytzeda385c2019-05-30 01:58:50 -0600520 PyObject *temp = PyUnicode_FromWideChar(name, -1);
521 PyErr_SetExcFromWindowsErrWithFilenameObject(PyExc_OSError, 0, temp);
522 Py_XDECREF(temp);
Davin Pottse895de32019-02-23 22:08:16 -0600523 handle = INVALID_HANDLE_VALUE;
524 }
525
526 return handle;
527}
528
529/*[clinic input]
Zachary Waref2244ea2015-05-13 01:22:54 -0500530_winapi.CreateJunction
Tim Golden0321cf22014-05-05 19:46:17 +0100531
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +0300532 src_path: LPCWSTR
533 dst_path: LPCWSTR
Zachary Waref2244ea2015-05-13 01:22:54 -0500534 /
535[clinic start generated code]*/
536
537static PyObject *
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +0300538_winapi_CreateJunction_impl(PyObject *module, LPCWSTR src_path,
539 LPCWSTR dst_path)
540/*[clinic end generated code: output=44b3f5e9bbcc4271 input=963d29b44b9384a7]*/
Zachary Waref2244ea2015-05-13 01:22:54 -0500541{
Tim Golden0321cf22014-05-05 19:46:17 +0100542 /* Privilege adjustment */
543 HANDLE token = NULL;
544 TOKEN_PRIVILEGES tp;
545
546 /* Reparse data buffer */
547 const USHORT prefix_len = 4;
548 USHORT print_len = 0;
549 USHORT rdb_size = 0;
Martin Panter70214ad2016-08-04 02:38:59 +0000550 _Py_PREPARSE_DATA_BUFFER rdb = NULL;
Tim Golden0321cf22014-05-05 19:46:17 +0100551
552 /* Junction point creation */
553 HANDLE junction = NULL;
554 DWORD ret = 0;
555
Tim Golden0321cf22014-05-05 19:46:17 +0100556 if (src_path == NULL || dst_path == NULL)
557 return PyErr_SetFromWindowsErr(ERROR_INVALID_PARAMETER);
558
559 if (wcsncmp(src_path, L"\\??\\", prefix_len) == 0)
560 return PyErr_SetFromWindowsErr(ERROR_INVALID_PARAMETER);
561
Steve Dowerb82e17e2019-05-23 08:45:22 -0700562 if (PySys_Audit("_winapi.CreateJunction", "uu", src_path, dst_path) < 0) {
563 return NULL;
564 }
565
Tim Golden0321cf22014-05-05 19:46:17 +0100566 /* Adjust privileges to allow rewriting directory entry as a
567 junction point. */
568 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &token))
569 goto cleanup;
570
571 if (!LookupPrivilegeValue(NULL, SE_RESTORE_NAME, &tp.Privileges[0].Luid))
572 goto cleanup;
573
574 tp.PrivilegeCount = 1;
575 tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
576 if (!AdjustTokenPrivileges(token, FALSE, &tp, sizeof(TOKEN_PRIVILEGES),
577 NULL, NULL))
578 goto cleanup;
579
580 if (GetFileAttributesW(src_path) == INVALID_FILE_ATTRIBUTES)
581 goto cleanup;
582
583 /* Store the absolute link target path length in print_len. */
584 print_len = (USHORT)GetFullPathNameW(src_path, 0, NULL, NULL);
585 if (print_len == 0)
586 goto cleanup;
587
588 /* NUL terminator should not be part of print_len. */
589 --print_len;
590
591 /* REPARSE_DATA_BUFFER usage is heavily under-documented, especially for
592 junction points. Here's what I've learned along the way:
593 - A junction point has two components: a print name and a substitute
594 name. They both describe the link target, but the substitute name is
595 the physical target and the print name is shown in directory listings.
596 - The print name must be a native name, prefixed with "\??\".
597 - Both names are stored after each other in the same buffer (the
598 PathBuffer) and both must be NUL-terminated.
599 - There are four members defining their respective offset and length
600 inside PathBuffer: SubstituteNameOffset, SubstituteNameLength,
601 PrintNameOffset and PrintNameLength.
602 - The total size we need to allocate for the REPARSE_DATA_BUFFER, thus,
603 is the sum of:
604 - the fixed header size (REPARSE_DATA_BUFFER_HEADER_SIZE)
605 - the size of the MountPointReparseBuffer member without the PathBuffer
606 - the size of the prefix ("\??\") in bytes
607 - the size of the print name in bytes
608 - the size of the substitute name in bytes
609 - the size of two NUL terminators in bytes */
Martin Panter70214ad2016-08-04 02:38:59 +0000610 rdb_size = _Py_REPARSE_DATA_BUFFER_HEADER_SIZE +
Tim Golden0321cf22014-05-05 19:46:17 +0100611 sizeof(rdb->MountPointReparseBuffer) -
612 sizeof(rdb->MountPointReparseBuffer.PathBuffer) +
613 /* Two +1's for NUL terminators. */
614 (prefix_len + print_len + 1 + print_len + 1) * sizeof(WCHAR);
Andy Lester7668a8b2020-03-24 23:26:44 -0500615 rdb = (_Py_PREPARSE_DATA_BUFFER)PyMem_RawCalloc(1, rdb_size);
Tim Golden0321cf22014-05-05 19:46:17 +0100616 if (rdb == NULL)
617 goto cleanup;
618
Tim Golden0321cf22014-05-05 19:46:17 +0100619 rdb->ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
Martin Panter70214ad2016-08-04 02:38:59 +0000620 rdb->ReparseDataLength = rdb_size - _Py_REPARSE_DATA_BUFFER_HEADER_SIZE;
Tim Golden0321cf22014-05-05 19:46:17 +0100621 rdb->MountPointReparseBuffer.SubstituteNameOffset = 0;
622 rdb->MountPointReparseBuffer.SubstituteNameLength =
623 (prefix_len + print_len) * sizeof(WCHAR);
624 rdb->MountPointReparseBuffer.PrintNameOffset =
625 rdb->MountPointReparseBuffer.SubstituteNameLength + sizeof(WCHAR);
626 rdb->MountPointReparseBuffer.PrintNameLength = print_len * sizeof(WCHAR);
627
628 /* Store the full native path of link target at the substitute name
629 offset (0). */
630 wcscpy(rdb->MountPointReparseBuffer.PathBuffer, L"\\??\\");
631 if (GetFullPathNameW(src_path, print_len + 1,
632 rdb->MountPointReparseBuffer.PathBuffer + prefix_len,
633 NULL) == 0)
634 goto cleanup;
635
636 /* Copy everything but the native prefix to the print name offset. */
637 wcscpy(rdb->MountPointReparseBuffer.PathBuffer +
638 prefix_len + print_len + 1,
639 rdb->MountPointReparseBuffer.PathBuffer + prefix_len);
640
641 /* Create a directory for the junction point. */
642 if (!CreateDirectoryW(dst_path, NULL))
643 goto cleanup;
644
645 junction = CreateFileW(dst_path, GENERIC_READ | GENERIC_WRITE, 0, NULL,
646 OPEN_EXISTING,
647 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, NULL);
648 if (junction == INVALID_HANDLE_VALUE)
649 goto cleanup;
650
651 /* Make the directory entry a junction point. */
652 if (!DeviceIoControl(junction, FSCTL_SET_REPARSE_POINT, rdb, rdb_size,
653 NULL, 0, &ret, NULL))
654 goto cleanup;
655
656cleanup:
657 ret = GetLastError();
658
659 CloseHandle(token);
660 CloseHandle(junction);
661 PyMem_RawFree(rdb);
662
663 if (ret != 0)
664 return PyErr_SetFromWindowsErr(ret);
665
666 Py_RETURN_NONE;
667}
668
Zachary Waref2244ea2015-05-13 01:22:54 -0500669/*[clinic input]
670_winapi.CreateNamedPipe -> HANDLE
671
672 name: LPCTSTR
673 open_mode: DWORD
674 pipe_mode: DWORD
675 max_instances: DWORD
676 out_buffer_size: DWORD
677 in_buffer_size: DWORD
678 default_timeout: DWORD
679 security_attributes: LPSECURITY_ATTRIBUTES
680 /
681[clinic start generated code]*/
682
683static HANDLE
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300684_winapi_CreateNamedPipe_impl(PyObject *module, LPCTSTR name, DWORD open_mode,
685 DWORD pipe_mode, DWORD max_instances,
686 DWORD out_buffer_size, DWORD in_buffer_size,
687 DWORD default_timeout,
Zachary Ware77772c02015-05-13 10:58:35 -0500688 LPSECURITY_ATTRIBUTES security_attributes)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300689/*[clinic end generated code: output=80f8c07346a94fbc input=5a73530b84d8bc37]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200690{
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200691 HANDLE handle;
692
Steve Dowerb82e17e2019-05-23 08:45:22 -0700693 if (PySys_Audit("_winapi.CreateNamedPipe", "uII",
694 name, open_mode, pipe_mode) < 0) {
695 return INVALID_HANDLE_VALUE;
696 }
697
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200698 Py_BEGIN_ALLOW_THREADS
Zachary Waref2244ea2015-05-13 01:22:54 -0500699 handle = CreateNamedPipe(name, open_mode, pipe_mode,
700 max_instances, out_buffer_size,
701 in_buffer_size, default_timeout,
702 security_attributes);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200703 Py_END_ALLOW_THREADS
704
705 if (handle == INVALID_HANDLE_VALUE)
Zachary Waref2244ea2015-05-13 01:22:54 -0500706 PyErr_SetFromWindowsErr(0);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200707
Zachary Waref2244ea2015-05-13 01:22:54 -0500708 return handle;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200709}
710
Zachary Waref2244ea2015-05-13 01:22:54 -0500711/*[clinic input]
712_winapi.CreatePipe
713
714 pipe_attrs: object
715 Ignored internally, can be None.
716 size: DWORD
717 /
718
719Create an anonymous pipe.
720
721Returns a 2-tuple of handles, to the read and write ends of the pipe.
722[clinic start generated code]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200723
724static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300725_winapi_CreatePipe_impl(PyObject *module, PyObject *pipe_attrs, DWORD size)
726/*[clinic end generated code: output=1c4411d8699f0925 input=c4f2cfa56ef68d90]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200727{
728 HANDLE read_pipe;
729 HANDLE write_pipe;
730 BOOL result;
731
Steve Dowerb82e17e2019-05-23 08:45:22 -0700732 if (PySys_Audit("_winapi.CreatePipe", NULL) < 0) {
733 return NULL;
734 }
735
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200736 Py_BEGIN_ALLOW_THREADS
737 result = CreatePipe(&read_pipe, &write_pipe, NULL, size);
738 Py_END_ALLOW_THREADS
739
740 if (! result)
741 return PyErr_SetFromWindowsErr(GetLastError());
742
743 return Py_BuildValue(
744 "NN", HANDLE_TO_PYNUM(read_pipe), HANDLE_TO_PYNUM(write_pipe));
745}
746
747/* helpers for createprocess */
748
749static unsigned long
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200750getulong(PyObject* obj, const char* name)
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200751{
752 PyObject* value;
753 unsigned long ret;
754
755 value = PyObject_GetAttrString(obj, name);
756 if (! value) {
757 PyErr_Clear(); /* FIXME: propagate error? */
758 return 0;
759 }
760 ret = PyLong_AsUnsignedLong(value);
761 Py_DECREF(value);
762 return ret;
763}
764
765static HANDLE
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200766gethandle(PyObject* obj, const char* name)
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200767{
768 PyObject* value;
769 HANDLE ret;
770
771 value = PyObject_GetAttrString(obj, name);
772 if (! value) {
773 PyErr_Clear(); /* FIXME: propagate error? */
774 return NULL;
775 }
776 if (value == Py_None)
777 ret = NULL;
778 else
779 ret = PYNUM_TO_HANDLE(value);
780 Py_DECREF(value);
781 return ret;
782}
783
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +0200784static wchar_t *
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200785getenvironment(PyObject* environment)
786{
787 Py_ssize_t i, envsize, totalsize;
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +0200788 wchar_t *buffer = NULL, *p, *end;
789 PyObject *keys, *values;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200790
Ezio Melotti85a86292013-08-17 16:57:41 +0300791 /* convert environment dictionary to windows environment string */
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200792 if (! PyMapping_Check(environment)) {
793 PyErr_SetString(
794 PyExc_TypeError, "environment must be dictionary or None");
795 return NULL;
796 }
797
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200798 keys = PyMapping_Keys(environment);
Oren Milman0b3a87e2017-09-14 22:30:28 +0300799 if (!keys) {
800 return NULL;
801 }
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200802 values = PyMapping_Values(environment);
Oren Milman0b3a87e2017-09-14 22:30:28 +0300803 if (!values) {
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200804 goto error;
Oren Milman0b3a87e2017-09-14 22:30:28 +0300805 }
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200806
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +0200807 envsize = PyList_GET_SIZE(keys);
808 if (PyList_GET_SIZE(values) != envsize) {
Serhiy Storchakabf623ae2017-04-19 20:03:52 +0300809 PyErr_SetString(PyExc_RuntimeError,
810 "environment changed size during iteration");
811 goto error;
812 }
813
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200814 totalsize = 1; /* trailing null character */
815 for (i = 0; i < envsize; i++) {
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +0200816 PyObject* key = PyList_GET_ITEM(keys, i);
817 PyObject* value = PyList_GET_ITEM(values, i);
818 Py_ssize_t size;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200819
820 if (! PyUnicode_Check(key) || ! PyUnicode_Check(value)) {
821 PyErr_SetString(PyExc_TypeError,
822 "environment can only contain strings");
823 goto error;
824 }
Serhiy Storchakad174d242017-06-23 19:39:27 +0300825 if (PyUnicode_FindChar(key, '\0', 0, PyUnicode_GET_LENGTH(key), 1) != -1 ||
826 PyUnicode_FindChar(value, '\0', 0, PyUnicode_GET_LENGTH(value), 1) != -1)
827 {
828 PyErr_SetString(PyExc_ValueError, "embedded null character");
829 goto error;
830 }
831 /* Search from index 1 because on Windows starting '=' is allowed for
832 defining hidden environment variables. */
833 if (PyUnicode_GET_LENGTH(key) == 0 ||
834 PyUnicode_FindChar(key, '=', 1, PyUnicode_GET_LENGTH(key), 1) != -1)
835 {
836 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
837 goto error;
838 }
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +0200839
840 size = PyUnicode_AsWideChar(key, NULL, 0);
841 assert(size > 1);
842 if (totalsize > PY_SSIZE_T_MAX - size) {
Benjamin Peterson8ce68062015-02-09 20:58:12 -0500843 PyErr_SetString(PyExc_OverflowError, "environment too long");
844 goto error;
845 }
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +0200846 totalsize += size; /* including '=' */
847
848 size = PyUnicode_AsWideChar(value, NULL, 0);
849 assert(size > 0);
850 if (totalsize > PY_SSIZE_T_MAX - size) {
Benjamin Peterson8ce68062015-02-09 20:58:12 -0500851 PyErr_SetString(PyExc_OverflowError, "environment too long");
852 goto error;
853 }
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +0200854 totalsize += size; /* including trailing '\0' */
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200855 }
856
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +0200857 buffer = PyMem_NEW(wchar_t, totalsize);
Benjamin Peterson8ce68062015-02-09 20:58:12 -0500858 if (! buffer) {
859 PyErr_NoMemory();
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200860 goto error;
Benjamin Peterson8ce68062015-02-09 20:58:12 -0500861 }
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200862 p = buffer;
863 end = buffer + totalsize;
864
865 for (i = 0; i < envsize; i++) {
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +0200866 PyObject* key = PyList_GET_ITEM(keys, i);
867 PyObject* value = PyList_GET_ITEM(values, i);
868 Py_ssize_t size = PyUnicode_AsWideChar(key, p, end - p);
869 assert(1 <= size && size < end - p);
870 p += size;
871 *p++ = L'=';
872 size = PyUnicode_AsWideChar(value, p, end - p);
873 assert(0 <= size && size < end - p);
874 p += size + 1;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200875 }
876
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +0200877 /* add trailing null character */
878 *p++ = L'\0';
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200879 assert(p == end);
880
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200881 error:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200882 Py_XDECREF(keys);
883 Py_XDECREF(values);
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +0200884 return buffer;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200885}
886
Segev Finerb2a60832017-12-18 11:28:19 +0200887static LPHANDLE
888gethandlelist(PyObject *mapping, const char *name, Py_ssize_t *size)
889{
890 LPHANDLE ret = NULL;
891 PyObject *value_fast = NULL;
892 PyObject *value;
893 Py_ssize_t i;
894
895 value = PyMapping_GetItemString(mapping, name);
896 if (!value) {
897 PyErr_Clear();
898 return NULL;
899 }
900
901 if (value == Py_None) {
902 goto cleanup;
903 }
904
905 value_fast = PySequence_Fast(value, "handle_list must be a sequence or None");
906 if (value_fast == NULL)
907 goto cleanup;
908
909 *size = PySequence_Fast_GET_SIZE(value_fast) * sizeof(HANDLE);
910
911 /* Passing an empty array causes CreateProcess to fail so just don't set it */
912 if (*size == 0) {
913 goto cleanup;
914 }
915
916 ret = PyMem_Malloc(*size);
917 if (ret == NULL)
918 goto cleanup;
919
920 for (i = 0; i < PySequence_Fast_GET_SIZE(value_fast); i++) {
921 ret[i] = PYNUM_TO_HANDLE(PySequence_Fast_GET_ITEM(value_fast, i));
922 if (ret[i] == (HANDLE)-1 && PyErr_Occurred()) {
923 PyMem_Free(ret);
924 ret = NULL;
925 goto cleanup;
926 }
927 }
928
929cleanup:
930 Py_DECREF(value);
931 Py_XDECREF(value_fast);
932 return ret;
933}
934
935typedef struct {
936 LPPROC_THREAD_ATTRIBUTE_LIST attribute_list;
937 LPHANDLE handle_list;
938} AttributeList;
939
940static void
941freeattributelist(AttributeList *attribute_list)
942{
943 if (attribute_list->attribute_list != NULL) {
944 DeleteProcThreadAttributeList(attribute_list->attribute_list);
945 PyMem_Free(attribute_list->attribute_list);
946 }
947
948 PyMem_Free(attribute_list->handle_list);
949
950 memset(attribute_list, 0, sizeof(*attribute_list));
951}
952
953static int
954getattributelist(PyObject *obj, const char *name, AttributeList *attribute_list)
955{
956 int ret = 0;
957 DWORD err;
958 BOOL result;
959 PyObject *value;
960 Py_ssize_t handle_list_size;
961 DWORD attribute_count = 0;
962 SIZE_T attribute_list_size = 0;
963
964 value = PyObject_GetAttrString(obj, name);
965 if (!value) {
966 PyErr_Clear(); /* FIXME: propagate error? */
967 return 0;
968 }
969
970 if (value == Py_None) {
971 ret = 0;
972 goto cleanup;
973 }
974
975 if (!PyMapping_Check(value)) {
976 ret = -1;
977 PyErr_Format(PyExc_TypeError, "%s must be a mapping or None", name);
978 goto cleanup;
979 }
980
981 attribute_list->handle_list = gethandlelist(value, "handle_list", &handle_list_size);
982 if (attribute_list->handle_list == NULL && PyErr_Occurred()) {
983 ret = -1;
984 goto cleanup;
985 }
986
987 if (attribute_list->handle_list != NULL)
988 ++attribute_count;
989
990 /* Get how many bytes we need for the attribute list */
991 result = InitializeProcThreadAttributeList(NULL, attribute_count, 0, &attribute_list_size);
992 if (result || GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
993 ret = -1;
994 PyErr_SetFromWindowsErr(GetLastError());
995 goto cleanup;
996 }
997
998 attribute_list->attribute_list = PyMem_Malloc(attribute_list_size);
999 if (attribute_list->attribute_list == NULL) {
1000 ret = -1;
1001 goto cleanup;
1002 }
1003
1004 result = InitializeProcThreadAttributeList(
1005 attribute_list->attribute_list,
1006 attribute_count,
1007 0,
1008 &attribute_list_size);
1009 if (!result) {
1010 err = GetLastError();
1011
1012 /* So that we won't call DeleteProcThreadAttributeList */
1013 PyMem_Free(attribute_list->attribute_list);
1014 attribute_list->attribute_list = NULL;
1015
1016 ret = -1;
1017 PyErr_SetFromWindowsErr(err);
1018 goto cleanup;
1019 }
1020
1021 if (attribute_list->handle_list != NULL) {
1022 result = UpdateProcThreadAttribute(
1023 attribute_list->attribute_list,
1024 0,
1025 PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
1026 attribute_list->handle_list,
1027 handle_list_size,
1028 NULL,
1029 NULL);
1030 if (!result) {
1031 ret = -1;
1032 PyErr_SetFromWindowsErr(GetLastError());
1033 goto cleanup;
1034 }
1035 }
1036
1037cleanup:
1038 Py_DECREF(value);
1039
1040 if (ret < 0)
1041 freeattributelist(attribute_list);
1042
1043 return ret;
1044}
1045
Zachary Waref2244ea2015-05-13 01:22:54 -05001046/*[clinic input]
1047_winapi.CreateProcess
1048
Zachary Ware77772c02015-05-13 10:58:35 -05001049 application_name: Py_UNICODE(accept={str, NoneType})
Vladimir Matveev7b360162018-12-14 00:30:51 -08001050 command_line: object
1051 Can be str or None
Zachary Waref2244ea2015-05-13 01:22:54 -05001052 proc_attrs: object
1053 Ignored internally, can be None.
1054 thread_attrs: object
1055 Ignored internally, can be None.
1056 inherit_handles: BOOL
1057 creation_flags: DWORD
1058 env_mapping: object
Zachary Ware77772c02015-05-13 10:58:35 -05001059 current_directory: Py_UNICODE(accept={str, NoneType})
Zachary Waref2244ea2015-05-13 01:22:54 -05001060 startup_info: object
1061 /
1062
1063Create a new process and its primary thread.
1064
1065The return value is a tuple of the process handle, thread handle,
1066process ID, and thread ID.
1067[clinic start generated code]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001068
1069static PyObject *
Serhiy Storchakaafb3e712018-12-14 11:19:51 +02001070_winapi_CreateProcess_impl(PyObject *module,
1071 const Py_UNICODE *application_name,
Vladimir Matveev7b360162018-12-14 00:30:51 -08001072 PyObject *command_line, PyObject *proc_attrs,
Zachary Ware77772c02015-05-13 10:58:35 -05001073 PyObject *thread_attrs, BOOL inherit_handles,
1074 DWORD creation_flags, PyObject *env_mapping,
Serhiy Storchakaafb3e712018-12-14 11:19:51 +02001075 const Py_UNICODE *current_directory,
Zachary Ware77772c02015-05-13 10:58:35 -05001076 PyObject *startup_info)
Serhiy Storchakaafb3e712018-12-14 11:19:51 +02001077/*[clinic end generated code: output=9b2423a609230132 input=42ac293eaea03fc4]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001078{
Segev Finerb2a60832017-12-18 11:28:19 +02001079 PyObject *ret = NULL;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001080 BOOL result;
1081 PROCESS_INFORMATION pi;
Segev Finerb2a60832017-12-18 11:28:19 +02001082 STARTUPINFOEXW si;
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +02001083 wchar_t *wenvironment = NULL;
Vladimir Matveev7b360162018-12-14 00:30:51 -08001084 wchar_t *command_line_copy = NULL;
Segev Finerb2a60832017-12-18 11:28:19 +02001085 AttributeList attribute_list = {0};
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001086
Steve Dowerb82e17e2019-05-23 08:45:22 -07001087 if (PySys_Audit("_winapi.CreateProcess", "uuu", application_name,
1088 command_line, current_directory) < 0) {
1089 return NULL;
1090 }
1091
Victor Stinner252346a2020-05-01 11:33:44 +02001092 PyInterpreterState *interp = PyInterpreterState_Get();
1093 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
1094 if (config->_isolated_interpreter) {
1095 PyErr_SetString(PyExc_RuntimeError,
1096 "subprocess not supported for isolated subinterpreters");
1097 return NULL;
1098 }
1099
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001100 ZeroMemory(&si, sizeof(si));
Segev Finerb2a60832017-12-18 11:28:19 +02001101 si.StartupInfo.cb = sizeof(si);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001102
1103 /* note: we only support a small subset of all SI attributes */
Segev Finerb2a60832017-12-18 11:28:19 +02001104 si.StartupInfo.dwFlags = getulong(startup_info, "dwFlags");
1105 si.StartupInfo.wShowWindow = (WORD)getulong(startup_info, "wShowWindow");
1106 si.StartupInfo.hStdInput = gethandle(startup_info, "hStdInput");
1107 si.StartupInfo.hStdOutput = gethandle(startup_info, "hStdOutput");
1108 si.StartupInfo.hStdError = gethandle(startup_info, "hStdError");
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001109 if (PyErr_Occurred())
Segev Finerb2a60832017-12-18 11:28:19 +02001110 goto cleanup;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001111
1112 if (env_mapping != Py_None) {
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +02001113 wenvironment = getenvironment(env_mapping);
Serhiy Storchakad174d242017-06-23 19:39:27 +03001114 if (wenvironment == NULL) {
Segev Finerb2a60832017-12-18 11:28:19 +02001115 goto cleanup;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001116 }
1117 }
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001118
Segev Finerb2a60832017-12-18 11:28:19 +02001119 if (getattributelist(startup_info, "lpAttributeList", &attribute_list) < 0)
1120 goto cleanup;
1121
1122 si.lpAttributeList = attribute_list.attribute_list;
Vladimir Matveev7b360162018-12-14 00:30:51 -08001123 if (PyUnicode_Check(command_line)) {
1124 command_line_copy = PyUnicode_AsWideCharString(command_line, NULL);
1125 if (command_line_copy == NULL) {
1126 goto cleanup;
1127 }
1128 }
1129 else if (command_line != Py_None) {
Victor Stinner4a21e572020-04-15 02:35:41 +02001130 PyErr_Format(PyExc_TypeError,
1131 "CreateProcess() argument 2 must be str or None, not %s",
Vladimir Matveev7b360162018-12-14 00:30:51 -08001132 Py_TYPE(command_line)->tp_name);
1133 goto cleanup;
1134 }
1135
Segev Finerb2a60832017-12-18 11:28:19 +02001136
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001137 Py_BEGIN_ALLOW_THREADS
1138 result = CreateProcessW(application_name,
Vladimir Matveev7b360162018-12-14 00:30:51 -08001139 command_line_copy,
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001140 NULL,
1141 NULL,
1142 inherit_handles,
Segev Finerb2a60832017-12-18 11:28:19 +02001143 creation_flags | EXTENDED_STARTUPINFO_PRESENT |
1144 CREATE_UNICODE_ENVIRONMENT,
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001145 wenvironment,
1146 current_directory,
Segev Finerb2a60832017-12-18 11:28:19 +02001147 (LPSTARTUPINFOW)&si,
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001148 &pi);
1149 Py_END_ALLOW_THREADS
1150
Segev Finerb2a60832017-12-18 11:28:19 +02001151 if (!result) {
1152 PyErr_SetFromWindowsErr(GetLastError());
1153 goto cleanup;
1154 }
1155
1156 ret = Py_BuildValue("NNkk",
1157 HANDLE_TO_PYNUM(pi.hProcess),
1158 HANDLE_TO_PYNUM(pi.hThread),
1159 pi.dwProcessId,
1160 pi.dwThreadId);
1161
1162cleanup:
Vladimir Matveev7b360162018-12-14 00:30:51 -08001163 PyMem_Free(command_line_copy);
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +02001164 PyMem_Free(wenvironment);
Segev Finerb2a60832017-12-18 11:28:19 +02001165 freeattributelist(&attribute_list);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001166
Segev Finerb2a60832017-12-18 11:28:19 +02001167 return ret;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001168}
1169
Zachary Waref2244ea2015-05-13 01:22:54 -05001170/*[clinic input]
1171_winapi.DuplicateHandle -> HANDLE
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001172
Zachary Waref2244ea2015-05-13 01:22:54 -05001173 source_process_handle: HANDLE
1174 source_handle: HANDLE
1175 target_process_handle: HANDLE
1176 desired_access: DWORD
1177 inherit_handle: BOOL
1178 options: DWORD = 0
1179 /
1180
1181Return a duplicate handle object.
1182
1183The duplicate handle refers to the same object as the original
1184handle. Therefore, any changes to the object are reflected
1185through both handles.
1186[clinic start generated code]*/
1187
1188static HANDLE
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001189_winapi_DuplicateHandle_impl(PyObject *module, HANDLE source_process_handle,
Zachary Ware77772c02015-05-13 10:58:35 -05001190 HANDLE source_handle,
1191 HANDLE target_process_handle,
1192 DWORD desired_access, BOOL inherit_handle,
1193 DWORD options)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001194/*[clinic end generated code: output=ad9711397b5dcd4e input=b933e3f2356a8c12]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001195{
1196 HANDLE target_handle;
1197 BOOL result;
1198
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001199 Py_BEGIN_ALLOW_THREADS
1200 result = DuplicateHandle(
1201 source_process_handle,
1202 source_handle,
1203 target_process_handle,
1204 &target_handle,
1205 desired_access,
1206 inherit_handle,
1207 options
1208 );
1209 Py_END_ALLOW_THREADS
1210
Zachary Waref2244ea2015-05-13 01:22:54 -05001211 if (! result) {
1212 PyErr_SetFromWindowsErr(GetLastError());
1213 return INVALID_HANDLE_VALUE;
1214 }
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001215
Zachary Waref2244ea2015-05-13 01:22:54 -05001216 return target_handle;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001217}
1218
Zachary Waref2244ea2015-05-13 01:22:54 -05001219/*[clinic input]
1220_winapi.ExitProcess
1221
1222 ExitCode: UINT
1223 /
1224
1225[clinic start generated code]*/
1226
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001227static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001228_winapi_ExitProcess_impl(PyObject *module, UINT ExitCode)
1229/*[clinic end generated code: output=a387deb651175301 input=4f05466a9406c558]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001230{
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001231 #if defined(Py_DEBUG)
1232 SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOALIGNMENTFAULTEXCEPT|
1233 SEM_NOGPFAULTERRORBOX|SEM_NOOPENFILEERRORBOX);
1234 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
1235 #endif
1236
Zachary Waref2244ea2015-05-13 01:22:54 -05001237 ExitProcess(ExitCode);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001238
1239 return NULL;
1240}
1241
Zachary Waref2244ea2015-05-13 01:22:54 -05001242/*[clinic input]
1243_winapi.GetCurrentProcess -> HANDLE
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001244
Zachary Waref2244ea2015-05-13 01:22:54 -05001245Return a handle object for the current process.
1246[clinic start generated code]*/
1247
1248static HANDLE
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001249_winapi_GetCurrentProcess_impl(PyObject *module)
1250/*[clinic end generated code: output=ddeb4dd2ffadf344 input=b213403fd4b96b41]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001251{
Zachary Waref2244ea2015-05-13 01:22:54 -05001252 return GetCurrentProcess();
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001253}
1254
Zachary Waref2244ea2015-05-13 01:22:54 -05001255/*[clinic input]
1256_winapi.GetExitCodeProcess -> DWORD
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001257
Zachary Waref2244ea2015-05-13 01:22:54 -05001258 process: HANDLE
1259 /
1260
1261Return the termination status of the specified process.
1262[clinic start generated code]*/
1263
1264static DWORD
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001265_winapi_GetExitCodeProcess_impl(PyObject *module, HANDLE process)
1266/*[clinic end generated code: output=b4620bdf2bccf36b input=61b6bfc7dc2ee374]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001267{
1268 DWORD exit_code;
1269 BOOL result;
1270
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001271 result = GetExitCodeProcess(process, &exit_code);
1272
Zachary Waref2244ea2015-05-13 01:22:54 -05001273 if (! result) {
1274 PyErr_SetFromWindowsErr(GetLastError());
Victor Stinner850a18e2017-10-24 16:53:32 -07001275 exit_code = PY_DWORD_MAX;
Zachary Waref2244ea2015-05-13 01:22:54 -05001276 }
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001277
Zachary Waref2244ea2015-05-13 01:22:54 -05001278 return exit_code;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001279}
1280
Zachary Waref2244ea2015-05-13 01:22:54 -05001281/*[clinic input]
1282_winapi.GetLastError -> DWORD
1283[clinic start generated code]*/
1284
1285static DWORD
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001286_winapi_GetLastError_impl(PyObject *module)
1287/*[clinic end generated code: output=8585b827cb1a92c5 input=62d47fb9bce038ba]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001288{
Zachary Waref2244ea2015-05-13 01:22:54 -05001289 return GetLastError();
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001290}
1291
Zachary Waref2244ea2015-05-13 01:22:54 -05001292/*[clinic input]
1293_winapi.GetModuleFileName
1294
1295 module_handle: HMODULE
1296 /
1297
1298Return the fully-qualified path for the file that contains module.
1299
1300The module must have been loaded by the current process.
1301
1302The module parameter should be a handle to the loaded module
1303whose path is being requested. If this parameter is 0,
1304GetModuleFileName retrieves the path of the executable file
1305of the current process.
1306[clinic start generated code]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001307
1308static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001309_winapi_GetModuleFileName_impl(PyObject *module, HMODULE module_handle)
1310/*[clinic end generated code: output=85b4b728c5160306 input=6d66ff7deca5d11f]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001311{
1312 BOOL result;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001313 WCHAR filename[MAX_PATH];
1314
Steve Dowerb82e17e2019-05-23 08:45:22 -07001315 Py_BEGIN_ALLOW_THREADS
Zachary Waref2244ea2015-05-13 01:22:54 -05001316 result = GetModuleFileNameW(module_handle, filename, MAX_PATH);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001317 filename[MAX_PATH-1] = '\0';
Steve Dowerb82e17e2019-05-23 08:45:22 -07001318 Py_END_ALLOW_THREADS
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001319
1320 if (! result)
1321 return PyErr_SetFromWindowsErr(GetLastError());
1322
1323 return PyUnicode_FromWideChar(filename, wcslen(filename));
1324}
1325
Zachary Waref2244ea2015-05-13 01:22:54 -05001326/*[clinic input]
1327_winapi.GetStdHandle -> HANDLE
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001328
Zachary Waref2244ea2015-05-13 01:22:54 -05001329 std_handle: DWORD
1330 One of STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, or STD_ERROR_HANDLE.
1331 /
1332
1333Return a handle to the specified standard device.
1334
1335The integer associated with the handle object is returned.
1336[clinic start generated code]*/
1337
1338static HANDLE
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001339_winapi_GetStdHandle_impl(PyObject *module, DWORD std_handle)
1340/*[clinic end generated code: output=0e613001e73ab614 input=07016b06a2fc8826]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001341{
1342 HANDLE handle;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001343
1344 Py_BEGIN_ALLOW_THREADS
1345 handle = GetStdHandle(std_handle);
1346 Py_END_ALLOW_THREADS
1347
1348 if (handle == INVALID_HANDLE_VALUE)
Zachary Waref2244ea2015-05-13 01:22:54 -05001349 PyErr_SetFromWindowsErr(GetLastError());
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001350
Zachary Waref2244ea2015-05-13 01:22:54 -05001351 return handle;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001352}
1353
Zachary Waref2244ea2015-05-13 01:22:54 -05001354/*[clinic input]
1355_winapi.GetVersion -> long
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001356
Zachary Waref2244ea2015-05-13 01:22:54 -05001357Return the version number of the current operating system.
1358[clinic start generated code]*/
1359
1360static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001361_winapi_GetVersion_impl(PyObject *module)
1362/*[clinic end generated code: output=e41f0db5a3b82682 input=e21dff8d0baeded2]*/
Steve Dower3e96f322015-03-02 08:01:10 -08001363/* Disable deprecation warnings about GetVersionEx as the result is
1364 being passed straight through to the caller, who is responsible for
1365 using it correctly. */
1366#pragma warning(push)
1367#pragma warning(disable:4996)
1368
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001369{
Zachary Waref2244ea2015-05-13 01:22:54 -05001370 return GetVersion();
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001371}
1372
Steve Dower3e96f322015-03-02 08:01:10 -08001373#pragma warning(pop)
1374
Zachary Waref2244ea2015-05-13 01:22:54 -05001375/*[clinic input]
Davin Pottse895de32019-02-23 22:08:16 -06001376_winapi.MapViewOfFile -> LPVOID
1377
1378 file_map: HANDLE
1379 desired_access: DWORD
1380 file_offset_high: DWORD
1381 file_offset_low: DWORD
1382 number_bytes: size_t
1383 /
1384[clinic start generated code]*/
1385
1386static LPVOID
1387_winapi_MapViewOfFile_impl(PyObject *module, HANDLE file_map,
1388 DWORD desired_access, DWORD file_offset_high,
1389 DWORD file_offset_low, size_t number_bytes)
1390/*[clinic end generated code: output=f23b1ee4823663e3 input=177471073be1a103]*/
1391{
1392 LPVOID address;
1393
1394 Py_BEGIN_ALLOW_THREADS
1395 address = MapViewOfFile(file_map, desired_access, file_offset_high,
1396 file_offset_low, number_bytes);
1397 Py_END_ALLOW_THREADS
1398
1399 if (address == NULL)
1400 PyErr_SetFromWindowsErr(0);
1401
1402 return address;
1403}
1404
1405/*[clinic input]
1406_winapi.OpenFileMapping -> HANDLE
1407
1408 desired_access: DWORD
1409 inherit_handle: BOOL
1410 name: LPCWSTR
1411 /
1412[clinic start generated code]*/
1413
1414static HANDLE
1415_winapi_OpenFileMapping_impl(PyObject *module, DWORD desired_access,
1416 BOOL inherit_handle, LPCWSTR name)
1417/*[clinic end generated code: output=08cc44def1cb11f1 input=131f2a405359de7f]*/
1418{
1419 HANDLE handle;
1420
1421 Py_BEGIN_ALLOW_THREADS
1422 handle = OpenFileMappingW(desired_access, inherit_handle, name);
1423 Py_END_ALLOW_THREADS
1424
1425 if (handle == NULL) {
Zackery Spytzeda385c2019-05-30 01:58:50 -06001426 PyObject *temp = PyUnicode_FromWideChar(name, -1);
1427 PyErr_SetExcFromWindowsErrWithFilenameObject(PyExc_OSError, 0, temp);
1428 Py_XDECREF(temp);
Davin Pottse895de32019-02-23 22:08:16 -06001429 handle = INVALID_HANDLE_VALUE;
1430 }
1431
1432 return handle;
1433}
1434
1435/*[clinic input]
Zachary Waref2244ea2015-05-13 01:22:54 -05001436_winapi.OpenProcess -> HANDLE
1437
1438 desired_access: DWORD
1439 inherit_handle: BOOL
1440 process_id: DWORD
1441 /
1442[clinic start generated code]*/
1443
1444static HANDLE
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001445_winapi_OpenProcess_impl(PyObject *module, DWORD desired_access,
Zachary Ware77772c02015-05-13 10:58:35 -05001446 BOOL inherit_handle, DWORD process_id)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001447/*[clinic end generated code: output=b42b6b81ea5a0fc3 input=ec98c4cf4ea2ec36]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001448{
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001449 HANDLE handle;
1450
Steve Dowerb82e17e2019-05-23 08:45:22 -07001451 if (PySys_Audit("_winapi.OpenProcess", "II",
1452 process_id, desired_access) < 0) {
1453 return INVALID_HANDLE_VALUE;
1454 }
1455
1456 Py_BEGIN_ALLOW_THREADS
Zachary Waref2244ea2015-05-13 01:22:54 -05001457 handle = OpenProcess(desired_access, inherit_handle, process_id);
Steve Dowerb82e17e2019-05-23 08:45:22 -07001458 Py_END_ALLOW_THREADS
Zachary Waref2244ea2015-05-13 01:22:54 -05001459 if (handle == NULL) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001460 PyErr_SetFromWindowsErr(GetLastError());
Zachary Waref2244ea2015-05-13 01:22:54 -05001461 handle = INVALID_HANDLE_VALUE;
1462 }
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001463
Zachary Waref2244ea2015-05-13 01:22:54 -05001464 return handle;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001465}
1466
Zachary Waref2244ea2015-05-13 01:22:54 -05001467/*[clinic input]
1468_winapi.PeekNamedPipe
1469
1470 handle: HANDLE
1471 size: int = 0
1472 /
1473[clinic start generated code]*/
1474
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001475static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001476_winapi_PeekNamedPipe_impl(PyObject *module, HANDLE handle, int size)
1477/*[clinic end generated code: output=d0c3e29e49d323dd input=c7aa53bfbce69d70]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001478{
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001479 PyObject *buf = NULL;
1480 DWORD nread, navail, nleft;
1481 BOOL ret;
1482
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001483 if (size < 0) {
1484 PyErr_SetString(PyExc_ValueError, "negative size");
1485 return NULL;
1486 }
1487
1488 if (size) {
1489 buf = PyBytes_FromStringAndSize(NULL, size);
1490 if (!buf)
1491 return NULL;
1492 Py_BEGIN_ALLOW_THREADS
1493 ret = PeekNamedPipe(handle, PyBytes_AS_STRING(buf), size, &nread,
1494 &navail, &nleft);
1495 Py_END_ALLOW_THREADS
1496 if (!ret) {
1497 Py_DECREF(buf);
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03001498 return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001499 }
1500 if (_PyBytes_Resize(&buf, nread))
1501 return NULL;
Alexander Buchkovsky266f4902018-09-04 19:10:28 +03001502 return Py_BuildValue("NII", buf, navail, nleft);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001503 }
1504 else {
1505 Py_BEGIN_ALLOW_THREADS
1506 ret = PeekNamedPipe(handle, NULL, 0, NULL, &navail, &nleft);
1507 Py_END_ALLOW_THREADS
1508 if (!ret) {
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03001509 return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001510 }
Alexander Buchkovsky266f4902018-09-04 19:10:28 +03001511 return Py_BuildValue("II", navail, nleft);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001512 }
1513}
1514
Zachary Waref2244ea2015-05-13 01:22:54 -05001515/*[clinic input]
1516_winapi.ReadFile
1517
1518 handle: HANDLE
Alexander Buchkovsky266f4902018-09-04 19:10:28 +03001519 size: DWORD
Serhiy Storchaka202fda52017-03-12 10:10:47 +02001520 overlapped as use_overlapped: bool(accept={int}) = False
Zachary Waref2244ea2015-05-13 01:22:54 -05001521[clinic start generated code]*/
1522
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001523static PyObject *
Alexander Buchkovsky266f4902018-09-04 19:10:28 +03001524_winapi_ReadFile_impl(PyObject *module, HANDLE handle, DWORD size,
Zachary Ware77772c02015-05-13 10:58:35 -05001525 int use_overlapped)
Alexander Buchkovsky266f4902018-09-04 19:10:28 +03001526/*[clinic end generated code: output=d3d5b44a8201b944 input=08c439d03a11aac5]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001527{
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001528 DWORD nread;
1529 PyObject *buf;
1530 BOOL ret;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001531 DWORD err;
1532 OverlappedObject *overlapped = NULL;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001533
1534 buf = PyBytes_FromStringAndSize(NULL, size);
1535 if (!buf)
1536 return NULL;
1537 if (use_overlapped) {
Mohamed Koubaae087f7c2020-08-13 09:22:48 -05001538 overlapped = new_overlapped(module, handle);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001539 if (!overlapped) {
1540 Py_DECREF(buf);
1541 return NULL;
1542 }
1543 /* Steals reference to buf */
1544 overlapped->read_buffer = buf;
1545 }
1546
1547 Py_BEGIN_ALLOW_THREADS
1548 ret = ReadFile(handle, PyBytes_AS_STRING(buf), size, &nread,
1549 overlapped ? &overlapped->overlapped : NULL);
1550 Py_END_ALLOW_THREADS
1551
1552 err = ret ? 0 : GetLastError();
1553
1554 if (overlapped) {
1555 if (!ret) {
1556 if (err == ERROR_IO_PENDING)
1557 overlapped->pending = 1;
1558 else if (err != ERROR_MORE_DATA) {
1559 Py_DECREF(overlapped);
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03001560 return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001561 }
1562 }
1563 return Py_BuildValue("NI", (PyObject *) overlapped, err);
1564 }
1565
1566 if (!ret && err != ERROR_MORE_DATA) {
1567 Py_DECREF(buf);
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03001568 return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001569 }
1570 if (_PyBytes_Resize(&buf, nread))
1571 return NULL;
1572 return Py_BuildValue("NI", buf, err);
1573}
1574
Zachary Waref2244ea2015-05-13 01:22:54 -05001575/*[clinic input]
1576_winapi.SetNamedPipeHandleState
1577
1578 named_pipe: HANDLE
1579 mode: object
1580 max_collection_count: object
1581 collect_data_timeout: object
1582 /
1583[clinic start generated code]*/
1584
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001585static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001586_winapi_SetNamedPipeHandleState_impl(PyObject *module, HANDLE named_pipe,
Zachary Ware77772c02015-05-13 10:58:35 -05001587 PyObject *mode,
1588 PyObject *max_collection_count,
1589 PyObject *collect_data_timeout)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001590/*[clinic end generated code: output=f2129d222cbfa095 input=9142d72163d0faa6]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001591{
Zachary Waref2244ea2015-05-13 01:22:54 -05001592 PyObject *oArgs[3] = {mode, max_collection_count, collect_data_timeout};
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001593 DWORD dwArgs[3], *pArgs[3] = {NULL, NULL, NULL};
1594 int i;
Steve Dowerb82e17e2019-05-23 08:45:22 -07001595 BOOL b;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001596
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001597 for (i = 0 ; i < 3 ; i++) {
1598 if (oArgs[i] != Py_None) {
1599 dwArgs[i] = PyLong_AsUnsignedLongMask(oArgs[i]);
1600 if (PyErr_Occurred())
1601 return NULL;
1602 pArgs[i] = &dwArgs[i];
1603 }
1604 }
1605
Steve Dowerb82e17e2019-05-23 08:45:22 -07001606 Py_BEGIN_ALLOW_THREADS
1607 b = SetNamedPipeHandleState(named_pipe, pArgs[0], pArgs[1], pArgs[2]);
1608 Py_END_ALLOW_THREADS
1609
1610 if (!b)
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001611 return PyErr_SetFromWindowsErr(0);
1612
1613 Py_RETURN_NONE;
1614}
1615
Zachary Waref2244ea2015-05-13 01:22:54 -05001616
1617/*[clinic input]
1618_winapi.TerminateProcess
1619
1620 handle: HANDLE
1621 exit_code: UINT
1622 /
1623
1624Terminate the specified process and all of its threads.
1625[clinic start generated code]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001626
1627static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001628_winapi_TerminateProcess_impl(PyObject *module, HANDLE handle,
Zachary Ware77772c02015-05-13 10:58:35 -05001629 UINT exit_code)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001630/*[clinic end generated code: output=f4e99ac3f0b1f34a input=d6bc0aa1ee3bb4df]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001631{
1632 BOOL result;
1633
Steve Dowerb82e17e2019-05-23 08:45:22 -07001634 if (PySys_Audit("_winapi.TerminateProcess", "nI",
1635 (Py_ssize_t)handle, exit_code) < 0) {
1636 return NULL;
1637 }
1638
Zachary Waref2244ea2015-05-13 01:22:54 -05001639 result = TerminateProcess(handle, exit_code);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001640
1641 if (! result)
1642 return PyErr_SetFromWindowsErr(GetLastError());
1643
Zachary Waref2244ea2015-05-13 01:22:54 -05001644 Py_RETURN_NONE;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001645}
1646
Zachary Waref2244ea2015-05-13 01:22:54 -05001647/*[clinic input]
Davin Pottse895de32019-02-23 22:08:16 -06001648_winapi.VirtualQuerySize -> size_t
1649
1650 address: LPCVOID
1651 /
1652[clinic start generated code]*/
1653
1654static size_t
1655_winapi_VirtualQuerySize_impl(PyObject *module, LPCVOID address)
1656/*[clinic end generated code: output=40c8e0ff5ec964df input=6b784a69755d0bb6]*/
1657{
1658 SIZE_T size_of_buf;
1659 MEMORY_BASIC_INFORMATION mem_basic_info;
1660 SIZE_T region_size;
1661
1662 Py_BEGIN_ALLOW_THREADS
1663 size_of_buf = VirtualQuery(address, &mem_basic_info, sizeof(mem_basic_info));
1664 Py_END_ALLOW_THREADS
1665
1666 if (size_of_buf == 0)
1667 PyErr_SetFromWindowsErr(0);
1668
1669 region_size = mem_basic_info.RegionSize;
1670 return region_size;
1671}
1672
1673/*[clinic input]
Zachary Waref2244ea2015-05-13 01:22:54 -05001674_winapi.WaitNamedPipe
1675
1676 name: LPCTSTR
1677 timeout: DWORD
1678 /
1679[clinic start generated code]*/
1680
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001681static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001682_winapi_WaitNamedPipe_impl(PyObject *module, LPCTSTR name, DWORD timeout)
1683/*[clinic end generated code: output=c2866f4439b1fe38 input=36fc781291b1862c]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001684{
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001685 BOOL success;
1686
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001687 Py_BEGIN_ALLOW_THREADS
Zachary Waref2244ea2015-05-13 01:22:54 -05001688 success = WaitNamedPipe(name, timeout);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001689 Py_END_ALLOW_THREADS
1690
1691 if (!success)
1692 return PyErr_SetFromWindowsErr(0);
1693
1694 Py_RETURN_NONE;
1695}
1696
Zachary Waref2244ea2015-05-13 01:22:54 -05001697/*[clinic input]
1698_winapi.WaitForMultipleObjects
1699
1700 handle_seq: object
1701 wait_flag: BOOL
1702 milliseconds: DWORD(c_default='INFINITE') = _winapi.INFINITE
1703 /
1704[clinic start generated code]*/
1705
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001706static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001707_winapi_WaitForMultipleObjects_impl(PyObject *module, PyObject *handle_seq,
1708 BOOL wait_flag, DWORD milliseconds)
1709/*[clinic end generated code: output=295e3f00b8e45899 input=36f76ca057cd28a0]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001710{
1711 DWORD result;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001712 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
1713 HANDLE sigint_event = NULL;
1714 Py_ssize_t nhandles, i;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001715
1716 if (!PySequence_Check(handle_seq)) {
1717 PyErr_Format(PyExc_TypeError,
1718 "sequence type expected, got '%s'",
Richard Oudkerk67339272012-08-21 14:54:22 +01001719 Py_TYPE(handle_seq)->tp_name);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001720 return NULL;
1721 }
1722 nhandles = PySequence_Length(handle_seq);
1723 if (nhandles == -1)
1724 return NULL;
1725 if (nhandles < 0 || nhandles >= MAXIMUM_WAIT_OBJECTS - 1) {
1726 PyErr_Format(PyExc_ValueError,
1727 "need at most %zd handles, got a sequence of length %zd",
1728 MAXIMUM_WAIT_OBJECTS - 1, nhandles);
1729 return NULL;
1730 }
1731 for (i = 0; i < nhandles; i++) {
1732 HANDLE h;
1733 PyObject *v = PySequence_GetItem(handle_seq, i);
1734 if (v == NULL)
1735 return NULL;
1736 if (!PyArg_Parse(v, F_HANDLE, &h)) {
1737 Py_DECREF(v);
1738 return NULL;
1739 }
1740 handles[i] = h;
1741 Py_DECREF(v);
1742 }
1743 /* If this is the main thread then make the wait interruptible
1744 by Ctrl-C unless we are waiting for *all* handles */
1745 if (!wait_flag && _PyOS_IsMainThread()) {
1746 sigint_event = _PyOS_SigintEvent();
1747 assert(sigint_event != NULL);
1748 handles[nhandles++] = sigint_event;
1749 }
1750
1751 Py_BEGIN_ALLOW_THREADS
1752 if (sigint_event != NULL)
1753 ResetEvent(sigint_event);
1754 result = WaitForMultipleObjects((DWORD) nhandles, handles,
1755 wait_flag, milliseconds);
1756 Py_END_ALLOW_THREADS
1757
1758 if (result == WAIT_FAILED)
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03001759 return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001760 else if (sigint_event != NULL && result == WAIT_OBJECT_0 + nhandles - 1) {
1761 errno = EINTR;
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03001762 return PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001763 }
1764
1765 return PyLong_FromLong((int) result);
1766}
1767
Zachary Waref2244ea2015-05-13 01:22:54 -05001768/*[clinic input]
1769_winapi.WaitForSingleObject -> long
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001770
Zachary Waref2244ea2015-05-13 01:22:54 -05001771 handle: HANDLE
1772 milliseconds: DWORD
1773 /
1774
1775Wait for a single object.
1776
1777Wait until the specified object is in the signaled state or
1778the time-out interval elapses. The timeout value is specified
1779in milliseconds.
1780[clinic start generated code]*/
1781
1782static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001783_winapi_WaitForSingleObject_impl(PyObject *module, HANDLE handle,
Zachary Ware77772c02015-05-13 10:58:35 -05001784 DWORD milliseconds)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001785/*[clinic end generated code: output=3c4715d8f1b39859 input=443d1ab076edc7b1]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001786{
1787 DWORD result;
1788
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001789 Py_BEGIN_ALLOW_THREADS
1790 result = WaitForSingleObject(handle, milliseconds);
1791 Py_END_ALLOW_THREADS
1792
Zachary Waref2244ea2015-05-13 01:22:54 -05001793 if (result == WAIT_FAILED) {
1794 PyErr_SetFromWindowsErr(GetLastError());
1795 return -1;
1796 }
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001797
Zachary Waref2244ea2015-05-13 01:22:54 -05001798 return result;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001799}
1800
Zachary Waref2244ea2015-05-13 01:22:54 -05001801/*[clinic input]
1802_winapi.WriteFile
1803
1804 handle: HANDLE
1805 buffer: object
Serhiy Storchaka202fda52017-03-12 10:10:47 +02001806 overlapped as use_overlapped: bool(accept={int}) = False
Zachary Waref2244ea2015-05-13 01:22:54 -05001807[clinic start generated code]*/
1808
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001809static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001810_winapi_WriteFile_impl(PyObject *module, HANDLE handle, PyObject *buffer,
Zachary Ware77772c02015-05-13 10:58:35 -05001811 int use_overlapped)
Serhiy Storchaka202fda52017-03-12 10:10:47 +02001812/*[clinic end generated code: output=2ca80f6bf3fa92e3 input=11eae2a03aa32731]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001813{
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001814 Py_buffer _buf, *buf;
Victor Stinner71765772013-06-24 23:13:24 +02001815 DWORD len, written;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001816 BOOL ret;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001817 DWORD err;
1818 OverlappedObject *overlapped = NULL;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001819
1820 if (use_overlapped) {
Mohamed Koubaae087f7c2020-08-13 09:22:48 -05001821 overlapped = new_overlapped(module, handle);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001822 if (!overlapped)
1823 return NULL;
1824 buf = &overlapped->write_buffer;
1825 }
1826 else
1827 buf = &_buf;
1828
Zachary Waref2244ea2015-05-13 01:22:54 -05001829 if (!PyArg_Parse(buffer, "y*", buf)) {
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001830 Py_XDECREF(overlapped);
1831 return NULL;
1832 }
1833
1834 Py_BEGIN_ALLOW_THREADS
Victor Stinner850a18e2017-10-24 16:53:32 -07001835 len = (DWORD)Py_MIN(buf->len, PY_DWORD_MAX);
Victor Stinner71765772013-06-24 23:13:24 +02001836 ret = WriteFile(handle, buf->buf, len, &written,
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001837 overlapped ? &overlapped->overlapped : NULL);
1838 Py_END_ALLOW_THREADS
1839
1840 err = ret ? 0 : GetLastError();
1841
1842 if (overlapped) {
1843 if (!ret) {
1844 if (err == ERROR_IO_PENDING)
1845 overlapped->pending = 1;
1846 else {
1847 Py_DECREF(overlapped);
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03001848 return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001849 }
1850 }
1851 return Py_BuildValue("NI", (PyObject *) overlapped, err);
1852 }
1853
1854 PyBuffer_Release(buf);
1855 if (!ret)
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03001856 return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001857 return Py_BuildValue("II", written, err);
1858}
1859
Victor Stinner91106cd2017-12-13 12:29:09 +01001860/*[clinic input]
1861_winapi.GetACP
1862
1863Get the current Windows ANSI code page identifier.
1864[clinic start generated code]*/
1865
1866static PyObject *
1867_winapi_GetACP_impl(PyObject *module)
1868/*[clinic end generated code: output=f7ee24bf705dbb88 input=1433c96d03a05229]*/
1869{
1870 return PyLong_FromUnsignedLong(GetACP());
1871}
1872
Segev Finerb2a60832017-12-18 11:28:19 +02001873/*[clinic input]
1874_winapi.GetFileType -> DWORD
1875
1876 handle: HANDLE
1877[clinic start generated code]*/
1878
1879static DWORD
1880_winapi_GetFileType_impl(PyObject *module, HANDLE handle)
1881/*[clinic end generated code: output=92b8466ac76ecc17 input=0058366bc40bbfbf]*/
1882{
1883 DWORD result;
1884
1885 Py_BEGIN_ALLOW_THREADS
1886 result = GetFileType(handle);
1887 Py_END_ALLOW_THREADS
1888
1889 if (result == FILE_TYPE_UNKNOWN && GetLastError() != NO_ERROR) {
1890 PyErr_SetFromWindowsErr(0);
1891 return -1;
1892 }
1893
1894 return result;
1895}
1896
Victor Stinner91106cd2017-12-13 12:29:09 +01001897
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001898static PyMethodDef winapi_functions[] = {
Zachary Waref2244ea2015-05-13 01:22:54 -05001899 _WINAPI_CLOSEHANDLE_METHODDEF
1900 _WINAPI_CONNECTNAMEDPIPE_METHODDEF
1901 _WINAPI_CREATEFILE_METHODDEF
Davin Pottse895de32019-02-23 22:08:16 -06001902 _WINAPI_CREATEFILEMAPPING_METHODDEF
Zachary Waref2244ea2015-05-13 01:22:54 -05001903 _WINAPI_CREATENAMEDPIPE_METHODDEF
1904 _WINAPI_CREATEPIPE_METHODDEF
1905 _WINAPI_CREATEPROCESS_METHODDEF
1906 _WINAPI_CREATEJUNCTION_METHODDEF
1907 _WINAPI_DUPLICATEHANDLE_METHODDEF
1908 _WINAPI_EXITPROCESS_METHODDEF
1909 _WINAPI_GETCURRENTPROCESS_METHODDEF
1910 _WINAPI_GETEXITCODEPROCESS_METHODDEF
1911 _WINAPI_GETLASTERROR_METHODDEF
1912 _WINAPI_GETMODULEFILENAME_METHODDEF
1913 _WINAPI_GETSTDHANDLE_METHODDEF
1914 _WINAPI_GETVERSION_METHODDEF
Davin Pottse895de32019-02-23 22:08:16 -06001915 _WINAPI_MAPVIEWOFFILE_METHODDEF
1916 _WINAPI_OPENFILEMAPPING_METHODDEF
Zachary Waref2244ea2015-05-13 01:22:54 -05001917 _WINAPI_OPENPROCESS_METHODDEF
1918 _WINAPI_PEEKNAMEDPIPE_METHODDEF
1919 _WINAPI_READFILE_METHODDEF
1920 _WINAPI_SETNAMEDPIPEHANDLESTATE_METHODDEF
1921 _WINAPI_TERMINATEPROCESS_METHODDEF
Davin Pottse895de32019-02-23 22:08:16 -06001922 _WINAPI_VIRTUALQUERYSIZE_METHODDEF
Zachary Waref2244ea2015-05-13 01:22:54 -05001923 _WINAPI_WAITNAMEDPIPE_METHODDEF
1924 _WINAPI_WAITFORMULTIPLEOBJECTS_METHODDEF
1925 _WINAPI_WAITFORSINGLEOBJECT_METHODDEF
1926 _WINAPI_WRITEFILE_METHODDEF
Victor Stinner91106cd2017-12-13 12:29:09 +01001927 _WINAPI_GETACP_METHODDEF
Segev Finerb2a60832017-12-18 11:28:19 +02001928 _WINAPI_GETFILETYPE_METHODDEF
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001929 {NULL, NULL}
1930};
1931
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001932#define WINAPI_CONSTANT(fmt, con) \
Mohamed Koubaae087f7c2020-08-13 09:22:48 -05001933 do { \
1934 PyObject *value = Py_BuildValue(fmt, con); \
1935 if (value == NULL) { \
1936 return -1; \
1937 } \
1938 if (PyDict_SetItemString(d, #con, value) < 0) { \
1939 Py_DECREF(value); \
1940 return -1; \
1941 } \
1942 Py_DECREF(value); \
1943 } while (0)
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001944
Mohamed Koubaae087f7c2020-08-13 09:22:48 -05001945static int winapi_exec(PyObject *m)
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001946{
Mohamed Koubaae087f7c2020-08-13 09:22:48 -05001947 WinApiState *st = winapi_get_state(m);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001948
Mohamed Koubaae087f7c2020-08-13 09:22:48 -05001949 st->overlapped_type = (PyTypeObject *)PyType_FromModuleAndSpec(m, &winapi_overlapped_type_spec, NULL);
1950 if (st->overlapped_type == NULL) {
1951 return -1;
1952 }
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001953
Mohamed Koubaae087f7c2020-08-13 09:22:48 -05001954 if (PyModule_AddType(m, st->overlapped_type) < 0) {
1955 return -1;
1956 }
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001957
Mohamed Koubaae087f7c2020-08-13 09:22:48 -05001958 PyObject *d = PyModule_GetDict(m);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001959
1960 /* constants */
1961 WINAPI_CONSTANT(F_DWORD, CREATE_NEW_CONSOLE);
1962 WINAPI_CONSTANT(F_DWORD, CREATE_NEW_PROCESS_GROUP);
1963 WINAPI_CONSTANT(F_DWORD, DUPLICATE_SAME_ACCESS);
Antoine Pitrou5438ed12012-04-24 22:56:57 +02001964 WINAPI_CONSTANT(F_DWORD, DUPLICATE_CLOSE_SOURCE);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001965 WINAPI_CONSTANT(F_DWORD, ERROR_ALREADY_EXISTS);
1966 WINAPI_CONSTANT(F_DWORD, ERROR_BROKEN_PIPE);
1967 WINAPI_CONSTANT(F_DWORD, ERROR_IO_PENDING);
1968 WINAPI_CONSTANT(F_DWORD, ERROR_MORE_DATA);
1969 WINAPI_CONSTANT(F_DWORD, ERROR_NETNAME_DELETED);
1970 WINAPI_CONSTANT(F_DWORD, ERROR_NO_SYSTEM_RESOURCES);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001971 WINAPI_CONSTANT(F_DWORD, ERROR_MORE_DATA);
1972 WINAPI_CONSTANT(F_DWORD, ERROR_NETNAME_DELETED);
Richard Oudkerkfdb8dcf2012-05-05 19:45:37 +01001973 WINAPI_CONSTANT(F_DWORD, ERROR_NO_DATA);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001974 WINAPI_CONSTANT(F_DWORD, ERROR_NO_SYSTEM_RESOURCES);
1975 WINAPI_CONSTANT(F_DWORD, ERROR_OPERATION_ABORTED);
1976 WINAPI_CONSTANT(F_DWORD, ERROR_PIPE_BUSY);
1977 WINAPI_CONSTANT(F_DWORD, ERROR_PIPE_CONNECTED);
1978 WINAPI_CONSTANT(F_DWORD, ERROR_SEM_TIMEOUT);
1979 WINAPI_CONSTANT(F_DWORD, FILE_FLAG_FIRST_PIPE_INSTANCE);
1980 WINAPI_CONSTANT(F_DWORD, FILE_FLAG_OVERLAPPED);
Antoine Pitrou5438ed12012-04-24 22:56:57 +02001981 WINAPI_CONSTANT(F_DWORD, FILE_GENERIC_READ);
1982 WINAPI_CONSTANT(F_DWORD, FILE_GENERIC_WRITE);
Davin Pottse895de32019-02-23 22:08:16 -06001983 WINAPI_CONSTANT(F_DWORD, FILE_MAP_ALL_ACCESS);
1984 WINAPI_CONSTANT(F_DWORD, FILE_MAP_COPY);
1985 WINAPI_CONSTANT(F_DWORD, FILE_MAP_EXECUTE);
1986 WINAPI_CONSTANT(F_DWORD, FILE_MAP_READ);
1987 WINAPI_CONSTANT(F_DWORD, FILE_MAP_WRITE);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001988 WINAPI_CONSTANT(F_DWORD, GENERIC_READ);
1989 WINAPI_CONSTANT(F_DWORD, GENERIC_WRITE);
1990 WINAPI_CONSTANT(F_DWORD, INFINITE);
Davin Pottse895de32019-02-23 22:08:16 -06001991 WINAPI_CONSTANT(F_HANDLE, INVALID_HANDLE_VALUE);
1992 WINAPI_CONSTANT(F_DWORD, MEM_COMMIT);
1993 WINAPI_CONSTANT(F_DWORD, MEM_FREE);
1994 WINAPI_CONSTANT(F_DWORD, MEM_IMAGE);
1995 WINAPI_CONSTANT(F_DWORD, MEM_MAPPED);
1996 WINAPI_CONSTANT(F_DWORD, MEM_PRIVATE);
1997 WINAPI_CONSTANT(F_DWORD, MEM_RESERVE);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001998 WINAPI_CONSTANT(F_DWORD, NMPWAIT_WAIT_FOREVER);
1999 WINAPI_CONSTANT(F_DWORD, OPEN_EXISTING);
Davin Pottse895de32019-02-23 22:08:16 -06002000 WINAPI_CONSTANT(F_DWORD, PAGE_EXECUTE);
2001 WINAPI_CONSTANT(F_DWORD, PAGE_EXECUTE_READ);
2002 WINAPI_CONSTANT(F_DWORD, PAGE_EXECUTE_READWRITE);
2003 WINAPI_CONSTANT(F_DWORD, PAGE_EXECUTE_WRITECOPY);
2004 WINAPI_CONSTANT(F_DWORD, PAGE_GUARD);
2005 WINAPI_CONSTANT(F_DWORD, PAGE_NOACCESS);
2006 WINAPI_CONSTANT(F_DWORD, PAGE_NOCACHE);
2007 WINAPI_CONSTANT(F_DWORD, PAGE_READONLY);
2008 WINAPI_CONSTANT(F_DWORD, PAGE_READWRITE);
2009 WINAPI_CONSTANT(F_DWORD, PAGE_WRITECOMBINE);
2010 WINAPI_CONSTANT(F_DWORD, PAGE_WRITECOPY);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02002011 WINAPI_CONSTANT(F_DWORD, PIPE_ACCESS_DUPLEX);
2012 WINAPI_CONSTANT(F_DWORD, PIPE_ACCESS_INBOUND);
2013 WINAPI_CONSTANT(F_DWORD, PIPE_READMODE_MESSAGE);
2014 WINAPI_CONSTANT(F_DWORD, PIPE_TYPE_MESSAGE);
2015 WINAPI_CONSTANT(F_DWORD, PIPE_UNLIMITED_INSTANCES);
2016 WINAPI_CONSTANT(F_DWORD, PIPE_WAIT);
2017 WINAPI_CONSTANT(F_DWORD, PROCESS_ALL_ACCESS);
Thomas Moreauc09a9f52019-05-20 21:37:05 +02002018 WINAPI_CONSTANT(F_DWORD, SYNCHRONIZE);
Antoine Pitrou5438ed12012-04-24 22:56:57 +02002019 WINAPI_CONSTANT(F_DWORD, PROCESS_DUP_HANDLE);
Davin Pottse895de32019-02-23 22:08:16 -06002020 WINAPI_CONSTANT(F_DWORD, SEC_COMMIT);
2021 WINAPI_CONSTANT(F_DWORD, SEC_IMAGE);
2022 WINAPI_CONSTANT(F_DWORD, SEC_LARGE_PAGES);
2023 WINAPI_CONSTANT(F_DWORD, SEC_NOCACHE);
2024 WINAPI_CONSTANT(F_DWORD, SEC_RESERVE);
2025 WINAPI_CONSTANT(F_DWORD, SEC_WRITECOMBINE);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02002026 WINAPI_CONSTANT(F_DWORD, STARTF_USESHOWWINDOW);
2027 WINAPI_CONSTANT(F_DWORD, STARTF_USESTDHANDLES);
2028 WINAPI_CONSTANT(F_DWORD, STD_INPUT_HANDLE);
2029 WINAPI_CONSTANT(F_DWORD, STD_OUTPUT_HANDLE);
2030 WINAPI_CONSTANT(F_DWORD, STD_ERROR_HANDLE);
2031 WINAPI_CONSTANT(F_DWORD, STILL_ACTIVE);
2032 WINAPI_CONSTANT(F_DWORD, SW_HIDE);
2033 WINAPI_CONSTANT(F_DWORD, WAIT_OBJECT_0);
Victor Stinner373f0a92014-03-20 09:26:55 +01002034 WINAPI_CONSTANT(F_DWORD, WAIT_ABANDONED_0);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02002035 WINAPI_CONSTANT(F_DWORD, WAIT_TIMEOUT);
Victor Stinner91106cd2017-12-13 12:29:09 +01002036
Jamesb5d9e082017-11-08 14:18:59 +00002037 WINAPI_CONSTANT(F_DWORD, ABOVE_NORMAL_PRIORITY_CLASS);
2038 WINAPI_CONSTANT(F_DWORD, BELOW_NORMAL_PRIORITY_CLASS);
2039 WINAPI_CONSTANT(F_DWORD, HIGH_PRIORITY_CLASS);
2040 WINAPI_CONSTANT(F_DWORD, IDLE_PRIORITY_CLASS);
2041 WINAPI_CONSTANT(F_DWORD, NORMAL_PRIORITY_CLASS);
2042 WINAPI_CONSTANT(F_DWORD, REALTIME_PRIORITY_CLASS);
Victor Stinner91106cd2017-12-13 12:29:09 +01002043
Jamesb5d9e082017-11-08 14:18:59 +00002044 WINAPI_CONSTANT(F_DWORD, CREATE_NO_WINDOW);
2045 WINAPI_CONSTANT(F_DWORD, DETACHED_PROCESS);
2046 WINAPI_CONSTANT(F_DWORD, CREATE_DEFAULT_ERROR_MODE);
2047 WINAPI_CONSTANT(F_DWORD, CREATE_BREAKAWAY_FROM_JOB);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02002048
Segev Finerb2a60832017-12-18 11:28:19 +02002049 WINAPI_CONSTANT(F_DWORD, FILE_TYPE_UNKNOWN);
2050 WINAPI_CONSTANT(F_DWORD, FILE_TYPE_DISK);
2051 WINAPI_CONSTANT(F_DWORD, FILE_TYPE_CHAR);
2052 WINAPI_CONSTANT(F_DWORD, FILE_TYPE_PIPE);
2053 WINAPI_CONSTANT(F_DWORD, FILE_TYPE_REMOTE);
2054
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02002055 WINAPI_CONSTANT("i", NULL);
2056
Mohamed Koubaae087f7c2020-08-13 09:22:48 -05002057 return 0;
2058}
2059
2060static PyModuleDef_Slot winapi_slots[] = {
2061 {Py_mod_exec, winapi_exec},
2062 {0, NULL}
2063};
2064
Ken Jin0d399512021-05-29 01:47:15 +08002065static int
2066winapi_traverse(PyObject *module, visitproc visit, void *arg)
2067{
2068 WinApiState *st = winapi_get_state(module);
2069 Py_VISIT(st->overlapped_type);
2070 return 0;
2071}
2072
2073static int
2074winapi_clear(PyObject *module)
2075{
2076 WinApiState *st = winapi_get_state(module);
2077 Py_CLEAR(st->overlapped_type);
2078 return 0;
2079}
2080
2081static void
2082winapi_free(void *module)
2083{
2084 winapi_clear((PyObject *)module);
2085}
2086
Mohamed Koubaae087f7c2020-08-13 09:22:48 -05002087static struct PyModuleDef winapi_module = {
2088 PyModuleDef_HEAD_INIT,
2089 .m_name = "_winapi",
2090 .m_size = sizeof(WinApiState),
2091 .m_methods = winapi_functions,
2092 .m_slots = winapi_slots,
Ken Jin0d399512021-05-29 01:47:15 +08002093 .m_traverse = winapi_traverse,
2094 .m_clear = winapi_clear,
2095 .m_free = winapi_free,
Mohamed Koubaae087f7c2020-08-13 09:22:48 -05002096};
2097
2098PyMODINIT_FUNC
2099PyInit__winapi(void)
2100{
2101 return PyModuleDef_Init(&winapi_module);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02002102}