blob: 7ba14095c96e19453627c0f4a8ccf589a8d396e1 [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"
Mohamed Koubaae087f7c2020-08-13 09:22:48 -050038#include "moduleobject.h" // PyModuleDef_Slot
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{
90 void *state = PyModule_GetState(module);
91 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
115static void
116overlapped_dealloc(OverlappedObject *self)
117{
118 DWORD bytes;
119 int err = GetLastError();
Richard Oudkerk633db6f2013-11-17 13:15:51 +0000120
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200121 if (self->pending) {
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200122 if (check_CancelIoEx() &&
Richard Oudkerk633db6f2013-11-17 13:15:51 +0000123 Py_CancelIoEx(self->handle, &self->overlapped) &&
124 GetOverlappedResult(self->handle, &self->overlapped, &bytes, TRUE))
125 {
126 /* The operation is no longer pending -- nothing to do. */
127 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600128 else if (_Py_IsFinalizing())
Richard Oudkerk633db6f2013-11-17 13:15:51 +0000129 {
130 /* The operation is still pending -- give a warning. This
131 will probably only happen on Windows XP. */
132 PyErr_SetString(PyExc_RuntimeError,
133 "I/O operations still in flight while destroying "
134 "Overlapped object, the process may crash");
135 PyErr_WriteUnraisable(NULL);
136 }
137 else
138 {
139 /* The operation is still pending, but the process is
140 probably about to exit, so we need not worry too much
141 about memory leaks. Leaking self prevents a potential
142 crash. This can happen when a daemon thread is cleaned
143 up at exit -- see #19565. We only expect to get here
144 on Windows XP. */
145 CloseHandle(self->overlapped.hEvent);
146 SetLastError(err);
147 return;
148 }
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200149 }
Richard Oudkerk633db6f2013-11-17 13:15:51 +0000150
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200151 CloseHandle(self->overlapped.hEvent);
152 SetLastError(err);
153 if (self->write_buffer.obj)
154 PyBuffer_Release(&self->write_buffer);
155 Py_CLEAR(self->read_buffer);
Mohamed Koubaae087f7c2020-08-13 09:22:48 -0500156 PyTypeObject *tp = Py_TYPE(self);
157 tp->tp_free(self);
158 Py_DECREF(tp);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200159}
160
Zachary Waref2244ea2015-05-13 01:22:54 -0500161/*[clinic input]
162module _winapi
163class _winapi.Overlapped "OverlappedObject *" "&OverlappedType"
164[clinic start generated code]*/
165/*[clinic end generated code: output=da39a3ee5e6b4b0d input=c13d3f5fd1dabb84]*/
166
167/*[python input]
168def create_converter(type_, format_unit):
169 name = type_ + '_converter'
170 # registered upon creation by CConverter's metaclass
171 type(name, (CConverter,), {'type': type_, 'format_unit': format_unit})
172
173# format unit differs between platforms for these
174create_converter('HANDLE', '" F_HANDLE "')
175create_converter('HMODULE', '" F_HANDLE "')
176create_converter('LPSECURITY_ATTRIBUTES', '" F_POINTER "')
Davin Pottse895de32019-02-23 22:08:16 -0600177create_converter('LPCVOID', '" F_POINTER "')
Zachary Waref2244ea2015-05-13 01:22:54 -0500178
179create_converter('BOOL', 'i') # F_BOOL used previously (always 'i')
180create_converter('DWORD', 'k') # F_DWORD is always "k" (which is much shorter)
181create_converter('LPCTSTR', 's')
Zachary Waref2244ea2015-05-13 01:22:54 -0500182create_converter('UINT', 'I') # F_UINT used previously (always 'I')
183
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +0300184class LPCWSTR_converter(Py_UNICODE_converter):
185 type = 'LPCWSTR'
186
Zachary Waref2244ea2015-05-13 01:22:54 -0500187class HANDLE_return_converter(CReturnConverter):
188 type = 'HANDLE'
189
190 def render(self, function, data):
191 self.declare(data)
192 self.err_occurred_if("_return_value == INVALID_HANDLE_VALUE", data)
193 data.return_conversion.append(
Serhiy Storchaka5dee6552016-06-09 16:16:06 +0300194 'if (_return_value == NULL) {\n Py_RETURN_NONE;\n}\n')
Zachary Waref2244ea2015-05-13 01:22:54 -0500195 data.return_conversion.append(
196 'return_value = HANDLE_TO_PYNUM(_return_value);\n')
197
198class DWORD_return_converter(CReturnConverter):
199 type = 'DWORD'
200
201 def render(self, function, data):
202 self.declare(data)
Victor Stinner850a18e2017-10-24 16:53:32 -0700203 self.err_occurred_if("_return_value == PY_DWORD_MAX", data)
Zachary Waref2244ea2015-05-13 01:22:54 -0500204 data.return_conversion.append(
205 'return_value = Py_BuildValue("k", _return_value);\n')
Davin Pottse895de32019-02-23 22:08:16 -0600206
207class LPVOID_return_converter(CReturnConverter):
208 type = 'LPVOID'
209
210 def render(self, function, data):
211 self.declare(data)
212 self.err_occurred_if("_return_value == NULL", data)
213 data.return_conversion.append(
214 'return_value = HANDLE_TO_PYNUM(_return_value);\n')
Zachary Waref2244ea2015-05-13 01:22:54 -0500215[python start generated code]*/
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +0300216/*[python end generated code: output=da39a3ee5e6b4b0d input=011ee0c3a2244bfe]*/
Zachary Waref2244ea2015-05-13 01:22:54 -0500217
218#include "clinic/_winapi.c.h"
219
220/*[clinic input]
221_winapi.Overlapped.GetOverlappedResult
222
223 wait: bool
224 /
225[clinic start generated code]*/
226
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200227static PyObject *
Zachary Waref2244ea2015-05-13 01:22:54 -0500228_winapi_Overlapped_GetOverlappedResult_impl(OverlappedObject *self, int wait)
229/*[clinic end generated code: output=bdd0c1ed6518cd03 input=194505ee8e0e3565]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200230{
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200231 BOOL res;
232 DWORD transferred = 0;
233 DWORD err;
234
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200235 Py_BEGIN_ALLOW_THREADS
236 res = GetOverlappedResult(self->handle, &self->overlapped, &transferred,
237 wait != 0);
238 Py_END_ALLOW_THREADS
239
240 err = res ? ERROR_SUCCESS : GetLastError();
241 switch (err) {
242 case ERROR_SUCCESS:
243 case ERROR_MORE_DATA:
244 case ERROR_OPERATION_ABORTED:
245 self->completed = 1;
246 self->pending = 0;
247 break;
248 case ERROR_IO_INCOMPLETE:
249 break;
250 default:
251 self->pending = 0;
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +0300252 return PyErr_SetExcFromWindowsErr(PyExc_OSError, err);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200253 }
254 if (self->completed && self->read_buffer != NULL) {
255 assert(PyBytes_CheckExact(self->read_buffer));
256 if (transferred != PyBytes_GET_SIZE(self->read_buffer) &&
257 _PyBytes_Resize(&self->read_buffer, transferred))
258 return NULL;
259 }
260 return Py_BuildValue("II", (unsigned) transferred, (unsigned) err);
261}
262
Zachary Waref2244ea2015-05-13 01:22:54 -0500263/*[clinic input]
264_winapi.Overlapped.getbuffer
265[clinic start generated code]*/
266
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200267static PyObject *
Zachary Waref2244ea2015-05-13 01:22:54 -0500268_winapi_Overlapped_getbuffer_impl(OverlappedObject *self)
269/*[clinic end generated code: output=95a3eceefae0f748 input=347fcfd56b4ceabd]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200270{
271 PyObject *res;
272 if (!self->completed) {
273 PyErr_SetString(PyExc_ValueError,
274 "can't get read buffer before GetOverlappedResult() "
275 "signals the operation completed");
276 return NULL;
277 }
278 res = self->read_buffer ? self->read_buffer : Py_None;
279 Py_INCREF(res);
280 return res;
281}
282
Zachary Waref2244ea2015-05-13 01:22:54 -0500283/*[clinic input]
284_winapi.Overlapped.cancel
285[clinic start generated code]*/
286
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200287static PyObject *
Zachary Waref2244ea2015-05-13 01:22:54 -0500288_winapi_Overlapped_cancel_impl(OverlappedObject *self)
289/*[clinic end generated code: output=fcb9ab5df4ebdae5 input=cbf3da142290039f]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200290{
291 BOOL res = TRUE;
292
293 if (self->pending) {
294 Py_BEGIN_ALLOW_THREADS
295 if (check_CancelIoEx())
296 res = Py_CancelIoEx(self->handle, &self->overlapped);
297 else
298 res = CancelIo(self->handle);
299 Py_END_ALLOW_THREADS
300 }
301
302 /* CancelIoEx returns ERROR_NOT_FOUND if the I/O completed in-between */
303 if (!res && GetLastError() != ERROR_NOT_FOUND)
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +0300304 return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200305 self->pending = 0;
306 Py_RETURN_NONE;
307}
308
309static PyMethodDef overlapped_methods[] = {
Zachary Waref2244ea2015-05-13 01:22:54 -0500310 _WINAPI_OVERLAPPED_GETOVERLAPPEDRESULT_METHODDEF
311 _WINAPI_OVERLAPPED_GETBUFFER_METHODDEF
312 _WINAPI_OVERLAPPED_CANCEL_METHODDEF
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200313 {NULL}
314};
315
316static PyMemberDef overlapped_members[] = {
317 {"event", T_HANDLE,
318 offsetof(OverlappedObject, overlapped) + offsetof(OVERLAPPED, hEvent),
319 READONLY, "overlapped event handle"},
320 {NULL}
321};
322
Mohamed Koubaae087f7c2020-08-13 09:22:48 -0500323static PyType_Slot winapi_overlapped_type_slots[] = {
324 {Py_tp_dealloc, overlapped_dealloc},
325 {Py_tp_doc, "OVERLAPPED structure wrapper"},
326 {Py_tp_methods, overlapped_methods},
327 {Py_tp_members, overlapped_members},
328 {0,0}
329};
330
331static PyType_Spec winapi_overlapped_type_spec = {
332 .name = "_winapi.Overlapped",
333 .basicsize = sizeof(OverlappedObject),
334 .flags = Py_TPFLAGS_DEFAULT,
335 .slots = winapi_overlapped_type_slots,
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200336};
337
338static OverlappedObject *
Mohamed Koubaae087f7c2020-08-13 09:22:48 -0500339new_overlapped(PyObject *module, HANDLE handle)
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200340{
Mohamed Koubaae087f7c2020-08-13 09:22:48 -0500341 WinApiState *st = winapi_get_state(module);
342 OverlappedObject *self = PyObject_New(OverlappedObject, st->overlapped_type);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200343 if (!self)
344 return NULL;
Mohamed Koubaae087f7c2020-08-13 09:22:48 -0500345
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200346 self->handle = handle;
347 self->read_buffer = NULL;
348 self->pending = 0;
349 self->completed = 0;
350 memset(&self->overlapped, 0, sizeof(OVERLAPPED));
351 memset(&self->write_buffer, 0, sizeof(Py_buffer));
352 /* Manual reset, initially non-signalled */
353 self->overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
354 return self;
355}
356
357/* -------------------------------------------------------------------- */
358/* windows API functions */
359
Zachary Waref2244ea2015-05-13 01:22:54 -0500360/*[clinic input]
361_winapi.CloseHandle
362
363 handle: HANDLE
364 /
365
366Close handle.
367[clinic start generated code]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200368
369static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300370_winapi_CloseHandle_impl(PyObject *module, HANDLE handle)
371/*[clinic end generated code: output=7ad37345f07bd782 input=7f0e4ac36e0352b8]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200372{
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200373 BOOL success;
374
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200375 Py_BEGIN_ALLOW_THREADS
Zachary Waref2244ea2015-05-13 01:22:54 -0500376 success = CloseHandle(handle);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200377 Py_END_ALLOW_THREADS
378
379 if (!success)
380 return PyErr_SetFromWindowsErr(0);
381
382 Py_RETURN_NONE;
383}
384
Zachary Waref2244ea2015-05-13 01:22:54 -0500385/*[clinic input]
386_winapi.ConnectNamedPipe
387
388 handle: HANDLE
Serhiy Storchaka202fda52017-03-12 10:10:47 +0200389 overlapped as use_overlapped: bool(accept={int}) = False
Zachary Waref2244ea2015-05-13 01:22:54 -0500390[clinic start generated code]*/
391
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200392static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300393_winapi_ConnectNamedPipe_impl(PyObject *module, HANDLE handle,
Zachary Ware77772c02015-05-13 10:58:35 -0500394 int use_overlapped)
Serhiy Storchaka202fda52017-03-12 10:10:47 +0200395/*[clinic end generated code: output=335a0e7086800671 input=34f937c1c86e5e68]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200396{
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200397 BOOL success;
398 OverlappedObject *overlapped = NULL;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200399
400 if (use_overlapped) {
Mohamed Koubaae087f7c2020-08-13 09:22:48 -0500401 overlapped = new_overlapped(module, handle);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200402 if (!overlapped)
403 return NULL;
404 }
405
406 Py_BEGIN_ALLOW_THREADS
Zachary Waref2244ea2015-05-13 01:22:54 -0500407 success = ConnectNamedPipe(handle,
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200408 overlapped ? &overlapped->overlapped : NULL);
409 Py_END_ALLOW_THREADS
410
411 if (overlapped) {
412 int err = GetLastError();
413 /* Overlapped ConnectNamedPipe never returns a success code */
414 assert(success == 0);
415 if (err == ERROR_IO_PENDING)
416 overlapped->pending = 1;
417 else if (err == ERROR_PIPE_CONNECTED)
418 SetEvent(overlapped->overlapped.hEvent);
419 else {
420 Py_DECREF(overlapped);
421 return PyErr_SetFromWindowsErr(err);
422 }
423 return (PyObject *) overlapped;
424 }
425 if (!success)
426 return PyErr_SetFromWindowsErr(0);
427
428 Py_RETURN_NONE;
429}
430
Zachary Waref2244ea2015-05-13 01:22:54 -0500431/*[clinic input]
432_winapi.CreateFile -> HANDLE
433
434 file_name: LPCTSTR
435 desired_access: DWORD
436 share_mode: DWORD
437 security_attributes: LPSECURITY_ATTRIBUTES
438 creation_disposition: DWORD
439 flags_and_attributes: DWORD
440 template_file: HANDLE
441 /
442[clinic start generated code]*/
443
444static HANDLE
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300445_winapi_CreateFile_impl(PyObject *module, LPCTSTR file_name,
Zachary Ware77772c02015-05-13 10:58:35 -0500446 DWORD desired_access, DWORD share_mode,
447 LPSECURITY_ATTRIBUTES security_attributes,
448 DWORD creation_disposition,
449 DWORD flags_and_attributes, HANDLE template_file)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300450/*[clinic end generated code: output=417ddcebfc5a3d53 input=6423c3e40372dbd5]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200451{
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200452 HANDLE handle;
453
Steve Dowerb82e17e2019-05-23 08:45:22 -0700454 if (PySys_Audit("_winapi.CreateFile", "uIIII",
455 file_name, desired_access, share_mode,
456 creation_disposition, flags_and_attributes) < 0) {
457 return INVALID_HANDLE_VALUE;
458 }
459
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200460 Py_BEGIN_ALLOW_THREADS
Zachary Waref2244ea2015-05-13 01:22:54 -0500461 handle = CreateFile(file_name, desired_access,
462 share_mode, security_attributes,
463 creation_disposition,
464 flags_and_attributes, template_file);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200465 Py_END_ALLOW_THREADS
466
467 if (handle == INVALID_HANDLE_VALUE)
Zachary Waref2244ea2015-05-13 01:22:54 -0500468 PyErr_SetFromWindowsErr(0);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200469
Zachary Waref2244ea2015-05-13 01:22:54 -0500470 return handle;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200471}
472
Zachary Waref2244ea2015-05-13 01:22:54 -0500473/*[clinic input]
Davin Pottse895de32019-02-23 22:08:16 -0600474_winapi.CreateFileMapping -> HANDLE
475
476 file_handle: HANDLE
477 security_attributes: LPSECURITY_ATTRIBUTES
478 protect: DWORD
479 max_size_high: DWORD
480 max_size_low: DWORD
481 name: LPCWSTR
482 /
483[clinic start generated code]*/
484
485static HANDLE
486_winapi_CreateFileMapping_impl(PyObject *module, HANDLE file_handle,
487 LPSECURITY_ATTRIBUTES security_attributes,
488 DWORD protect, DWORD max_size_high,
489 DWORD max_size_low, LPCWSTR name)
490/*[clinic end generated code: output=6c0a4d5cf7f6fcc6 input=3dc5cf762a74dee8]*/
491{
492 HANDLE handle;
493
494 Py_BEGIN_ALLOW_THREADS
495 handle = CreateFileMappingW(file_handle, security_attributes,
496 protect, max_size_high, max_size_low,
497 name);
498 Py_END_ALLOW_THREADS
499
500 if (handle == NULL) {
Zackery Spytzeda385c2019-05-30 01:58:50 -0600501 PyObject *temp = PyUnicode_FromWideChar(name, -1);
502 PyErr_SetExcFromWindowsErrWithFilenameObject(PyExc_OSError, 0, temp);
503 Py_XDECREF(temp);
Davin Pottse895de32019-02-23 22:08:16 -0600504 handle = INVALID_HANDLE_VALUE;
505 }
506
507 return handle;
508}
509
510/*[clinic input]
Zachary Waref2244ea2015-05-13 01:22:54 -0500511_winapi.CreateJunction
Tim Golden0321cf22014-05-05 19:46:17 +0100512
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +0300513 src_path: LPCWSTR
514 dst_path: LPCWSTR
Zachary Waref2244ea2015-05-13 01:22:54 -0500515 /
516[clinic start generated code]*/
517
518static PyObject *
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +0300519_winapi_CreateJunction_impl(PyObject *module, LPCWSTR src_path,
520 LPCWSTR dst_path)
521/*[clinic end generated code: output=44b3f5e9bbcc4271 input=963d29b44b9384a7]*/
Zachary Waref2244ea2015-05-13 01:22:54 -0500522{
Tim Golden0321cf22014-05-05 19:46:17 +0100523 /* Privilege adjustment */
524 HANDLE token = NULL;
525 TOKEN_PRIVILEGES tp;
526
527 /* Reparse data buffer */
528 const USHORT prefix_len = 4;
529 USHORT print_len = 0;
530 USHORT rdb_size = 0;
Martin Panter70214ad2016-08-04 02:38:59 +0000531 _Py_PREPARSE_DATA_BUFFER rdb = NULL;
Tim Golden0321cf22014-05-05 19:46:17 +0100532
533 /* Junction point creation */
534 HANDLE junction = NULL;
535 DWORD ret = 0;
536
Tim Golden0321cf22014-05-05 19:46:17 +0100537 if (src_path == NULL || dst_path == NULL)
538 return PyErr_SetFromWindowsErr(ERROR_INVALID_PARAMETER);
539
540 if (wcsncmp(src_path, L"\\??\\", prefix_len) == 0)
541 return PyErr_SetFromWindowsErr(ERROR_INVALID_PARAMETER);
542
Steve Dowerb82e17e2019-05-23 08:45:22 -0700543 if (PySys_Audit("_winapi.CreateJunction", "uu", src_path, dst_path) < 0) {
544 return NULL;
545 }
546
Tim Golden0321cf22014-05-05 19:46:17 +0100547 /* Adjust privileges to allow rewriting directory entry as a
548 junction point. */
549 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &token))
550 goto cleanup;
551
552 if (!LookupPrivilegeValue(NULL, SE_RESTORE_NAME, &tp.Privileges[0].Luid))
553 goto cleanup;
554
555 tp.PrivilegeCount = 1;
556 tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
557 if (!AdjustTokenPrivileges(token, FALSE, &tp, sizeof(TOKEN_PRIVILEGES),
558 NULL, NULL))
559 goto cleanup;
560
561 if (GetFileAttributesW(src_path) == INVALID_FILE_ATTRIBUTES)
562 goto cleanup;
563
564 /* Store the absolute link target path length in print_len. */
565 print_len = (USHORT)GetFullPathNameW(src_path, 0, NULL, NULL);
566 if (print_len == 0)
567 goto cleanup;
568
569 /* NUL terminator should not be part of print_len. */
570 --print_len;
571
572 /* REPARSE_DATA_BUFFER usage is heavily under-documented, especially for
573 junction points. Here's what I've learned along the way:
574 - A junction point has two components: a print name and a substitute
575 name. They both describe the link target, but the substitute name is
576 the physical target and the print name is shown in directory listings.
577 - The print name must be a native name, prefixed with "\??\".
578 - Both names are stored after each other in the same buffer (the
579 PathBuffer) and both must be NUL-terminated.
580 - There are four members defining their respective offset and length
581 inside PathBuffer: SubstituteNameOffset, SubstituteNameLength,
582 PrintNameOffset and PrintNameLength.
583 - The total size we need to allocate for the REPARSE_DATA_BUFFER, thus,
584 is the sum of:
585 - the fixed header size (REPARSE_DATA_BUFFER_HEADER_SIZE)
586 - the size of the MountPointReparseBuffer member without the PathBuffer
587 - the size of the prefix ("\??\") in bytes
588 - the size of the print name in bytes
589 - the size of the substitute name in bytes
590 - the size of two NUL terminators in bytes */
Martin Panter70214ad2016-08-04 02:38:59 +0000591 rdb_size = _Py_REPARSE_DATA_BUFFER_HEADER_SIZE +
Tim Golden0321cf22014-05-05 19:46:17 +0100592 sizeof(rdb->MountPointReparseBuffer) -
593 sizeof(rdb->MountPointReparseBuffer.PathBuffer) +
594 /* Two +1's for NUL terminators. */
595 (prefix_len + print_len + 1 + print_len + 1) * sizeof(WCHAR);
Andy Lester7668a8b2020-03-24 23:26:44 -0500596 rdb = (_Py_PREPARSE_DATA_BUFFER)PyMem_RawCalloc(1, rdb_size);
Tim Golden0321cf22014-05-05 19:46:17 +0100597 if (rdb == NULL)
598 goto cleanup;
599
Tim Golden0321cf22014-05-05 19:46:17 +0100600 rdb->ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
Martin Panter70214ad2016-08-04 02:38:59 +0000601 rdb->ReparseDataLength = rdb_size - _Py_REPARSE_DATA_BUFFER_HEADER_SIZE;
Tim Golden0321cf22014-05-05 19:46:17 +0100602 rdb->MountPointReparseBuffer.SubstituteNameOffset = 0;
603 rdb->MountPointReparseBuffer.SubstituteNameLength =
604 (prefix_len + print_len) * sizeof(WCHAR);
605 rdb->MountPointReparseBuffer.PrintNameOffset =
606 rdb->MountPointReparseBuffer.SubstituteNameLength + sizeof(WCHAR);
607 rdb->MountPointReparseBuffer.PrintNameLength = print_len * sizeof(WCHAR);
608
609 /* Store the full native path of link target at the substitute name
610 offset (0). */
611 wcscpy(rdb->MountPointReparseBuffer.PathBuffer, L"\\??\\");
612 if (GetFullPathNameW(src_path, print_len + 1,
613 rdb->MountPointReparseBuffer.PathBuffer + prefix_len,
614 NULL) == 0)
615 goto cleanup;
616
617 /* Copy everything but the native prefix to the print name offset. */
618 wcscpy(rdb->MountPointReparseBuffer.PathBuffer +
619 prefix_len + print_len + 1,
620 rdb->MountPointReparseBuffer.PathBuffer + prefix_len);
621
622 /* Create a directory for the junction point. */
623 if (!CreateDirectoryW(dst_path, NULL))
624 goto cleanup;
625
626 junction = CreateFileW(dst_path, GENERIC_READ | GENERIC_WRITE, 0, NULL,
627 OPEN_EXISTING,
628 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, NULL);
629 if (junction == INVALID_HANDLE_VALUE)
630 goto cleanup;
631
632 /* Make the directory entry a junction point. */
633 if (!DeviceIoControl(junction, FSCTL_SET_REPARSE_POINT, rdb, rdb_size,
634 NULL, 0, &ret, NULL))
635 goto cleanup;
636
637cleanup:
638 ret = GetLastError();
639
640 CloseHandle(token);
641 CloseHandle(junction);
642 PyMem_RawFree(rdb);
643
644 if (ret != 0)
645 return PyErr_SetFromWindowsErr(ret);
646
647 Py_RETURN_NONE;
648}
649
Zachary Waref2244ea2015-05-13 01:22:54 -0500650/*[clinic input]
651_winapi.CreateNamedPipe -> HANDLE
652
653 name: LPCTSTR
654 open_mode: DWORD
655 pipe_mode: DWORD
656 max_instances: DWORD
657 out_buffer_size: DWORD
658 in_buffer_size: DWORD
659 default_timeout: DWORD
660 security_attributes: LPSECURITY_ATTRIBUTES
661 /
662[clinic start generated code]*/
663
664static HANDLE
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300665_winapi_CreateNamedPipe_impl(PyObject *module, LPCTSTR name, DWORD open_mode,
666 DWORD pipe_mode, DWORD max_instances,
667 DWORD out_buffer_size, DWORD in_buffer_size,
668 DWORD default_timeout,
Zachary Ware77772c02015-05-13 10:58:35 -0500669 LPSECURITY_ATTRIBUTES security_attributes)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300670/*[clinic end generated code: output=80f8c07346a94fbc input=5a73530b84d8bc37]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200671{
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200672 HANDLE handle;
673
Steve Dowerb82e17e2019-05-23 08:45:22 -0700674 if (PySys_Audit("_winapi.CreateNamedPipe", "uII",
675 name, open_mode, pipe_mode) < 0) {
676 return INVALID_HANDLE_VALUE;
677 }
678
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200679 Py_BEGIN_ALLOW_THREADS
Zachary Waref2244ea2015-05-13 01:22:54 -0500680 handle = CreateNamedPipe(name, open_mode, pipe_mode,
681 max_instances, out_buffer_size,
682 in_buffer_size, default_timeout,
683 security_attributes);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200684 Py_END_ALLOW_THREADS
685
686 if (handle == INVALID_HANDLE_VALUE)
Zachary Waref2244ea2015-05-13 01:22:54 -0500687 PyErr_SetFromWindowsErr(0);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200688
Zachary Waref2244ea2015-05-13 01:22:54 -0500689 return handle;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200690}
691
Zachary Waref2244ea2015-05-13 01:22:54 -0500692/*[clinic input]
693_winapi.CreatePipe
694
695 pipe_attrs: object
696 Ignored internally, can be None.
697 size: DWORD
698 /
699
700Create an anonymous pipe.
701
702Returns a 2-tuple of handles, to the read and write ends of the pipe.
703[clinic start generated code]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200704
705static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300706_winapi_CreatePipe_impl(PyObject *module, PyObject *pipe_attrs, DWORD size)
707/*[clinic end generated code: output=1c4411d8699f0925 input=c4f2cfa56ef68d90]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200708{
709 HANDLE read_pipe;
710 HANDLE write_pipe;
711 BOOL result;
712
Steve Dowerb82e17e2019-05-23 08:45:22 -0700713 if (PySys_Audit("_winapi.CreatePipe", NULL) < 0) {
714 return NULL;
715 }
716
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200717 Py_BEGIN_ALLOW_THREADS
718 result = CreatePipe(&read_pipe, &write_pipe, NULL, size);
719 Py_END_ALLOW_THREADS
720
721 if (! result)
722 return PyErr_SetFromWindowsErr(GetLastError());
723
724 return Py_BuildValue(
725 "NN", HANDLE_TO_PYNUM(read_pipe), HANDLE_TO_PYNUM(write_pipe));
726}
727
728/* helpers for createprocess */
729
730static unsigned long
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200731getulong(PyObject* obj, const char* name)
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200732{
733 PyObject* value;
734 unsigned long ret;
735
736 value = PyObject_GetAttrString(obj, name);
737 if (! value) {
738 PyErr_Clear(); /* FIXME: propagate error? */
739 return 0;
740 }
741 ret = PyLong_AsUnsignedLong(value);
742 Py_DECREF(value);
743 return ret;
744}
745
746static HANDLE
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200747gethandle(PyObject* obj, const char* name)
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200748{
749 PyObject* value;
750 HANDLE ret;
751
752 value = PyObject_GetAttrString(obj, name);
753 if (! value) {
754 PyErr_Clear(); /* FIXME: propagate error? */
755 return NULL;
756 }
757 if (value == Py_None)
758 ret = NULL;
759 else
760 ret = PYNUM_TO_HANDLE(value);
761 Py_DECREF(value);
762 return ret;
763}
764
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +0200765static wchar_t *
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200766getenvironment(PyObject* environment)
767{
768 Py_ssize_t i, envsize, totalsize;
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +0200769 wchar_t *buffer = NULL, *p, *end;
770 PyObject *keys, *values;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200771
Ezio Melotti85a86292013-08-17 16:57:41 +0300772 /* convert environment dictionary to windows environment string */
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200773 if (! PyMapping_Check(environment)) {
774 PyErr_SetString(
775 PyExc_TypeError, "environment must be dictionary or None");
776 return NULL;
777 }
778
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200779 keys = PyMapping_Keys(environment);
Oren Milman0b3a87e2017-09-14 22:30:28 +0300780 if (!keys) {
781 return NULL;
782 }
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200783 values = PyMapping_Values(environment);
Oren Milman0b3a87e2017-09-14 22:30:28 +0300784 if (!values) {
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200785 goto error;
Oren Milman0b3a87e2017-09-14 22:30:28 +0300786 }
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200787
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +0200788 envsize = PyList_GET_SIZE(keys);
789 if (PyList_GET_SIZE(values) != envsize) {
Serhiy Storchakabf623ae2017-04-19 20:03:52 +0300790 PyErr_SetString(PyExc_RuntimeError,
791 "environment changed size during iteration");
792 goto error;
793 }
794
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200795 totalsize = 1; /* trailing null character */
796 for (i = 0; i < envsize; i++) {
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +0200797 PyObject* key = PyList_GET_ITEM(keys, i);
798 PyObject* value = PyList_GET_ITEM(values, i);
799 Py_ssize_t size;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200800
801 if (! PyUnicode_Check(key) || ! PyUnicode_Check(value)) {
802 PyErr_SetString(PyExc_TypeError,
803 "environment can only contain strings");
804 goto error;
805 }
Serhiy Storchakad174d242017-06-23 19:39:27 +0300806 if (PyUnicode_FindChar(key, '\0', 0, PyUnicode_GET_LENGTH(key), 1) != -1 ||
807 PyUnicode_FindChar(value, '\0', 0, PyUnicode_GET_LENGTH(value), 1) != -1)
808 {
809 PyErr_SetString(PyExc_ValueError, "embedded null character");
810 goto error;
811 }
812 /* Search from index 1 because on Windows starting '=' is allowed for
813 defining hidden environment variables. */
814 if (PyUnicode_GET_LENGTH(key) == 0 ||
815 PyUnicode_FindChar(key, '=', 1, PyUnicode_GET_LENGTH(key), 1) != -1)
816 {
817 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
818 goto error;
819 }
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +0200820
821 size = PyUnicode_AsWideChar(key, NULL, 0);
822 assert(size > 1);
823 if (totalsize > PY_SSIZE_T_MAX - size) {
Benjamin Peterson8ce68062015-02-09 20:58:12 -0500824 PyErr_SetString(PyExc_OverflowError, "environment too long");
825 goto error;
826 }
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +0200827 totalsize += size; /* including '=' */
828
829 size = PyUnicode_AsWideChar(value, NULL, 0);
830 assert(size > 0);
831 if (totalsize > PY_SSIZE_T_MAX - size) {
Benjamin Peterson8ce68062015-02-09 20:58:12 -0500832 PyErr_SetString(PyExc_OverflowError, "environment too long");
833 goto error;
834 }
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +0200835 totalsize += size; /* including trailing '\0' */
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200836 }
837
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +0200838 buffer = PyMem_NEW(wchar_t, totalsize);
Benjamin Peterson8ce68062015-02-09 20:58:12 -0500839 if (! buffer) {
840 PyErr_NoMemory();
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200841 goto error;
Benjamin Peterson8ce68062015-02-09 20:58:12 -0500842 }
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200843 p = buffer;
844 end = buffer + totalsize;
845
846 for (i = 0; i < envsize; i++) {
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +0200847 PyObject* key = PyList_GET_ITEM(keys, i);
848 PyObject* value = PyList_GET_ITEM(values, i);
849 Py_ssize_t size = PyUnicode_AsWideChar(key, p, end - p);
850 assert(1 <= size && size < end - p);
851 p += size;
852 *p++ = L'=';
853 size = PyUnicode_AsWideChar(value, p, end - p);
854 assert(0 <= size && size < end - p);
855 p += size + 1;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200856 }
857
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +0200858 /* add trailing null character */
859 *p++ = L'\0';
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200860 assert(p == end);
861
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200862 error:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200863 Py_XDECREF(keys);
864 Py_XDECREF(values);
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +0200865 return buffer;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200866}
867
Segev Finerb2a60832017-12-18 11:28:19 +0200868static LPHANDLE
869gethandlelist(PyObject *mapping, const char *name, Py_ssize_t *size)
870{
871 LPHANDLE ret = NULL;
872 PyObject *value_fast = NULL;
873 PyObject *value;
874 Py_ssize_t i;
875
876 value = PyMapping_GetItemString(mapping, name);
877 if (!value) {
878 PyErr_Clear();
879 return NULL;
880 }
881
882 if (value == Py_None) {
883 goto cleanup;
884 }
885
886 value_fast = PySequence_Fast(value, "handle_list must be a sequence or None");
887 if (value_fast == NULL)
888 goto cleanup;
889
890 *size = PySequence_Fast_GET_SIZE(value_fast) * sizeof(HANDLE);
891
892 /* Passing an empty array causes CreateProcess to fail so just don't set it */
893 if (*size == 0) {
894 goto cleanup;
895 }
896
897 ret = PyMem_Malloc(*size);
898 if (ret == NULL)
899 goto cleanup;
900
901 for (i = 0; i < PySequence_Fast_GET_SIZE(value_fast); i++) {
902 ret[i] = PYNUM_TO_HANDLE(PySequence_Fast_GET_ITEM(value_fast, i));
903 if (ret[i] == (HANDLE)-1 && PyErr_Occurred()) {
904 PyMem_Free(ret);
905 ret = NULL;
906 goto cleanup;
907 }
908 }
909
910cleanup:
911 Py_DECREF(value);
912 Py_XDECREF(value_fast);
913 return ret;
914}
915
916typedef struct {
917 LPPROC_THREAD_ATTRIBUTE_LIST attribute_list;
918 LPHANDLE handle_list;
919} AttributeList;
920
921static void
922freeattributelist(AttributeList *attribute_list)
923{
924 if (attribute_list->attribute_list != NULL) {
925 DeleteProcThreadAttributeList(attribute_list->attribute_list);
926 PyMem_Free(attribute_list->attribute_list);
927 }
928
929 PyMem_Free(attribute_list->handle_list);
930
931 memset(attribute_list, 0, sizeof(*attribute_list));
932}
933
934static int
935getattributelist(PyObject *obj, const char *name, AttributeList *attribute_list)
936{
937 int ret = 0;
938 DWORD err;
939 BOOL result;
940 PyObject *value;
941 Py_ssize_t handle_list_size;
942 DWORD attribute_count = 0;
943 SIZE_T attribute_list_size = 0;
944
945 value = PyObject_GetAttrString(obj, name);
946 if (!value) {
947 PyErr_Clear(); /* FIXME: propagate error? */
948 return 0;
949 }
950
951 if (value == Py_None) {
952 ret = 0;
953 goto cleanup;
954 }
955
956 if (!PyMapping_Check(value)) {
957 ret = -1;
958 PyErr_Format(PyExc_TypeError, "%s must be a mapping or None", name);
959 goto cleanup;
960 }
961
962 attribute_list->handle_list = gethandlelist(value, "handle_list", &handle_list_size);
963 if (attribute_list->handle_list == NULL && PyErr_Occurred()) {
964 ret = -1;
965 goto cleanup;
966 }
967
968 if (attribute_list->handle_list != NULL)
969 ++attribute_count;
970
971 /* Get how many bytes we need for the attribute list */
972 result = InitializeProcThreadAttributeList(NULL, attribute_count, 0, &attribute_list_size);
973 if (result || GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
974 ret = -1;
975 PyErr_SetFromWindowsErr(GetLastError());
976 goto cleanup;
977 }
978
979 attribute_list->attribute_list = PyMem_Malloc(attribute_list_size);
980 if (attribute_list->attribute_list == NULL) {
981 ret = -1;
982 goto cleanup;
983 }
984
985 result = InitializeProcThreadAttributeList(
986 attribute_list->attribute_list,
987 attribute_count,
988 0,
989 &attribute_list_size);
990 if (!result) {
991 err = GetLastError();
992
993 /* So that we won't call DeleteProcThreadAttributeList */
994 PyMem_Free(attribute_list->attribute_list);
995 attribute_list->attribute_list = NULL;
996
997 ret = -1;
998 PyErr_SetFromWindowsErr(err);
999 goto cleanup;
1000 }
1001
1002 if (attribute_list->handle_list != NULL) {
1003 result = UpdateProcThreadAttribute(
1004 attribute_list->attribute_list,
1005 0,
1006 PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
1007 attribute_list->handle_list,
1008 handle_list_size,
1009 NULL,
1010 NULL);
1011 if (!result) {
1012 ret = -1;
1013 PyErr_SetFromWindowsErr(GetLastError());
1014 goto cleanup;
1015 }
1016 }
1017
1018cleanup:
1019 Py_DECREF(value);
1020
1021 if (ret < 0)
1022 freeattributelist(attribute_list);
1023
1024 return ret;
1025}
1026
Zachary Waref2244ea2015-05-13 01:22:54 -05001027/*[clinic input]
1028_winapi.CreateProcess
1029
Zachary Ware77772c02015-05-13 10:58:35 -05001030 application_name: Py_UNICODE(accept={str, NoneType})
Vladimir Matveev7b360162018-12-14 00:30:51 -08001031 command_line: object
1032 Can be str or None
Zachary Waref2244ea2015-05-13 01:22:54 -05001033 proc_attrs: object
1034 Ignored internally, can be None.
1035 thread_attrs: object
1036 Ignored internally, can be None.
1037 inherit_handles: BOOL
1038 creation_flags: DWORD
1039 env_mapping: object
Zachary Ware77772c02015-05-13 10:58:35 -05001040 current_directory: Py_UNICODE(accept={str, NoneType})
Zachary Waref2244ea2015-05-13 01:22:54 -05001041 startup_info: object
1042 /
1043
1044Create a new process and its primary thread.
1045
1046The return value is a tuple of the process handle, thread handle,
1047process ID, and thread ID.
1048[clinic start generated code]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001049
1050static PyObject *
Serhiy Storchakaafb3e712018-12-14 11:19:51 +02001051_winapi_CreateProcess_impl(PyObject *module,
1052 const Py_UNICODE *application_name,
Vladimir Matveev7b360162018-12-14 00:30:51 -08001053 PyObject *command_line, PyObject *proc_attrs,
Zachary Ware77772c02015-05-13 10:58:35 -05001054 PyObject *thread_attrs, BOOL inherit_handles,
1055 DWORD creation_flags, PyObject *env_mapping,
Serhiy Storchakaafb3e712018-12-14 11:19:51 +02001056 const Py_UNICODE *current_directory,
Zachary Ware77772c02015-05-13 10:58:35 -05001057 PyObject *startup_info)
Serhiy Storchakaafb3e712018-12-14 11:19:51 +02001058/*[clinic end generated code: output=9b2423a609230132 input=42ac293eaea03fc4]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001059{
Segev Finerb2a60832017-12-18 11:28:19 +02001060 PyObject *ret = NULL;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001061 BOOL result;
1062 PROCESS_INFORMATION pi;
Segev Finerb2a60832017-12-18 11:28:19 +02001063 STARTUPINFOEXW si;
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +02001064 wchar_t *wenvironment = NULL;
Vladimir Matveev7b360162018-12-14 00:30:51 -08001065 wchar_t *command_line_copy = NULL;
Segev Finerb2a60832017-12-18 11:28:19 +02001066 AttributeList attribute_list = {0};
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001067
Steve Dowerb82e17e2019-05-23 08:45:22 -07001068 if (PySys_Audit("_winapi.CreateProcess", "uuu", application_name,
1069 command_line, current_directory) < 0) {
1070 return NULL;
1071 }
1072
Victor Stinner252346a2020-05-01 11:33:44 +02001073 PyInterpreterState *interp = PyInterpreterState_Get();
1074 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
1075 if (config->_isolated_interpreter) {
1076 PyErr_SetString(PyExc_RuntimeError,
1077 "subprocess not supported for isolated subinterpreters");
1078 return NULL;
1079 }
1080
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001081 ZeroMemory(&si, sizeof(si));
Segev Finerb2a60832017-12-18 11:28:19 +02001082 si.StartupInfo.cb = sizeof(si);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001083
1084 /* note: we only support a small subset of all SI attributes */
Segev Finerb2a60832017-12-18 11:28:19 +02001085 si.StartupInfo.dwFlags = getulong(startup_info, "dwFlags");
1086 si.StartupInfo.wShowWindow = (WORD)getulong(startup_info, "wShowWindow");
1087 si.StartupInfo.hStdInput = gethandle(startup_info, "hStdInput");
1088 si.StartupInfo.hStdOutput = gethandle(startup_info, "hStdOutput");
1089 si.StartupInfo.hStdError = gethandle(startup_info, "hStdError");
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001090 if (PyErr_Occurred())
Segev Finerb2a60832017-12-18 11:28:19 +02001091 goto cleanup;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001092
1093 if (env_mapping != Py_None) {
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +02001094 wenvironment = getenvironment(env_mapping);
Serhiy Storchakad174d242017-06-23 19:39:27 +03001095 if (wenvironment == NULL) {
Segev Finerb2a60832017-12-18 11:28:19 +02001096 goto cleanup;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001097 }
1098 }
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001099
Segev Finerb2a60832017-12-18 11:28:19 +02001100 if (getattributelist(startup_info, "lpAttributeList", &attribute_list) < 0)
1101 goto cleanup;
1102
1103 si.lpAttributeList = attribute_list.attribute_list;
Vladimir Matveev7b360162018-12-14 00:30:51 -08001104 if (PyUnicode_Check(command_line)) {
1105 command_line_copy = PyUnicode_AsWideCharString(command_line, NULL);
1106 if (command_line_copy == NULL) {
1107 goto cleanup;
1108 }
1109 }
1110 else if (command_line != Py_None) {
Victor Stinner4a21e572020-04-15 02:35:41 +02001111 PyErr_Format(PyExc_TypeError,
1112 "CreateProcess() argument 2 must be str or None, not %s",
Vladimir Matveev7b360162018-12-14 00:30:51 -08001113 Py_TYPE(command_line)->tp_name);
1114 goto cleanup;
1115 }
1116
Segev Finerb2a60832017-12-18 11:28:19 +02001117
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001118 Py_BEGIN_ALLOW_THREADS
1119 result = CreateProcessW(application_name,
Vladimir Matveev7b360162018-12-14 00:30:51 -08001120 command_line_copy,
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001121 NULL,
1122 NULL,
1123 inherit_handles,
Segev Finerb2a60832017-12-18 11:28:19 +02001124 creation_flags | EXTENDED_STARTUPINFO_PRESENT |
1125 CREATE_UNICODE_ENVIRONMENT,
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001126 wenvironment,
1127 current_directory,
Segev Finerb2a60832017-12-18 11:28:19 +02001128 (LPSTARTUPINFOW)&si,
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001129 &pi);
1130 Py_END_ALLOW_THREADS
1131
Segev Finerb2a60832017-12-18 11:28:19 +02001132 if (!result) {
1133 PyErr_SetFromWindowsErr(GetLastError());
1134 goto cleanup;
1135 }
1136
1137 ret = Py_BuildValue("NNkk",
1138 HANDLE_TO_PYNUM(pi.hProcess),
1139 HANDLE_TO_PYNUM(pi.hThread),
1140 pi.dwProcessId,
1141 pi.dwThreadId);
1142
1143cleanup:
Vladimir Matveev7b360162018-12-14 00:30:51 -08001144 PyMem_Free(command_line_copy);
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +02001145 PyMem_Free(wenvironment);
Segev Finerb2a60832017-12-18 11:28:19 +02001146 freeattributelist(&attribute_list);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001147
Segev Finerb2a60832017-12-18 11:28:19 +02001148 return ret;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001149}
1150
Zachary Waref2244ea2015-05-13 01:22:54 -05001151/*[clinic input]
1152_winapi.DuplicateHandle -> HANDLE
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001153
Zachary Waref2244ea2015-05-13 01:22:54 -05001154 source_process_handle: HANDLE
1155 source_handle: HANDLE
1156 target_process_handle: HANDLE
1157 desired_access: DWORD
1158 inherit_handle: BOOL
1159 options: DWORD = 0
1160 /
1161
1162Return a duplicate handle object.
1163
1164The duplicate handle refers to the same object as the original
1165handle. Therefore, any changes to the object are reflected
1166through both handles.
1167[clinic start generated code]*/
1168
1169static HANDLE
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001170_winapi_DuplicateHandle_impl(PyObject *module, HANDLE source_process_handle,
Zachary Ware77772c02015-05-13 10:58:35 -05001171 HANDLE source_handle,
1172 HANDLE target_process_handle,
1173 DWORD desired_access, BOOL inherit_handle,
1174 DWORD options)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001175/*[clinic end generated code: output=ad9711397b5dcd4e input=b933e3f2356a8c12]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001176{
1177 HANDLE target_handle;
1178 BOOL result;
1179
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001180 Py_BEGIN_ALLOW_THREADS
1181 result = DuplicateHandle(
1182 source_process_handle,
1183 source_handle,
1184 target_process_handle,
1185 &target_handle,
1186 desired_access,
1187 inherit_handle,
1188 options
1189 );
1190 Py_END_ALLOW_THREADS
1191
Zachary Waref2244ea2015-05-13 01:22:54 -05001192 if (! result) {
1193 PyErr_SetFromWindowsErr(GetLastError());
1194 return INVALID_HANDLE_VALUE;
1195 }
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001196
Zachary Waref2244ea2015-05-13 01:22:54 -05001197 return target_handle;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001198}
1199
Zachary Waref2244ea2015-05-13 01:22:54 -05001200/*[clinic input]
1201_winapi.ExitProcess
1202
1203 ExitCode: UINT
1204 /
1205
1206[clinic start generated code]*/
1207
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001208static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001209_winapi_ExitProcess_impl(PyObject *module, UINT ExitCode)
1210/*[clinic end generated code: output=a387deb651175301 input=4f05466a9406c558]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001211{
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001212 #if defined(Py_DEBUG)
1213 SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOALIGNMENTFAULTEXCEPT|
1214 SEM_NOGPFAULTERRORBOX|SEM_NOOPENFILEERRORBOX);
1215 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
1216 #endif
1217
Zachary Waref2244ea2015-05-13 01:22:54 -05001218 ExitProcess(ExitCode);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001219
1220 return NULL;
1221}
1222
Zachary Waref2244ea2015-05-13 01:22:54 -05001223/*[clinic input]
1224_winapi.GetCurrentProcess -> HANDLE
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001225
Zachary Waref2244ea2015-05-13 01:22:54 -05001226Return a handle object for the current process.
1227[clinic start generated code]*/
1228
1229static HANDLE
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001230_winapi_GetCurrentProcess_impl(PyObject *module)
1231/*[clinic end generated code: output=ddeb4dd2ffadf344 input=b213403fd4b96b41]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001232{
Zachary Waref2244ea2015-05-13 01:22:54 -05001233 return GetCurrentProcess();
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001234}
1235
Zachary Waref2244ea2015-05-13 01:22:54 -05001236/*[clinic input]
1237_winapi.GetExitCodeProcess -> DWORD
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001238
Zachary Waref2244ea2015-05-13 01:22:54 -05001239 process: HANDLE
1240 /
1241
1242Return the termination status of the specified process.
1243[clinic start generated code]*/
1244
1245static DWORD
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001246_winapi_GetExitCodeProcess_impl(PyObject *module, HANDLE process)
1247/*[clinic end generated code: output=b4620bdf2bccf36b input=61b6bfc7dc2ee374]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001248{
1249 DWORD exit_code;
1250 BOOL result;
1251
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001252 result = GetExitCodeProcess(process, &exit_code);
1253
Zachary Waref2244ea2015-05-13 01:22:54 -05001254 if (! result) {
1255 PyErr_SetFromWindowsErr(GetLastError());
Victor Stinner850a18e2017-10-24 16:53:32 -07001256 exit_code = PY_DWORD_MAX;
Zachary Waref2244ea2015-05-13 01:22:54 -05001257 }
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001258
Zachary Waref2244ea2015-05-13 01:22:54 -05001259 return exit_code;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001260}
1261
Zachary Waref2244ea2015-05-13 01:22:54 -05001262/*[clinic input]
1263_winapi.GetLastError -> DWORD
1264[clinic start generated code]*/
1265
1266static DWORD
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001267_winapi_GetLastError_impl(PyObject *module)
1268/*[clinic end generated code: output=8585b827cb1a92c5 input=62d47fb9bce038ba]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001269{
Zachary Waref2244ea2015-05-13 01:22:54 -05001270 return GetLastError();
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001271}
1272
Zachary Waref2244ea2015-05-13 01:22:54 -05001273/*[clinic input]
1274_winapi.GetModuleFileName
1275
1276 module_handle: HMODULE
1277 /
1278
1279Return the fully-qualified path for the file that contains module.
1280
1281The module must have been loaded by the current process.
1282
1283The module parameter should be a handle to the loaded module
1284whose path is being requested. If this parameter is 0,
1285GetModuleFileName retrieves the path of the executable file
1286of the current process.
1287[clinic start generated code]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001288
1289static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001290_winapi_GetModuleFileName_impl(PyObject *module, HMODULE module_handle)
1291/*[clinic end generated code: output=85b4b728c5160306 input=6d66ff7deca5d11f]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001292{
1293 BOOL result;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001294 WCHAR filename[MAX_PATH];
1295
Steve Dowerb82e17e2019-05-23 08:45:22 -07001296 Py_BEGIN_ALLOW_THREADS
Zachary Waref2244ea2015-05-13 01:22:54 -05001297 result = GetModuleFileNameW(module_handle, filename, MAX_PATH);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001298 filename[MAX_PATH-1] = '\0';
Steve Dowerb82e17e2019-05-23 08:45:22 -07001299 Py_END_ALLOW_THREADS
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001300
1301 if (! result)
1302 return PyErr_SetFromWindowsErr(GetLastError());
1303
1304 return PyUnicode_FromWideChar(filename, wcslen(filename));
1305}
1306
Zachary Waref2244ea2015-05-13 01:22:54 -05001307/*[clinic input]
1308_winapi.GetStdHandle -> HANDLE
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001309
Zachary Waref2244ea2015-05-13 01:22:54 -05001310 std_handle: DWORD
1311 One of STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, or STD_ERROR_HANDLE.
1312 /
1313
1314Return a handle to the specified standard device.
1315
1316The integer associated with the handle object is returned.
1317[clinic start generated code]*/
1318
1319static HANDLE
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001320_winapi_GetStdHandle_impl(PyObject *module, DWORD std_handle)
1321/*[clinic end generated code: output=0e613001e73ab614 input=07016b06a2fc8826]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001322{
1323 HANDLE handle;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001324
1325 Py_BEGIN_ALLOW_THREADS
1326 handle = GetStdHandle(std_handle);
1327 Py_END_ALLOW_THREADS
1328
1329 if (handle == INVALID_HANDLE_VALUE)
Zachary Waref2244ea2015-05-13 01:22:54 -05001330 PyErr_SetFromWindowsErr(GetLastError());
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001331
Zachary Waref2244ea2015-05-13 01:22:54 -05001332 return handle;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001333}
1334
Zachary Waref2244ea2015-05-13 01:22:54 -05001335/*[clinic input]
1336_winapi.GetVersion -> long
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001337
Zachary Waref2244ea2015-05-13 01:22:54 -05001338Return the version number of the current operating system.
1339[clinic start generated code]*/
1340
1341static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001342_winapi_GetVersion_impl(PyObject *module)
1343/*[clinic end generated code: output=e41f0db5a3b82682 input=e21dff8d0baeded2]*/
Steve Dower3e96f322015-03-02 08:01:10 -08001344/* Disable deprecation warnings about GetVersionEx as the result is
1345 being passed straight through to the caller, who is responsible for
1346 using it correctly. */
1347#pragma warning(push)
1348#pragma warning(disable:4996)
1349
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001350{
Zachary Waref2244ea2015-05-13 01:22:54 -05001351 return GetVersion();
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001352}
1353
Steve Dower3e96f322015-03-02 08:01:10 -08001354#pragma warning(pop)
1355
Zachary Waref2244ea2015-05-13 01:22:54 -05001356/*[clinic input]
Davin Pottse895de32019-02-23 22:08:16 -06001357_winapi.MapViewOfFile -> LPVOID
1358
1359 file_map: HANDLE
1360 desired_access: DWORD
1361 file_offset_high: DWORD
1362 file_offset_low: DWORD
1363 number_bytes: size_t
1364 /
1365[clinic start generated code]*/
1366
1367static LPVOID
1368_winapi_MapViewOfFile_impl(PyObject *module, HANDLE file_map,
1369 DWORD desired_access, DWORD file_offset_high,
1370 DWORD file_offset_low, size_t number_bytes)
1371/*[clinic end generated code: output=f23b1ee4823663e3 input=177471073be1a103]*/
1372{
1373 LPVOID address;
1374
1375 Py_BEGIN_ALLOW_THREADS
1376 address = MapViewOfFile(file_map, desired_access, file_offset_high,
1377 file_offset_low, number_bytes);
1378 Py_END_ALLOW_THREADS
1379
1380 if (address == NULL)
1381 PyErr_SetFromWindowsErr(0);
1382
1383 return address;
1384}
1385
1386/*[clinic input]
1387_winapi.OpenFileMapping -> HANDLE
1388
1389 desired_access: DWORD
1390 inherit_handle: BOOL
1391 name: LPCWSTR
1392 /
1393[clinic start generated code]*/
1394
1395static HANDLE
1396_winapi_OpenFileMapping_impl(PyObject *module, DWORD desired_access,
1397 BOOL inherit_handle, LPCWSTR name)
1398/*[clinic end generated code: output=08cc44def1cb11f1 input=131f2a405359de7f]*/
1399{
1400 HANDLE handle;
1401
1402 Py_BEGIN_ALLOW_THREADS
1403 handle = OpenFileMappingW(desired_access, inherit_handle, name);
1404 Py_END_ALLOW_THREADS
1405
1406 if (handle == NULL) {
Zackery Spytzeda385c2019-05-30 01:58:50 -06001407 PyObject *temp = PyUnicode_FromWideChar(name, -1);
1408 PyErr_SetExcFromWindowsErrWithFilenameObject(PyExc_OSError, 0, temp);
1409 Py_XDECREF(temp);
Davin Pottse895de32019-02-23 22:08:16 -06001410 handle = INVALID_HANDLE_VALUE;
1411 }
1412
1413 return handle;
1414}
1415
1416/*[clinic input]
Zachary Waref2244ea2015-05-13 01:22:54 -05001417_winapi.OpenProcess -> HANDLE
1418
1419 desired_access: DWORD
1420 inherit_handle: BOOL
1421 process_id: DWORD
1422 /
1423[clinic start generated code]*/
1424
1425static HANDLE
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001426_winapi_OpenProcess_impl(PyObject *module, DWORD desired_access,
Zachary Ware77772c02015-05-13 10:58:35 -05001427 BOOL inherit_handle, DWORD process_id)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001428/*[clinic end generated code: output=b42b6b81ea5a0fc3 input=ec98c4cf4ea2ec36]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001429{
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001430 HANDLE handle;
1431
Steve Dowerb82e17e2019-05-23 08:45:22 -07001432 if (PySys_Audit("_winapi.OpenProcess", "II",
1433 process_id, desired_access) < 0) {
1434 return INVALID_HANDLE_VALUE;
1435 }
1436
1437 Py_BEGIN_ALLOW_THREADS
Zachary Waref2244ea2015-05-13 01:22:54 -05001438 handle = OpenProcess(desired_access, inherit_handle, process_id);
Steve Dowerb82e17e2019-05-23 08:45:22 -07001439 Py_END_ALLOW_THREADS
Zachary Waref2244ea2015-05-13 01:22:54 -05001440 if (handle == NULL) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001441 PyErr_SetFromWindowsErr(GetLastError());
Zachary Waref2244ea2015-05-13 01:22:54 -05001442 handle = INVALID_HANDLE_VALUE;
1443 }
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001444
Zachary Waref2244ea2015-05-13 01:22:54 -05001445 return handle;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001446}
1447
Zachary Waref2244ea2015-05-13 01:22:54 -05001448/*[clinic input]
1449_winapi.PeekNamedPipe
1450
1451 handle: HANDLE
1452 size: int = 0
1453 /
1454[clinic start generated code]*/
1455
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001456static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001457_winapi_PeekNamedPipe_impl(PyObject *module, HANDLE handle, int size)
1458/*[clinic end generated code: output=d0c3e29e49d323dd input=c7aa53bfbce69d70]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001459{
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001460 PyObject *buf = NULL;
1461 DWORD nread, navail, nleft;
1462 BOOL ret;
1463
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001464 if (size < 0) {
1465 PyErr_SetString(PyExc_ValueError, "negative size");
1466 return NULL;
1467 }
1468
1469 if (size) {
1470 buf = PyBytes_FromStringAndSize(NULL, size);
1471 if (!buf)
1472 return NULL;
1473 Py_BEGIN_ALLOW_THREADS
1474 ret = PeekNamedPipe(handle, PyBytes_AS_STRING(buf), size, &nread,
1475 &navail, &nleft);
1476 Py_END_ALLOW_THREADS
1477 if (!ret) {
1478 Py_DECREF(buf);
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03001479 return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001480 }
1481 if (_PyBytes_Resize(&buf, nread))
1482 return NULL;
Alexander Buchkovsky266f4902018-09-04 19:10:28 +03001483 return Py_BuildValue("NII", buf, navail, nleft);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001484 }
1485 else {
1486 Py_BEGIN_ALLOW_THREADS
1487 ret = PeekNamedPipe(handle, NULL, 0, NULL, &navail, &nleft);
1488 Py_END_ALLOW_THREADS
1489 if (!ret) {
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03001490 return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001491 }
Alexander Buchkovsky266f4902018-09-04 19:10:28 +03001492 return Py_BuildValue("II", navail, nleft);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001493 }
1494}
1495
Zachary Waref2244ea2015-05-13 01:22:54 -05001496/*[clinic input]
1497_winapi.ReadFile
1498
1499 handle: HANDLE
Alexander Buchkovsky266f4902018-09-04 19:10:28 +03001500 size: DWORD
Serhiy Storchaka202fda52017-03-12 10:10:47 +02001501 overlapped as use_overlapped: bool(accept={int}) = False
Zachary Waref2244ea2015-05-13 01:22:54 -05001502[clinic start generated code]*/
1503
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001504static PyObject *
Alexander Buchkovsky266f4902018-09-04 19:10:28 +03001505_winapi_ReadFile_impl(PyObject *module, HANDLE handle, DWORD size,
Zachary Ware77772c02015-05-13 10:58:35 -05001506 int use_overlapped)
Alexander Buchkovsky266f4902018-09-04 19:10:28 +03001507/*[clinic end generated code: output=d3d5b44a8201b944 input=08c439d03a11aac5]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001508{
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001509 DWORD nread;
1510 PyObject *buf;
1511 BOOL ret;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001512 DWORD err;
1513 OverlappedObject *overlapped = NULL;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001514
1515 buf = PyBytes_FromStringAndSize(NULL, size);
1516 if (!buf)
1517 return NULL;
1518 if (use_overlapped) {
Mohamed Koubaae087f7c2020-08-13 09:22:48 -05001519 overlapped = new_overlapped(module, handle);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001520 if (!overlapped) {
1521 Py_DECREF(buf);
1522 return NULL;
1523 }
1524 /* Steals reference to buf */
1525 overlapped->read_buffer = buf;
1526 }
1527
1528 Py_BEGIN_ALLOW_THREADS
1529 ret = ReadFile(handle, PyBytes_AS_STRING(buf), size, &nread,
1530 overlapped ? &overlapped->overlapped : NULL);
1531 Py_END_ALLOW_THREADS
1532
1533 err = ret ? 0 : GetLastError();
1534
1535 if (overlapped) {
1536 if (!ret) {
1537 if (err == ERROR_IO_PENDING)
1538 overlapped->pending = 1;
1539 else if (err != ERROR_MORE_DATA) {
1540 Py_DECREF(overlapped);
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03001541 return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001542 }
1543 }
1544 return Py_BuildValue("NI", (PyObject *) overlapped, err);
1545 }
1546
1547 if (!ret && err != ERROR_MORE_DATA) {
1548 Py_DECREF(buf);
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03001549 return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001550 }
1551 if (_PyBytes_Resize(&buf, nread))
1552 return NULL;
1553 return Py_BuildValue("NI", buf, err);
1554}
1555
Zachary Waref2244ea2015-05-13 01:22:54 -05001556/*[clinic input]
1557_winapi.SetNamedPipeHandleState
1558
1559 named_pipe: HANDLE
1560 mode: object
1561 max_collection_count: object
1562 collect_data_timeout: object
1563 /
1564[clinic start generated code]*/
1565
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001566static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001567_winapi_SetNamedPipeHandleState_impl(PyObject *module, HANDLE named_pipe,
Zachary Ware77772c02015-05-13 10:58:35 -05001568 PyObject *mode,
1569 PyObject *max_collection_count,
1570 PyObject *collect_data_timeout)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001571/*[clinic end generated code: output=f2129d222cbfa095 input=9142d72163d0faa6]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001572{
Zachary Waref2244ea2015-05-13 01:22:54 -05001573 PyObject *oArgs[3] = {mode, max_collection_count, collect_data_timeout};
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001574 DWORD dwArgs[3], *pArgs[3] = {NULL, NULL, NULL};
1575 int i;
Steve Dowerb82e17e2019-05-23 08:45:22 -07001576 BOOL b;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001577
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001578 for (i = 0 ; i < 3 ; i++) {
1579 if (oArgs[i] != Py_None) {
1580 dwArgs[i] = PyLong_AsUnsignedLongMask(oArgs[i]);
1581 if (PyErr_Occurred())
1582 return NULL;
1583 pArgs[i] = &dwArgs[i];
1584 }
1585 }
1586
Steve Dowerb82e17e2019-05-23 08:45:22 -07001587 Py_BEGIN_ALLOW_THREADS
1588 b = SetNamedPipeHandleState(named_pipe, pArgs[0], pArgs[1], pArgs[2]);
1589 Py_END_ALLOW_THREADS
1590
1591 if (!b)
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001592 return PyErr_SetFromWindowsErr(0);
1593
1594 Py_RETURN_NONE;
1595}
1596
Zachary Waref2244ea2015-05-13 01:22:54 -05001597
1598/*[clinic input]
1599_winapi.TerminateProcess
1600
1601 handle: HANDLE
1602 exit_code: UINT
1603 /
1604
1605Terminate the specified process and all of its threads.
1606[clinic start generated code]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001607
1608static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001609_winapi_TerminateProcess_impl(PyObject *module, HANDLE handle,
Zachary Ware77772c02015-05-13 10:58:35 -05001610 UINT exit_code)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001611/*[clinic end generated code: output=f4e99ac3f0b1f34a input=d6bc0aa1ee3bb4df]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001612{
1613 BOOL result;
1614
Steve Dowerb82e17e2019-05-23 08:45:22 -07001615 if (PySys_Audit("_winapi.TerminateProcess", "nI",
1616 (Py_ssize_t)handle, exit_code) < 0) {
1617 return NULL;
1618 }
1619
Zachary Waref2244ea2015-05-13 01:22:54 -05001620 result = TerminateProcess(handle, exit_code);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001621
1622 if (! result)
1623 return PyErr_SetFromWindowsErr(GetLastError());
1624
Zachary Waref2244ea2015-05-13 01:22:54 -05001625 Py_RETURN_NONE;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001626}
1627
Zachary Waref2244ea2015-05-13 01:22:54 -05001628/*[clinic input]
Davin Pottse895de32019-02-23 22:08:16 -06001629_winapi.VirtualQuerySize -> size_t
1630
1631 address: LPCVOID
1632 /
1633[clinic start generated code]*/
1634
1635static size_t
1636_winapi_VirtualQuerySize_impl(PyObject *module, LPCVOID address)
1637/*[clinic end generated code: output=40c8e0ff5ec964df input=6b784a69755d0bb6]*/
1638{
1639 SIZE_T size_of_buf;
1640 MEMORY_BASIC_INFORMATION mem_basic_info;
1641 SIZE_T region_size;
1642
1643 Py_BEGIN_ALLOW_THREADS
1644 size_of_buf = VirtualQuery(address, &mem_basic_info, sizeof(mem_basic_info));
1645 Py_END_ALLOW_THREADS
1646
1647 if (size_of_buf == 0)
1648 PyErr_SetFromWindowsErr(0);
1649
1650 region_size = mem_basic_info.RegionSize;
1651 return region_size;
1652}
1653
1654/*[clinic input]
Zachary Waref2244ea2015-05-13 01:22:54 -05001655_winapi.WaitNamedPipe
1656
1657 name: LPCTSTR
1658 timeout: DWORD
1659 /
1660[clinic start generated code]*/
1661
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001662static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001663_winapi_WaitNamedPipe_impl(PyObject *module, LPCTSTR name, DWORD timeout)
1664/*[clinic end generated code: output=c2866f4439b1fe38 input=36fc781291b1862c]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001665{
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001666 BOOL success;
1667
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001668 Py_BEGIN_ALLOW_THREADS
Zachary Waref2244ea2015-05-13 01:22:54 -05001669 success = WaitNamedPipe(name, timeout);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001670 Py_END_ALLOW_THREADS
1671
1672 if (!success)
1673 return PyErr_SetFromWindowsErr(0);
1674
1675 Py_RETURN_NONE;
1676}
1677
Zachary Waref2244ea2015-05-13 01:22:54 -05001678/*[clinic input]
1679_winapi.WaitForMultipleObjects
1680
1681 handle_seq: object
1682 wait_flag: BOOL
1683 milliseconds: DWORD(c_default='INFINITE') = _winapi.INFINITE
1684 /
1685[clinic start generated code]*/
1686
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001687static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001688_winapi_WaitForMultipleObjects_impl(PyObject *module, PyObject *handle_seq,
1689 BOOL wait_flag, DWORD milliseconds)
1690/*[clinic end generated code: output=295e3f00b8e45899 input=36f76ca057cd28a0]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001691{
1692 DWORD result;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001693 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
1694 HANDLE sigint_event = NULL;
1695 Py_ssize_t nhandles, i;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001696
1697 if (!PySequence_Check(handle_seq)) {
1698 PyErr_Format(PyExc_TypeError,
1699 "sequence type expected, got '%s'",
Richard Oudkerk67339272012-08-21 14:54:22 +01001700 Py_TYPE(handle_seq)->tp_name);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001701 return NULL;
1702 }
1703 nhandles = PySequence_Length(handle_seq);
1704 if (nhandles == -1)
1705 return NULL;
1706 if (nhandles < 0 || nhandles >= MAXIMUM_WAIT_OBJECTS - 1) {
1707 PyErr_Format(PyExc_ValueError,
1708 "need at most %zd handles, got a sequence of length %zd",
1709 MAXIMUM_WAIT_OBJECTS - 1, nhandles);
1710 return NULL;
1711 }
1712 for (i = 0; i < nhandles; i++) {
1713 HANDLE h;
1714 PyObject *v = PySequence_GetItem(handle_seq, i);
1715 if (v == NULL)
1716 return NULL;
1717 if (!PyArg_Parse(v, F_HANDLE, &h)) {
1718 Py_DECREF(v);
1719 return NULL;
1720 }
1721 handles[i] = h;
1722 Py_DECREF(v);
1723 }
1724 /* If this is the main thread then make the wait interruptible
1725 by Ctrl-C unless we are waiting for *all* handles */
1726 if (!wait_flag && _PyOS_IsMainThread()) {
1727 sigint_event = _PyOS_SigintEvent();
1728 assert(sigint_event != NULL);
1729 handles[nhandles++] = sigint_event;
1730 }
1731
1732 Py_BEGIN_ALLOW_THREADS
1733 if (sigint_event != NULL)
1734 ResetEvent(sigint_event);
1735 result = WaitForMultipleObjects((DWORD) nhandles, handles,
1736 wait_flag, milliseconds);
1737 Py_END_ALLOW_THREADS
1738
1739 if (result == WAIT_FAILED)
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03001740 return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001741 else if (sigint_event != NULL && result == WAIT_OBJECT_0 + nhandles - 1) {
1742 errno = EINTR;
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03001743 return PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001744 }
1745
1746 return PyLong_FromLong((int) result);
1747}
1748
Zachary Waref2244ea2015-05-13 01:22:54 -05001749/*[clinic input]
1750_winapi.WaitForSingleObject -> long
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001751
Zachary Waref2244ea2015-05-13 01:22:54 -05001752 handle: HANDLE
1753 milliseconds: DWORD
1754 /
1755
1756Wait for a single object.
1757
1758Wait until the specified object is in the signaled state or
1759the time-out interval elapses. The timeout value is specified
1760in milliseconds.
1761[clinic start generated code]*/
1762
1763static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001764_winapi_WaitForSingleObject_impl(PyObject *module, HANDLE handle,
Zachary Ware77772c02015-05-13 10:58:35 -05001765 DWORD milliseconds)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001766/*[clinic end generated code: output=3c4715d8f1b39859 input=443d1ab076edc7b1]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001767{
1768 DWORD result;
1769
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001770 Py_BEGIN_ALLOW_THREADS
1771 result = WaitForSingleObject(handle, milliseconds);
1772 Py_END_ALLOW_THREADS
1773
Zachary Waref2244ea2015-05-13 01:22:54 -05001774 if (result == WAIT_FAILED) {
1775 PyErr_SetFromWindowsErr(GetLastError());
1776 return -1;
1777 }
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001778
Zachary Waref2244ea2015-05-13 01:22:54 -05001779 return result;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001780}
1781
Zachary Waref2244ea2015-05-13 01:22:54 -05001782/*[clinic input]
1783_winapi.WriteFile
1784
1785 handle: HANDLE
1786 buffer: object
Serhiy Storchaka202fda52017-03-12 10:10:47 +02001787 overlapped as use_overlapped: bool(accept={int}) = False
Zachary Waref2244ea2015-05-13 01:22:54 -05001788[clinic start generated code]*/
1789
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001790static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001791_winapi_WriteFile_impl(PyObject *module, HANDLE handle, PyObject *buffer,
Zachary Ware77772c02015-05-13 10:58:35 -05001792 int use_overlapped)
Serhiy Storchaka202fda52017-03-12 10:10:47 +02001793/*[clinic end generated code: output=2ca80f6bf3fa92e3 input=11eae2a03aa32731]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001794{
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001795 Py_buffer _buf, *buf;
Victor Stinner71765772013-06-24 23:13:24 +02001796 DWORD len, written;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001797 BOOL ret;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001798 DWORD err;
1799 OverlappedObject *overlapped = NULL;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001800
1801 if (use_overlapped) {
Mohamed Koubaae087f7c2020-08-13 09:22:48 -05001802 overlapped = new_overlapped(module, handle);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001803 if (!overlapped)
1804 return NULL;
1805 buf = &overlapped->write_buffer;
1806 }
1807 else
1808 buf = &_buf;
1809
Zachary Waref2244ea2015-05-13 01:22:54 -05001810 if (!PyArg_Parse(buffer, "y*", buf)) {
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001811 Py_XDECREF(overlapped);
1812 return NULL;
1813 }
1814
1815 Py_BEGIN_ALLOW_THREADS
Victor Stinner850a18e2017-10-24 16:53:32 -07001816 len = (DWORD)Py_MIN(buf->len, PY_DWORD_MAX);
Victor Stinner71765772013-06-24 23:13:24 +02001817 ret = WriteFile(handle, buf->buf, len, &written,
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001818 overlapped ? &overlapped->overlapped : NULL);
1819 Py_END_ALLOW_THREADS
1820
1821 err = ret ? 0 : GetLastError();
1822
1823 if (overlapped) {
1824 if (!ret) {
1825 if (err == ERROR_IO_PENDING)
1826 overlapped->pending = 1;
1827 else {
1828 Py_DECREF(overlapped);
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03001829 return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001830 }
1831 }
1832 return Py_BuildValue("NI", (PyObject *) overlapped, err);
1833 }
1834
1835 PyBuffer_Release(buf);
1836 if (!ret)
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03001837 return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001838 return Py_BuildValue("II", written, err);
1839}
1840
Victor Stinner91106cd2017-12-13 12:29:09 +01001841/*[clinic input]
1842_winapi.GetACP
1843
1844Get the current Windows ANSI code page identifier.
1845[clinic start generated code]*/
1846
1847static PyObject *
1848_winapi_GetACP_impl(PyObject *module)
1849/*[clinic end generated code: output=f7ee24bf705dbb88 input=1433c96d03a05229]*/
1850{
1851 return PyLong_FromUnsignedLong(GetACP());
1852}
1853
Segev Finerb2a60832017-12-18 11:28:19 +02001854/*[clinic input]
1855_winapi.GetFileType -> DWORD
1856
1857 handle: HANDLE
1858[clinic start generated code]*/
1859
1860static DWORD
1861_winapi_GetFileType_impl(PyObject *module, HANDLE handle)
1862/*[clinic end generated code: output=92b8466ac76ecc17 input=0058366bc40bbfbf]*/
1863{
1864 DWORD result;
1865
1866 Py_BEGIN_ALLOW_THREADS
1867 result = GetFileType(handle);
1868 Py_END_ALLOW_THREADS
1869
1870 if (result == FILE_TYPE_UNKNOWN && GetLastError() != NO_ERROR) {
1871 PyErr_SetFromWindowsErr(0);
1872 return -1;
1873 }
1874
1875 return result;
1876}
1877
Victor Stinner91106cd2017-12-13 12:29:09 +01001878
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001879static PyMethodDef winapi_functions[] = {
Zachary Waref2244ea2015-05-13 01:22:54 -05001880 _WINAPI_CLOSEHANDLE_METHODDEF
1881 _WINAPI_CONNECTNAMEDPIPE_METHODDEF
1882 _WINAPI_CREATEFILE_METHODDEF
Davin Pottse895de32019-02-23 22:08:16 -06001883 _WINAPI_CREATEFILEMAPPING_METHODDEF
Zachary Waref2244ea2015-05-13 01:22:54 -05001884 _WINAPI_CREATENAMEDPIPE_METHODDEF
1885 _WINAPI_CREATEPIPE_METHODDEF
1886 _WINAPI_CREATEPROCESS_METHODDEF
1887 _WINAPI_CREATEJUNCTION_METHODDEF
1888 _WINAPI_DUPLICATEHANDLE_METHODDEF
1889 _WINAPI_EXITPROCESS_METHODDEF
1890 _WINAPI_GETCURRENTPROCESS_METHODDEF
1891 _WINAPI_GETEXITCODEPROCESS_METHODDEF
1892 _WINAPI_GETLASTERROR_METHODDEF
1893 _WINAPI_GETMODULEFILENAME_METHODDEF
1894 _WINAPI_GETSTDHANDLE_METHODDEF
1895 _WINAPI_GETVERSION_METHODDEF
Davin Pottse895de32019-02-23 22:08:16 -06001896 _WINAPI_MAPVIEWOFFILE_METHODDEF
1897 _WINAPI_OPENFILEMAPPING_METHODDEF
Zachary Waref2244ea2015-05-13 01:22:54 -05001898 _WINAPI_OPENPROCESS_METHODDEF
1899 _WINAPI_PEEKNAMEDPIPE_METHODDEF
1900 _WINAPI_READFILE_METHODDEF
1901 _WINAPI_SETNAMEDPIPEHANDLESTATE_METHODDEF
1902 _WINAPI_TERMINATEPROCESS_METHODDEF
Davin Pottse895de32019-02-23 22:08:16 -06001903 _WINAPI_VIRTUALQUERYSIZE_METHODDEF
Zachary Waref2244ea2015-05-13 01:22:54 -05001904 _WINAPI_WAITNAMEDPIPE_METHODDEF
1905 _WINAPI_WAITFORMULTIPLEOBJECTS_METHODDEF
1906 _WINAPI_WAITFORSINGLEOBJECT_METHODDEF
1907 _WINAPI_WRITEFILE_METHODDEF
Victor Stinner91106cd2017-12-13 12:29:09 +01001908 _WINAPI_GETACP_METHODDEF
Segev Finerb2a60832017-12-18 11:28:19 +02001909 _WINAPI_GETFILETYPE_METHODDEF
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001910 {NULL, NULL}
1911};
1912
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001913#define WINAPI_CONSTANT(fmt, con) \
Mohamed Koubaae087f7c2020-08-13 09:22:48 -05001914 do { \
1915 PyObject *value = Py_BuildValue(fmt, con); \
1916 if (value == NULL) { \
1917 return -1; \
1918 } \
1919 if (PyDict_SetItemString(d, #con, value) < 0) { \
1920 Py_DECREF(value); \
1921 return -1; \
1922 } \
1923 Py_DECREF(value); \
1924 } while (0)
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001925
Mohamed Koubaae087f7c2020-08-13 09:22:48 -05001926static int winapi_exec(PyObject *m)
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001927{
Mohamed Koubaae087f7c2020-08-13 09:22:48 -05001928 WinApiState *st = winapi_get_state(m);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001929
Mohamed Koubaae087f7c2020-08-13 09:22:48 -05001930 st->overlapped_type = (PyTypeObject *)PyType_FromModuleAndSpec(m, &winapi_overlapped_type_spec, NULL);
1931 if (st->overlapped_type == NULL) {
1932 return -1;
1933 }
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001934
Mohamed Koubaae087f7c2020-08-13 09:22:48 -05001935 if (PyModule_AddType(m, st->overlapped_type) < 0) {
1936 return -1;
1937 }
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001938
Mohamed Koubaae087f7c2020-08-13 09:22:48 -05001939 PyObject *d = PyModule_GetDict(m);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001940
1941 /* constants */
1942 WINAPI_CONSTANT(F_DWORD, CREATE_NEW_CONSOLE);
1943 WINAPI_CONSTANT(F_DWORD, CREATE_NEW_PROCESS_GROUP);
1944 WINAPI_CONSTANT(F_DWORD, DUPLICATE_SAME_ACCESS);
Antoine Pitrou5438ed12012-04-24 22:56:57 +02001945 WINAPI_CONSTANT(F_DWORD, DUPLICATE_CLOSE_SOURCE);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001946 WINAPI_CONSTANT(F_DWORD, ERROR_ALREADY_EXISTS);
1947 WINAPI_CONSTANT(F_DWORD, ERROR_BROKEN_PIPE);
1948 WINAPI_CONSTANT(F_DWORD, ERROR_IO_PENDING);
1949 WINAPI_CONSTANT(F_DWORD, ERROR_MORE_DATA);
1950 WINAPI_CONSTANT(F_DWORD, ERROR_NETNAME_DELETED);
1951 WINAPI_CONSTANT(F_DWORD, ERROR_NO_SYSTEM_RESOURCES);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001952 WINAPI_CONSTANT(F_DWORD, ERROR_MORE_DATA);
1953 WINAPI_CONSTANT(F_DWORD, ERROR_NETNAME_DELETED);
Richard Oudkerkfdb8dcf2012-05-05 19:45:37 +01001954 WINAPI_CONSTANT(F_DWORD, ERROR_NO_DATA);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001955 WINAPI_CONSTANT(F_DWORD, ERROR_NO_SYSTEM_RESOURCES);
1956 WINAPI_CONSTANT(F_DWORD, ERROR_OPERATION_ABORTED);
1957 WINAPI_CONSTANT(F_DWORD, ERROR_PIPE_BUSY);
1958 WINAPI_CONSTANT(F_DWORD, ERROR_PIPE_CONNECTED);
1959 WINAPI_CONSTANT(F_DWORD, ERROR_SEM_TIMEOUT);
1960 WINAPI_CONSTANT(F_DWORD, FILE_FLAG_FIRST_PIPE_INSTANCE);
1961 WINAPI_CONSTANT(F_DWORD, FILE_FLAG_OVERLAPPED);
Antoine Pitrou5438ed12012-04-24 22:56:57 +02001962 WINAPI_CONSTANT(F_DWORD, FILE_GENERIC_READ);
1963 WINAPI_CONSTANT(F_DWORD, FILE_GENERIC_WRITE);
Davin Pottse895de32019-02-23 22:08:16 -06001964 WINAPI_CONSTANT(F_DWORD, FILE_MAP_ALL_ACCESS);
1965 WINAPI_CONSTANT(F_DWORD, FILE_MAP_COPY);
1966 WINAPI_CONSTANT(F_DWORD, FILE_MAP_EXECUTE);
1967 WINAPI_CONSTANT(F_DWORD, FILE_MAP_READ);
1968 WINAPI_CONSTANT(F_DWORD, FILE_MAP_WRITE);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001969 WINAPI_CONSTANT(F_DWORD, GENERIC_READ);
1970 WINAPI_CONSTANT(F_DWORD, GENERIC_WRITE);
1971 WINAPI_CONSTANT(F_DWORD, INFINITE);
Davin Pottse895de32019-02-23 22:08:16 -06001972 WINAPI_CONSTANT(F_HANDLE, INVALID_HANDLE_VALUE);
1973 WINAPI_CONSTANT(F_DWORD, MEM_COMMIT);
1974 WINAPI_CONSTANT(F_DWORD, MEM_FREE);
1975 WINAPI_CONSTANT(F_DWORD, MEM_IMAGE);
1976 WINAPI_CONSTANT(F_DWORD, MEM_MAPPED);
1977 WINAPI_CONSTANT(F_DWORD, MEM_PRIVATE);
1978 WINAPI_CONSTANT(F_DWORD, MEM_RESERVE);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001979 WINAPI_CONSTANT(F_DWORD, NMPWAIT_WAIT_FOREVER);
1980 WINAPI_CONSTANT(F_DWORD, OPEN_EXISTING);
Davin Pottse895de32019-02-23 22:08:16 -06001981 WINAPI_CONSTANT(F_DWORD, PAGE_EXECUTE);
1982 WINAPI_CONSTANT(F_DWORD, PAGE_EXECUTE_READ);
1983 WINAPI_CONSTANT(F_DWORD, PAGE_EXECUTE_READWRITE);
1984 WINAPI_CONSTANT(F_DWORD, PAGE_EXECUTE_WRITECOPY);
1985 WINAPI_CONSTANT(F_DWORD, PAGE_GUARD);
1986 WINAPI_CONSTANT(F_DWORD, PAGE_NOACCESS);
1987 WINAPI_CONSTANT(F_DWORD, PAGE_NOCACHE);
1988 WINAPI_CONSTANT(F_DWORD, PAGE_READONLY);
1989 WINAPI_CONSTANT(F_DWORD, PAGE_READWRITE);
1990 WINAPI_CONSTANT(F_DWORD, PAGE_WRITECOMBINE);
1991 WINAPI_CONSTANT(F_DWORD, PAGE_WRITECOPY);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001992 WINAPI_CONSTANT(F_DWORD, PIPE_ACCESS_DUPLEX);
1993 WINAPI_CONSTANT(F_DWORD, PIPE_ACCESS_INBOUND);
1994 WINAPI_CONSTANT(F_DWORD, PIPE_READMODE_MESSAGE);
1995 WINAPI_CONSTANT(F_DWORD, PIPE_TYPE_MESSAGE);
1996 WINAPI_CONSTANT(F_DWORD, PIPE_UNLIMITED_INSTANCES);
1997 WINAPI_CONSTANT(F_DWORD, PIPE_WAIT);
1998 WINAPI_CONSTANT(F_DWORD, PROCESS_ALL_ACCESS);
Thomas Moreauc09a9f52019-05-20 21:37:05 +02001999 WINAPI_CONSTANT(F_DWORD, SYNCHRONIZE);
Antoine Pitrou5438ed12012-04-24 22:56:57 +02002000 WINAPI_CONSTANT(F_DWORD, PROCESS_DUP_HANDLE);
Davin Pottse895de32019-02-23 22:08:16 -06002001 WINAPI_CONSTANT(F_DWORD, SEC_COMMIT);
2002 WINAPI_CONSTANT(F_DWORD, SEC_IMAGE);
2003 WINAPI_CONSTANT(F_DWORD, SEC_LARGE_PAGES);
2004 WINAPI_CONSTANT(F_DWORD, SEC_NOCACHE);
2005 WINAPI_CONSTANT(F_DWORD, SEC_RESERVE);
2006 WINAPI_CONSTANT(F_DWORD, SEC_WRITECOMBINE);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02002007 WINAPI_CONSTANT(F_DWORD, STARTF_USESHOWWINDOW);
2008 WINAPI_CONSTANT(F_DWORD, STARTF_USESTDHANDLES);
2009 WINAPI_CONSTANT(F_DWORD, STD_INPUT_HANDLE);
2010 WINAPI_CONSTANT(F_DWORD, STD_OUTPUT_HANDLE);
2011 WINAPI_CONSTANT(F_DWORD, STD_ERROR_HANDLE);
2012 WINAPI_CONSTANT(F_DWORD, STILL_ACTIVE);
2013 WINAPI_CONSTANT(F_DWORD, SW_HIDE);
2014 WINAPI_CONSTANT(F_DWORD, WAIT_OBJECT_0);
Victor Stinner373f0a92014-03-20 09:26:55 +01002015 WINAPI_CONSTANT(F_DWORD, WAIT_ABANDONED_0);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02002016 WINAPI_CONSTANT(F_DWORD, WAIT_TIMEOUT);
Victor Stinner91106cd2017-12-13 12:29:09 +01002017
Jamesb5d9e082017-11-08 14:18:59 +00002018 WINAPI_CONSTANT(F_DWORD, ABOVE_NORMAL_PRIORITY_CLASS);
2019 WINAPI_CONSTANT(F_DWORD, BELOW_NORMAL_PRIORITY_CLASS);
2020 WINAPI_CONSTANT(F_DWORD, HIGH_PRIORITY_CLASS);
2021 WINAPI_CONSTANT(F_DWORD, IDLE_PRIORITY_CLASS);
2022 WINAPI_CONSTANT(F_DWORD, NORMAL_PRIORITY_CLASS);
2023 WINAPI_CONSTANT(F_DWORD, REALTIME_PRIORITY_CLASS);
Victor Stinner91106cd2017-12-13 12:29:09 +01002024
Jamesb5d9e082017-11-08 14:18:59 +00002025 WINAPI_CONSTANT(F_DWORD, CREATE_NO_WINDOW);
2026 WINAPI_CONSTANT(F_DWORD, DETACHED_PROCESS);
2027 WINAPI_CONSTANT(F_DWORD, CREATE_DEFAULT_ERROR_MODE);
2028 WINAPI_CONSTANT(F_DWORD, CREATE_BREAKAWAY_FROM_JOB);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02002029
Segev Finerb2a60832017-12-18 11:28:19 +02002030 WINAPI_CONSTANT(F_DWORD, FILE_TYPE_UNKNOWN);
2031 WINAPI_CONSTANT(F_DWORD, FILE_TYPE_DISK);
2032 WINAPI_CONSTANT(F_DWORD, FILE_TYPE_CHAR);
2033 WINAPI_CONSTANT(F_DWORD, FILE_TYPE_PIPE);
2034 WINAPI_CONSTANT(F_DWORD, FILE_TYPE_REMOTE);
2035
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02002036 WINAPI_CONSTANT("i", NULL);
2037
Mohamed Koubaae087f7c2020-08-13 09:22:48 -05002038 return 0;
2039}
2040
2041static PyModuleDef_Slot winapi_slots[] = {
2042 {Py_mod_exec, winapi_exec},
2043 {0, NULL}
2044};
2045
2046static struct PyModuleDef winapi_module = {
2047 PyModuleDef_HEAD_INIT,
2048 .m_name = "_winapi",
2049 .m_size = sizeof(WinApiState),
2050 .m_methods = winapi_functions,
2051 .m_slots = winapi_slots,
2052};
2053
2054PyMODINIT_FUNC
2055PyInit__winapi(void)
2056{
2057 return PyModuleDef_Init(&winapi_module);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02002058}