blob: ddb11aa5a820425ff4a5b67af322bcc365f7c828 [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 Stinner4a21e572020-04-15 02:35:41 +020038#include "structmember.h" // PyMemberDef
Antoine Pitrou23bba4c2012-04-18 20:51:15 +020039
40#define WINDOWS_LEAN_AND_MEAN
41#include "windows.h"
42#include <crtdbg.h>
Tim Golden0321cf22014-05-05 19:46:17 +010043#include "winreparse.h"
Antoine Pitrou23bba4c2012-04-18 20:51:15 +020044
45#if defined(MS_WIN32) && !defined(MS_WIN64)
46#define HANDLE_TO_PYNUM(handle) \
47 PyLong_FromUnsignedLong((unsigned long) handle)
48#define PYNUM_TO_HANDLE(obj) ((HANDLE)PyLong_AsUnsignedLong(obj))
49#define F_POINTER "k"
50#define T_POINTER T_ULONG
51#else
52#define HANDLE_TO_PYNUM(handle) \
53 PyLong_FromUnsignedLongLong((unsigned long long) handle)
54#define PYNUM_TO_HANDLE(obj) ((HANDLE)PyLong_AsUnsignedLongLong(obj))
55#define F_POINTER "K"
56#define T_POINTER T_ULONGLONG
57#endif
58
59#define F_HANDLE F_POINTER
60#define F_DWORD "k"
Antoine Pitrou23bba4c2012-04-18 20:51:15 +020061
62#define T_HANDLE T_POINTER
63
64/* Grab CancelIoEx dynamically from kernel32 */
65static int has_CancelIoEx = -1;
66static BOOL (CALLBACK *Py_CancelIoEx)(HANDLE, LPOVERLAPPED);
67
68static int
69check_CancelIoEx()
70{
71 if (has_CancelIoEx == -1)
72 {
73 HINSTANCE hKernel32 = GetModuleHandle("KERNEL32");
74 * (FARPROC *) &Py_CancelIoEx = GetProcAddress(hKernel32,
75 "CancelIoEx");
76 has_CancelIoEx = (Py_CancelIoEx != NULL);
77 }
78 return has_CancelIoEx;
79}
80
81
82/*
83 * A Python object wrapping an OVERLAPPED structure and other useful data
84 * for overlapped I/O
85 */
86
87typedef struct {
88 PyObject_HEAD
89 OVERLAPPED overlapped;
90 /* For convenience, we store the file handle too */
91 HANDLE handle;
92 /* Whether there's I/O in flight */
93 int pending;
94 /* Whether I/O completed successfully */
95 int completed;
96 /* Buffer used for reading (optional) */
97 PyObject *read_buffer;
98 /* Buffer used for writing (optional) */
99 Py_buffer write_buffer;
100} OverlappedObject;
101
102static void
103overlapped_dealloc(OverlappedObject *self)
104{
105 DWORD bytes;
106 int err = GetLastError();
Richard Oudkerk633db6f2013-11-17 13:15:51 +0000107
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200108 if (self->pending) {
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200109 if (check_CancelIoEx() &&
Richard Oudkerk633db6f2013-11-17 13:15:51 +0000110 Py_CancelIoEx(self->handle, &self->overlapped) &&
111 GetOverlappedResult(self->handle, &self->overlapped, &bytes, TRUE))
112 {
113 /* The operation is no longer pending -- nothing to do. */
114 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600115 else if (_Py_IsFinalizing())
Richard Oudkerk633db6f2013-11-17 13:15:51 +0000116 {
117 /* The operation is still pending -- give a warning. This
118 will probably only happen on Windows XP. */
119 PyErr_SetString(PyExc_RuntimeError,
120 "I/O operations still in flight while destroying "
121 "Overlapped object, the process may crash");
122 PyErr_WriteUnraisable(NULL);
123 }
124 else
125 {
126 /* The operation is still pending, but the process is
127 probably about to exit, so we need not worry too much
128 about memory leaks. Leaking self prevents a potential
129 crash. This can happen when a daemon thread is cleaned
130 up at exit -- see #19565. We only expect to get here
131 on Windows XP. */
132 CloseHandle(self->overlapped.hEvent);
133 SetLastError(err);
134 return;
135 }
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200136 }
Richard Oudkerk633db6f2013-11-17 13:15:51 +0000137
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200138 CloseHandle(self->overlapped.hEvent);
139 SetLastError(err);
140 if (self->write_buffer.obj)
141 PyBuffer_Release(&self->write_buffer);
142 Py_CLEAR(self->read_buffer);
143 PyObject_Del(self);
144}
145
Zachary Waref2244ea2015-05-13 01:22:54 -0500146/*[clinic input]
147module _winapi
148class _winapi.Overlapped "OverlappedObject *" "&OverlappedType"
149[clinic start generated code]*/
150/*[clinic end generated code: output=da39a3ee5e6b4b0d input=c13d3f5fd1dabb84]*/
151
152/*[python input]
153def create_converter(type_, format_unit):
154 name = type_ + '_converter'
155 # registered upon creation by CConverter's metaclass
156 type(name, (CConverter,), {'type': type_, 'format_unit': format_unit})
157
158# format unit differs between platforms for these
159create_converter('HANDLE', '" F_HANDLE "')
160create_converter('HMODULE', '" F_HANDLE "')
161create_converter('LPSECURITY_ATTRIBUTES', '" F_POINTER "')
Davin Pottse895de32019-02-23 22:08:16 -0600162create_converter('LPCVOID', '" F_POINTER "')
Zachary Waref2244ea2015-05-13 01:22:54 -0500163
164create_converter('BOOL', 'i') # F_BOOL used previously (always 'i')
165create_converter('DWORD', 'k') # F_DWORD is always "k" (which is much shorter)
166create_converter('LPCTSTR', 's')
Zachary Waref2244ea2015-05-13 01:22:54 -0500167create_converter('UINT', 'I') # F_UINT used previously (always 'I')
168
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +0300169class LPCWSTR_converter(Py_UNICODE_converter):
170 type = 'LPCWSTR'
171
Zachary Waref2244ea2015-05-13 01:22:54 -0500172class HANDLE_return_converter(CReturnConverter):
173 type = 'HANDLE'
174
175 def render(self, function, data):
176 self.declare(data)
177 self.err_occurred_if("_return_value == INVALID_HANDLE_VALUE", data)
178 data.return_conversion.append(
Serhiy Storchaka5dee6552016-06-09 16:16:06 +0300179 'if (_return_value == NULL) {\n Py_RETURN_NONE;\n}\n')
Zachary Waref2244ea2015-05-13 01:22:54 -0500180 data.return_conversion.append(
181 'return_value = HANDLE_TO_PYNUM(_return_value);\n')
182
183class DWORD_return_converter(CReturnConverter):
184 type = 'DWORD'
185
186 def render(self, function, data):
187 self.declare(data)
Victor Stinner850a18e2017-10-24 16:53:32 -0700188 self.err_occurred_if("_return_value == PY_DWORD_MAX", data)
Zachary Waref2244ea2015-05-13 01:22:54 -0500189 data.return_conversion.append(
190 'return_value = Py_BuildValue("k", _return_value);\n')
Davin Pottse895de32019-02-23 22:08:16 -0600191
192class LPVOID_return_converter(CReturnConverter):
193 type = 'LPVOID'
194
195 def render(self, function, data):
196 self.declare(data)
197 self.err_occurred_if("_return_value == NULL", data)
198 data.return_conversion.append(
199 'return_value = HANDLE_TO_PYNUM(_return_value);\n')
Zachary Waref2244ea2015-05-13 01:22:54 -0500200[python start generated code]*/
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +0300201/*[python end generated code: output=da39a3ee5e6b4b0d input=011ee0c3a2244bfe]*/
Zachary Waref2244ea2015-05-13 01:22:54 -0500202
203#include "clinic/_winapi.c.h"
204
205/*[clinic input]
206_winapi.Overlapped.GetOverlappedResult
207
208 wait: bool
209 /
210[clinic start generated code]*/
211
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200212static PyObject *
Zachary Waref2244ea2015-05-13 01:22:54 -0500213_winapi_Overlapped_GetOverlappedResult_impl(OverlappedObject *self, int wait)
214/*[clinic end generated code: output=bdd0c1ed6518cd03 input=194505ee8e0e3565]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200215{
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200216 BOOL res;
217 DWORD transferred = 0;
218 DWORD err;
219
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200220 Py_BEGIN_ALLOW_THREADS
221 res = GetOverlappedResult(self->handle, &self->overlapped, &transferred,
222 wait != 0);
223 Py_END_ALLOW_THREADS
224
225 err = res ? ERROR_SUCCESS : GetLastError();
226 switch (err) {
227 case ERROR_SUCCESS:
228 case ERROR_MORE_DATA:
229 case ERROR_OPERATION_ABORTED:
230 self->completed = 1;
231 self->pending = 0;
232 break;
233 case ERROR_IO_INCOMPLETE:
234 break;
235 default:
236 self->pending = 0;
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +0300237 return PyErr_SetExcFromWindowsErr(PyExc_OSError, err);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200238 }
239 if (self->completed && self->read_buffer != NULL) {
240 assert(PyBytes_CheckExact(self->read_buffer));
241 if (transferred != PyBytes_GET_SIZE(self->read_buffer) &&
242 _PyBytes_Resize(&self->read_buffer, transferred))
243 return NULL;
244 }
245 return Py_BuildValue("II", (unsigned) transferred, (unsigned) err);
246}
247
Zachary Waref2244ea2015-05-13 01:22:54 -0500248/*[clinic input]
249_winapi.Overlapped.getbuffer
250[clinic start generated code]*/
251
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200252static PyObject *
Zachary Waref2244ea2015-05-13 01:22:54 -0500253_winapi_Overlapped_getbuffer_impl(OverlappedObject *self)
254/*[clinic end generated code: output=95a3eceefae0f748 input=347fcfd56b4ceabd]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200255{
256 PyObject *res;
257 if (!self->completed) {
258 PyErr_SetString(PyExc_ValueError,
259 "can't get read buffer before GetOverlappedResult() "
260 "signals the operation completed");
261 return NULL;
262 }
263 res = self->read_buffer ? self->read_buffer : Py_None;
264 Py_INCREF(res);
265 return res;
266}
267
Zachary Waref2244ea2015-05-13 01:22:54 -0500268/*[clinic input]
269_winapi.Overlapped.cancel
270[clinic start generated code]*/
271
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200272static PyObject *
Zachary Waref2244ea2015-05-13 01:22:54 -0500273_winapi_Overlapped_cancel_impl(OverlappedObject *self)
274/*[clinic end generated code: output=fcb9ab5df4ebdae5 input=cbf3da142290039f]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200275{
276 BOOL res = TRUE;
277
278 if (self->pending) {
279 Py_BEGIN_ALLOW_THREADS
280 if (check_CancelIoEx())
281 res = Py_CancelIoEx(self->handle, &self->overlapped);
282 else
283 res = CancelIo(self->handle);
284 Py_END_ALLOW_THREADS
285 }
286
287 /* CancelIoEx returns ERROR_NOT_FOUND if the I/O completed in-between */
288 if (!res && GetLastError() != ERROR_NOT_FOUND)
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +0300289 return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200290 self->pending = 0;
291 Py_RETURN_NONE;
292}
293
294static PyMethodDef overlapped_methods[] = {
Zachary Waref2244ea2015-05-13 01:22:54 -0500295 _WINAPI_OVERLAPPED_GETOVERLAPPEDRESULT_METHODDEF
296 _WINAPI_OVERLAPPED_GETBUFFER_METHODDEF
297 _WINAPI_OVERLAPPED_CANCEL_METHODDEF
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200298 {NULL}
299};
300
301static PyMemberDef overlapped_members[] = {
302 {"event", T_HANDLE,
303 offsetof(OverlappedObject, overlapped) + offsetof(OVERLAPPED, hEvent),
304 READONLY, "overlapped event handle"},
305 {NULL}
306};
307
308PyTypeObject OverlappedType = {
309 PyVarObject_HEAD_INIT(NULL, 0)
310 /* tp_name */ "_winapi.Overlapped",
311 /* tp_basicsize */ sizeof(OverlappedObject),
312 /* tp_itemsize */ 0,
313 /* tp_dealloc */ (destructor) overlapped_dealloc,
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200314 /* tp_vectorcall_offset */ 0,
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200315 /* tp_getattr */ 0,
316 /* tp_setattr */ 0,
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200317 /* tp_as_async */ 0,
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200318 /* tp_repr */ 0,
319 /* tp_as_number */ 0,
320 /* tp_as_sequence */ 0,
321 /* tp_as_mapping */ 0,
322 /* tp_hash */ 0,
323 /* tp_call */ 0,
324 /* tp_str */ 0,
325 /* tp_getattro */ 0,
326 /* tp_setattro */ 0,
327 /* tp_as_buffer */ 0,
328 /* tp_flags */ Py_TPFLAGS_DEFAULT,
329 /* tp_doc */ "OVERLAPPED structure wrapper",
330 /* tp_traverse */ 0,
331 /* tp_clear */ 0,
332 /* tp_richcompare */ 0,
333 /* tp_weaklistoffset */ 0,
334 /* tp_iter */ 0,
335 /* tp_iternext */ 0,
336 /* tp_methods */ overlapped_methods,
337 /* tp_members */ overlapped_members,
338 /* tp_getset */ 0,
339 /* tp_base */ 0,
340 /* tp_dict */ 0,
341 /* tp_descr_get */ 0,
342 /* tp_descr_set */ 0,
343 /* tp_dictoffset */ 0,
344 /* tp_init */ 0,
345 /* tp_alloc */ 0,
346 /* tp_new */ 0,
347};
348
349static OverlappedObject *
350new_overlapped(HANDLE handle)
351{
352 OverlappedObject *self;
353
354 self = PyObject_New(OverlappedObject, &OverlappedType);
355 if (!self)
356 return NULL;
357 self->handle = handle;
358 self->read_buffer = NULL;
359 self->pending = 0;
360 self->completed = 0;
361 memset(&self->overlapped, 0, sizeof(OVERLAPPED));
362 memset(&self->write_buffer, 0, sizeof(Py_buffer));
363 /* Manual reset, initially non-signalled */
364 self->overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
365 return self;
366}
367
368/* -------------------------------------------------------------------- */
369/* windows API functions */
370
Zachary Waref2244ea2015-05-13 01:22:54 -0500371/*[clinic input]
372_winapi.CloseHandle
373
374 handle: HANDLE
375 /
376
377Close handle.
378[clinic start generated code]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200379
380static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300381_winapi_CloseHandle_impl(PyObject *module, HANDLE handle)
382/*[clinic end generated code: output=7ad37345f07bd782 input=7f0e4ac36e0352b8]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200383{
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200384 BOOL success;
385
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200386 Py_BEGIN_ALLOW_THREADS
Zachary Waref2244ea2015-05-13 01:22:54 -0500387 success = CloseHandle(handle);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200388 Py_END_ALLOW_THREADS
389
390 if (!success)
391 return PyErr_SetFromWindowsErr(0);
392
393 Py_RETURN_NONE;
394}
395
Zachary Waref2244ea2015-05-13 01:22:54 -0500396/*[clinic input]
397_winapi.ConnectNamedPipe
398
399 handle: HANDLE
Serhiy Storchaka202fda52017-03-12 10:10:47 +0200400 overlapped as use_overlapped: bool(accept={int}) = False
Zachary Waref2244ea2015-05-13 01:22:54 -0500401[clinic start generated code]*/
402
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200403static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300404_winapi_ConnectNamedPipe_impl(PyObject *module, HANDLE handle,
Zachary Ware77772c02015-05-13 10:58:35 -0500405 int use_overlapped)
Serhiy Storchaka202fda52017-03-12 10:10:47 +0200406/*[clinic end generated code: output=335a0e7086800671 input=34f937c1c86e5e68]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200407{
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200408 BOOL success;
409 OverlappedObject *overlapped = NULL;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200410
411 if (use_overlapped) {
Zachary Waref2244ea2015-05-13 01:22:54 -0500412 overlapped = new_overlapped(handle);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200413 if (!overlapped)
414 return NULL;
415 }
416
417 Py_BEGIN_ALLOW_THREADS
Zachary Waref2244ea2015-05-13 01:22:54 -0500418 success = ConnectNamedPipe(handle,
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200419 overlapped ? &overlapped->overlapped : NULL);
420 Py_END_ALLOW_THREADS
421
422 if (overlapped) {
423 int err = GetLastError();
424 /* Overlapped ConnectNamedPipe never returns a success code */
425 assert(success == 0);
426 if (err == ERROR_IO_PENDING)
427 overlapped->pending = 1;
428 else if (err == ERROR_PIPE_CONNECTED)
429 SetEvent(overlapped->overlapped.hEvent);
430 else {
431 Py_DECREF(overlapped);
432 return PyErr_SetFromWindowsErr(err);
433 }
434 return (PyObject *) overlapped;
435 }
436 if (!success)
437 return PyErr_SetFromWindowsErr(0);
438
439 Py_RETURN_NONE;
440}
441
Zachary Waref2244ea2015-05-13 01:22:54 -0500442/*[clinic input]
443_winapi.CreateFile -> HANDLE
444
445 file_name: LPCTSTR
446 desired_access: DWORD
447 share_mode: DWORD
448 security_attributes: LPSECURITY_ATTRIBUTES
449 creation_disposition: DWORD
450 flags_and_attributes: DWORD
451 template_file: HANDLE
452 /
453[clinic start generated code]*/
454
455static HANDLE
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300456_winapi_CreateFile_impl(PyObject *module, LPCTSTR file_name,
Zachary Ware77772c02015-05-13 10:58:35 -0500457 DWORD desired_access, DWORD share_mode,
458 LPSECURITY_ATTRIBUTES security_attributes,
459 DWORD creation_disposition,
460 DWORD flags_and_attributes, HANDLE template_file)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300461/*[clinic end generated code: output=417ddcebfc5a3d53 input=6423c3e40372dbd5]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200462{
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200463 HANDLE handle;
464
Steve Dowerb82e17e2019-05-23 08:45:22 -0700465 if (PySys_Audit("_winapi.CreateFile", "uIIII",
466 file_name, desired_access, share_mode,
467 creation_disposition, flags_and_attributes) < 0) {
468 return INVALID_HANDLE_VALUE;
469 }
470
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200471 Py_BEGIN_ALLOW_THREADS
Zachary Waref2244ea2015-05-13 01:22:54 -0500472 handle = CreateFile(file_name, desired_access,
473 share_mode, security_attributes,
474 creation_disposition,
475 flags_and_attributes, template_file);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200476 Py_END_ALLOW_THREADS
477
478 if (handle == INVALID_HANDLE_VALUE)
Zachary Waref2244ea2015-05-13 01:22:54 -0500479 PyErr_SetFromWindowsErr(0);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200480
Zachary Waref2244ea2015-05-13 01:22:54 -0500481 return handle;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200482}
483
Zachary Waref2244ea2015-05-13 01:22:54 -0500484/*[clinic input]
Davin Pottse895de32019-02-23 22:08:16 -0600485_winapi.CreateFileMapping -> HANDLE
486
487 file_handle: HANDLE
488 security_attributes: LPSECURITY_ATTRIBUTES
489 protect: DWORD
490 max_size_high: DWORD
491 max_size_low: DWORD
492 name: LPCWSTR
493 /
494[clinic start generated code]*/
495
496static HANDLE
497_winapi_CreateFileMapping_impl(PyObject *module, HANDLE file_handle,
498 LPSECURITY_ATTRIBUTES security_attributes,
499 DWORD protect, DWORD max_size_high,
500 DWORD max_size_low, LPCWSTR name)
501/*[clinic end generated code: output=6c0a4d5cf7f6fcc6 input=3dc5cf762a74dee8]*/
502{
503 HANDLE handle;
504
505 Py_BEGIN_ALLOW_THREADS
506 handle = CreateFileMappingW(file_handle, security_attributes,
507 protect, max_size_high, max_size_low,
508 name);
509 Py_END_ALLOW_THREADS
510
511 if (handle == NULL) {
Zackery Spytzeda385c2019-05-30 01:58:50 -0600512 PyObject *temp = PyUnicode_FromWideChar(name, -1);
513 PyErr_SetExcFromWindowsErrWithFilenameObject(PyExc_OSError, 0, temp);
514 Py_XDECREF(temp);
Davin Pottse895de32019-02-23 22:08:16 -0600515 handle = INVALID_HANDLE_VALUE;
516 }
517
518 return handle;
519}
520
521/*[clinic input]
Zachary Waref2244ea2015-05-13 01:22:54 -0500522_winapi.CreateJunction
Tim Golden0321cf22014-05-05 19:46:17 +0100523
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +0300524 src_path: LPCWSTR
525 dst_path: LPCWSTR
Zachary Waref2244ea2015-05-13 01:22:54 -0500526 /
527[clinic start generated code]*/
528
529static PyObject *
Serhiy Storchaka4c8f09d2020-07-10 23:26:06 +0300530_winapi_CreateJunction_impl(PyObject *module, LPCWSTR src_path,
531 LPCWSTR dst_path)
532/*[clinic end generated code: output=44b3f5e9bbcc4271 input=963d29b44b9384a7]*/
Zachary Waref2244ea2015-05-13 01:22:54 -0500533{
Tim Golden0321cf22014-05-05 19:46:17 +0100534 /* Privilege adjustment */
535 HANDLE token = NULL;
536 TOKEN_PRIVILEGES tp;
537
538 /* Reparse data buffer */
539 const USHORT prefix_len = 4;
540 USHORT print_len = 0;
541 USHORT rdb_size = 0;
Martin Panter70214ad2016-08-04 02:38:59 +0000542 _Py_PREPARSE_DATA_BUFFER rdb = NULL;
Tim Golden0321cf22014-05-05 19:46:17 +0100543
544 /* Junction point creation */
545 HANDLE junction = NULL;
546 DWORD ret = 0;
547
Tim Golden0321cf22014-05-05 19:46:17 +0100548 if (src_path == NULL || dst_path == NULL)
549 return PyErr_SetFromWindowsErr(ERROR_INVALID_PARAMETER);
550
551 if (wcsncmp(src_path, L"\\??\\", prefix_len) == 0)
552 return PyErr_SetFromWindowsErr(ERROR_INVALID_PARAMETER);
553
Steve Dowerb82e17e2019-05-23 08:45:22 -0700554 if (PySys_Audit("_winapi.CreateJunction", "uu", src_path, dst_path) < 0) {
555 return NULL;
556 }
557
Tim Golden0321cf22014-05-05 19:46:17 +0100558 /* Adjust privileges to allow rewriting directory entry as a
559 junction point. */
560 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &token))
561 goto cleanup;
562
563 if (!LookupPrivilegeValue(NULL, SE_RESTORE_NAME, &tp.Privileges[0].Luid))
564 goto cleanup;
565
566 tp.PrivilegeCount = 1;
567 tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
568 if (!AdjustTokenPrivileges(token, FALSE, &tp, sizeof(TOKEN_PRIVILEGES),
569 NULL, NULL))
570 goto cleanup;
571
572 if (GetFileAttributesW(src_path) == INVALID_FILE_ATTRIBUTES)
573 goto cleanup;
574
575 /* Store the absolute link target path length in print_len. */
576 print_len = (USHORT)GetFullPathNameW(src_path, 0, NULL, NULL);
577 if (print_len == 0)
578 goto cleanup;
579
580 /* NUL terminator should not be part of print_len. */
581 --print_len;
582
583 /* REPARSE_DATA_BUFFER usage is heavily under-documented, especially for
584 junction points. Here's what I've learned along the way:
585 - A junction point has two components: a print name and a substitute
586 name. They both describe the link target, but the substitute name is
587 the physical target and the print name is shown in directory listings.
588 - The print name must be a native name, prefixed with "\??\".
589 - Both names are stored after each other in the same buffer (the
590 PathBuffer) and both must be NUL-terminated.
591 - There are four members defining their respective offset and length
592 inside PathBuffer: SubstituteNameOffset, SubstituteNameLength,
593 PrintNameOffset and PrintNameLength.
594 - The total size we need to allocate for the REPARSE_DATA_BUFFER, thus,
595 is the sum of:
596 - the fixed header size (REPARSE_DATA_BUFFER_HEADER_SIZE)
597 - the size of the MountPointReparseBuffer member without the PathBuffer
598 - the size of the prefix ("\??\") in bytes
599 - the size of the print name in bytes
600 - the size of the substitute name in bytes
601 - the size of two NUL terminators in bytes */
Martin Panter70214ad2016-08-04 02:38:59 +0000602 rdb_size = _Py_REPARSE_DATA_BUFFER_HEADER_SIZE +
Tim Golden0321cf22014-05-05 19:46:17 +0100603 sizeof(rdb->MountPointReparseBuffer) -
604 sizeof(rdb->MountPointReparseBuffer.PathBuffer) +
605 /* Two +1's for NUL terminators. */
606 (prefix_len + print_len + 1 + print_len + 1) * sizeof(WCHAR);
Andy Lester7668a8b2020-03-24 23:26:44 -0500607 rdb = (_Py_PREPARSE_DATA_BUFFER)PyMem_RawCalloc(1, rdb_size);
Tim Golden0321cf22014-05-05 19:46:17 +0100608 if (rdb == NULL)
609 goto cleanup;
610
Tim Golden0321cf22014-05-05 19:46:17 +0100611 rdb->ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
Martin Panter70214ad2016-08-04 02:38:59 +0000612 rdb->ReparseDataLength = rdb_size - _Py_REPARSE_DATA_BUFFER_HEADER_SIZE;
Tim Golden0321cf22014-05-05 19:46:17 +0100613 rdb->MountPointReparseBuffer.SubstituteNameOffset = 0;
614 rdb->MountPointReparseBuffer.SubstituteNameLength =
615 (prefix_len + print_len) * sizeof(WCHAR);
616 rdb->MountPointReparseBuffer.PrintNameOffset =
617 rdb->MountPointReparseBuffer.SubstituteNameLength + sizeof(WCHAR);
618 rdb->MountPointReparseBuffer.PrintNameLength = print_len * sizeof(WCHAR);
619
620 /* Store the full native path of link target at the substitute name
621 offset (0). */
622 wcscpy(rdb->MountPointReparseBuffer.PathBuffer, L"\\??\\");
623 if (GetFullPathNameW(src_path, print_len + 1,
624 rdb->MountPointReparseBuffer.PathBuffer + prefix_len,
625 NULL) == 0)
626 goto cleanup;
627
628 /* Copy everything but the native prefix to the print name offset. */
629 wcscpy(rdb->MountPointReparseBuffer.PathBuffer +
630 prefix_len + print_len + 1,
631 rdb->MountPointReparseBuffer.PathBuffer + prefix_len);
632
633 /* Create a directory for the junction point. */
634 if (!CreateDirectoryW(dst_path, NULL))
635 goto cleanup;
636
637 junction = CreateFileW(dst_path, GENERIC_READ | GENERIC_WRITE, 0, NULL,
638 OPEN_EXISTING,
639 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, NULL);
640 if (junction == INVALID_HANDLE_VALUE)
641 goto cleanup;
642
643 /* Make the directory entry a junction point. */
644 if (!DeviceIoControl(junction, FSCTL_SET_REPARSE_POINT, rdb, rdb_size,
645 NULL, 0, &ret, NULL))
646 goto cleanup;
647
648cleanup:
649 ret = GetLastError();
650
651 CloseHandle(token);
652 CloseHandle(junction);
653 PyMem_RawFree(rdb);
654
655 if (ret != 0)
656 return PyErr_SetFromWindowsErr(ret);
657
658 Py_RETURN_NONE;
659}
660
Zachary Waref2244ea2015-05-13 01:22:54 -0500661/*[clinic input]
662_winapi.CreateNamedPipe -> HANDLE
663
664 name: LPCTSTR
665 open_mode: DWORD
666 pipe_mode: DWORD
667 max_instances: DWORD
668 out_buffer_size: DWORD
669 in_buffer_size: DWORD
670 default_timeout: DWORD
671 security_attributes: LPSECURITY_ATTRIBUTES
672 /
673[clinic start generated code]*/
674
675static HANDLE
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300676_winapi_CreateNamedPipe_impl(PyObject *module, LPCTSTR name, DWORD open_mode,
677 DWORD pipe_mode, DWORD max_instances,
678 DWORD out_buffer_size, DWORD in_buffer_size,
679 DWORD default_timeout,
Zachary Ware77772c02015-05-13 10:58:35 -0500680 LPSECURITY_ATTRIBUTES security_attributes)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300681/*[clinic end generated code: output=80f8c07346a94fbc input=5a73530b84d8bc37]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200682{
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200683 HANDLE handle;
684
Steve Dowerb82e17e2019-05-23 08:45:22 -0700685 if (PySys_Audit("_winapi.CreateNamedPipe", "uII",
686 name, open_mode, pipe_mode) < 0) {
687 return INVALID_HANDLE_VALUE;
688 }
689
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200690 Py_BEGIN_ALLOW_THREADS
Zachary Waref2244ea2015-05-13 01:22:54 -0500691 handle = CreateNamedPipe(name, open_mode, pipe_mode,
692 max_instances, out_buffer_size,
693 in_buffer_size, default_timeout,
694 security_attributes);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200695 Py_END_ALLOW_THREADS
696
697 if (handle == INVALID_HANDLE_VALUE)
Zachary Waref2244ea2015-05-13 01:22:54 -0500698 PyErr_SetFromWindowsErr(0);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200699
Zachary Waref2244ea2015-05-13 01:22:54 -0500700 return handle;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200701}
702
Zachary Waref2244ea2015-05-13 01:22:54 -0500703/*[clinic input]
704_winapi.CreatePipe
705
706 pipe_attrs: object
707 Ignored internally, can be None.
708 size: DWORD
709 /
710
711Create an anonymous pipe.
712
713Returns a 2-tuple of handles, to the read and write ends of the pipe.
714[clinic start generated code]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200715
716static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +0300717_winapi_CreatePipe_impl(PyObject *module, PyObject *pipe_attrs, DWORD size)
718/*[clinic end generated code: output=1c4411d8699f0925 input=c4f2cfa56ef68d90]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200719{
720 HANDLE read_pipe;
721 HANDLE write_pipe;
722 BOOL result;
723
Steve Dowerb82e17e2019-05-23 08:45:22 -0700724 if (PySys_Audit("_winapi.CreatePipe", NULL) < 0) {
725 return NULL;
726 }
727
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200728 Py_BEGIN_ALLOW_THREADS
729 result = CreatePipe(&read_pipe, &write_pipe, NULL, size);
730 Py_END_ALLOW_THREADS
731
732 if (! result)
733 return PyErr_SetFromWindowsErr(GetLastError());
734
735 return Py_BuildValue(
736 "NN", HANDLE_TO_PYNUM(read_pipe), HANDLE_TO_PYNUM(write_pipe));
737}
738
739/* helpers for createprocess */
740
741static unsigned long
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200742getulong(PyObject* obj, const char* name)
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200743{
744 PyObject* value;
745 unsigned long ret;
746
747 value = PyObject_GetAttrString(obj, name);
748 if (! value) {
749 PyErr_Clear(); /* FIXME: propagate error? */
750 return 0;
751 }
752 ret = PyLong_AsUnsignedLong(value);
753 Py_DECREF(value);
754 return ret;
755}
756
757static HANDLE
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200758gethandle(PyObject* obj, const char* name)
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200759{
760 PyObject* value;
761 HANDLE ret;
762
763 value = PyObject_GetAttrString(obj, name);
764 if (! value) {
765 PyErr_Clear(); /* FIXME: propagate error? */
766 return NULL;
767 }
768 if (value == Py_None)
769 ret = NULL;
770 else
771 ret = PYNUM_TO_HANDLE(value);
772 Py_DECREF(value);
773 return ret;
774}
775
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +0200776static wchar_t *
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200777getenvironment(PyObject* environment)
778{
779 Py_ssize_t i, envsize, totalsize;
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +0200780 wchar_t *buffer = NULL, *p, *end;
781 PyObject *keys, *values;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200782
Ezio Melotti85a86292013-08-17 16:57:41 +0300783 /* convert environment dictionary to windows environment string */
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200784 if (! PyMapping_Check(environment)) {
785 PyErr_SetString(
786 PyExc_TypeError, "environment must be dictionary or None");
787 return NULL;
788 }
789
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200790 keys = PyMapping_Keys(environment);
Oren Milman0b3a87e2017-09-14 22:30:28 +0300791 if (!keys) {
792 return NULL;
793 }
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200794 values = PyMapping_Values(environment);
Oren Milman0b3a87e2017-09-14 22:30:28 +0300795 if (!values) {
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200796 goto error;
Oren Milman0b3a87e2017-09-14 22:30:28 +0300797 }
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200798
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +0200799 envsize = PyList_GET_SIZE(keys);
800 if (PyList_GET_SIZE(values) != envsize) {
Serhiy Storchakabf623ae2017-04-19 20:03:52 +0300801 PyErr_SetString(PyExc_RuntimeError,
802 "environment changed size during iteration");
803 goto error;
804 }
805
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200806 totalsize = 1; /* trailing null character */
807 for (i = 0; i < envsize; i++) {
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +0200808 PyObject* key = PyList_GET_ITEM(keys, i);
809 PyObject* value = PyList_GET_ITEM(values, i);
810 Py_ssize_t size;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200811
812 if (! PyUnicode_Check(key) || ! PyUnicode_Check(value)) {
813 PyErr_SetString(PyExc_TypeError,
814 "environment can only contain strings");
815 goto error;
816 }
Serhiy Storchakad174d242017-06-23 19:39:27 +0300817 if (PyUnicode_FindChar(key, '\0', 0, PyUnicode_GET_LENGTH(key), 1) != -1 ||
818 PyUnicode_FindChar(value, '\0', 0, PyUnicode_GET_LENGTH(value), 1) != -1)
819 {
820 PyErr_SetString(PyExc_ValueError, "embedded null character");
821 goto error;
822 }
823 /* Search from index 1 because on Windows starting '=' is allowed for
824 defining hidden environment variables. */
825 if (PyUnicode_GET_LENGTH(key) == 0 ||
826 PyUnicode_FindChar(key, '=', 1, PyUnicode_GET_LENGTH(key), 1) != -1)
827 {
828 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
829 goto error;
830 }
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +0200831
832 size = PyUnicode_AsWideChar(key, NULL, 0);
833 assert(size > 1);
834 if (totalsize > PY_SSIZE_T_MAX - size) {
Benjamin Peterson8ce68062015-02-09 20:58:12 -0500835 PyErr_SetString(PyExc_OverflowError, "environment too long");
836 goto error;
837 }
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +0200838 totalsize += size; /* including '=' */
839
840 size = PyUnicode_AsWideChar(value, NULL, 0);
841 assert(size > 0);
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 trailing '\0' */
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200847 }
848
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +0200849 buffer = PyMem_NEW(wchar_t, totalsize);
Benjamin Peterson8ce68062015-02-09 20:58:12 -0500850 if (! buffer) {
851 PyErr_NoMemory();
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200852 goto error;
Benjamin Peterson8ce68062015-02-09 20:58:12 -0500853 }
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200854 p = buffer;
855 end = buffer + totalsize;
856
857 for (i = 0; i < envsize; i++) {
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +0200858 PyObject* key = PyList_GET_ITEM(keys, i);
859 PyObject* value = PyList_GET_ITEM(values, i);
860 Py_ssize_t size = PyUnicode_AsWideChar(key, p, end - p);
861 assert(1 <= size && size < end - p);
862 p += size;
863 *p++ = L'=';
864 size = PyUnicode_AsWideChar(value, p, end - p);
865 assert(0 <= size && size < end - p);
866 p += size + 1;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200867 }
868
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +0200869 /* add trailing null character */
870 *p++ = L'\0';
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200871 assert(p == end);
872
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200873 error:
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200874 Py_XDECREF(keys);
875 Py_XDECREF(values);
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +0200876 return buffer;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +0200877}
878
Segev Finerb2a60832017-12-18 11:28:19 +0200879static LPHANDLE
880gethandlelist(PyObject *mapping, const char *name, Py_ssize_t *size)
881{
882 LPHANDLE ret = NULL;
883 PyObject *value_fast = NULL;
884 PyObject *value;
885 Py_ssize_t i;
886
887 value = PyMapping_GetItemString(mapping, name);
888 if (!value) {
889 PyErr_Clear();
890 return NULL;
891 }
892
893 if (value == Py_None) {
894 goto cleanup;
895 }
896
897 value_fast = PySequence_Fast(value, "handle_list must be a sequence or None");
898 if (value_fast == NULL)
899 goto cleanup;
900
901 *size = PySequence_Fast_GET_SIZE(value_fast) * sizeof(HANDLE);
902
903 /* Passing an empty array causes CreateProcess to fail so just don't set it */
904 if (*size == 0) {
905 goto cleanup;
906 }
907
908 ret = PyMem_Malloc(*size);
909 if (ret == NULL)
910 goto cleanup;
911
912 for (i = 0; i < PySequence_Fast_GET_SIZE(value_fast); i++) {
913 ret[i] = PYNUM_TO_HANDLE(PySequence_Fast_GET_ITEM(value_fast, i));
914 if (ret[i] == (HANDLE)-1 && PyErr_Occurred()) {
915 PyMem_Free(ret);
916 ret = NULL;
917 goto cleanup;
918 }
919 }
920
921cleanup:
922 Py_DECREF(value);
923 Py_XDECREF(value_fast);
924 return ret;
925}
926
927typedef struct {
928 LPPROC_THREAD_ATTRIBUTE_LIST attribute_list;
929 LPHANDLE handle_list;
930} AttributeList;
931
932static void
933freeattributelist(AttributeList *attribute_list)
934{
935 if (attribute_list->attribute_list != NULL) {
936 DeleteProcThreadAttributeList(attribute_list->attribute_list);
937 PyMem_Free(attribute_list->attribute_list);
938 }
939
940 PyMem_Free(attribute_list->handle_list);
941
942 memset(attribute_list, 0, sizeof(*attribute_list));
943}
944
945static int
946getattributelist(PyObject *obj, const char *name, AttributeList *attribute_list)
947{
948 int ret = 0;
949 DWORD err;
950 BOOL result;
951 PyObject *value;
952 Py_ssize_t handle_list_size;
953 DWORD attribute_count = 0;
954 SIZE_T attribute_list_size = 0;
955
956 value = PyObject_GetAttrString(obj, name);
957 if (!value) {
958 PyErr_Clear(); /* FIXME: propagate error? */
959 return 0;
960 }
961
962 if (value == Py_None) {
963 ret = 0;
964 goto cleanup;
965 }
966
967 if (!PyMapping_Check(value)) {
968 ret = -1;
969 PyErr_Format(PyExc_TypeError, "%s must be a mapping or None", name);
970 goto cleanup;
971 }
972
973 attribute_list->handle_list = gethandlelist(value, "handle_list", &handle_list_size);
974 if (attribute_list->handle_list == NULL && PyErr_Occurred()) {
975 ret = -1;
976 goto cleanup;
977 }
978
979 if (attribute_list->handle_list != NULL)
980 ++attribute_count;
981
982 /* Get how many bytes we need for the attribute list */
983 result = InitializeProcThreadAttributeList(NULL, attribute_count, 0, &attribute_list_size);
984 if (result || GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
985 ret = -1;
986 PyErr_SetFromWindowsErr(GetLastError());
987 goto cleanup;
988 }
989
990 attribute_list->attribute_list = PyMem_Malloc(attribute_list_size);
991 if (attribute_list->attribute_list == NULL) {
992 ret = -1;
993 goto cleanup;
994 }
995
996 result = InitializeProcThreadAttributeList(
997 attribute_list->attribute_list,
998 attribute_count,
999 0,
1000 &attribute_list_size);
1001 if (!result) {
1002 err = GetLastError();
1003
1004 /* So that we won't call DeleteProcThreadAttributeList */
1005 PyMem_Free(attribute_list->attribute_list);
1006 attribute_list->attribute_list = NULL;
1007
1008 ret = -1;
1009 PyErr_SetFromWindowsErr(err);
1010 goto cleanup;
1011 }
1012
1013 if (attribute_list->handle_list != NULL) {
1014 result = UpdateProcThreadAttribute(
1015 attribute_list->attribute_list,
1016 0,
1017 PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
1018 attribute_list->handle_list,
1019 handle_list_size,
1020 NULL,
1021 NULL);
1022 if (!result) {
1023 ret = -1;
1024 PyErr_SetFromWindowsErr(GetLastError());
1025 goto cleanup;
1026 }
1027 }
1028
1029cleanup:
1030 Py_DECREF(value);
1031
1032 if (ret < 0)
1033 freeattributelist(attribute_list);
1034
1035 return ret;
1036}
1037
Zachary Waref2244ea2015-05-13 01:22:54 -05001038/*[clinic input]
1039_winapi.CreateProcess
1040
Zachary Ware77772c02015-05-13 10:58:35 -05001041 application_name: Py_UNICODE(accept={str, NoneType})
Vladimir Matveev7b360162018-12-14 00:30:51 -08001042 command_line: object
1043 Can be str or None
Zachary Waref2244ea2015-05-13 01:22:54 -05001044 proc_attrs: object
1045 Ignored internally, can be None.
1046 thread_attrs: object
1047 Ignored internally, can be None.
1048 inherit_handles: BOOL
1049 creation_flags: DWORD
1050 env_mapping: object
Zachary Ware77772c02015-05-13 10:58:35 -05001051 current_directory: Py_UNICODE(accept={str, NoneType})
Zachary Waref2244ea2015-05-13 01:22:54 -05001052 startup_info: object
1053 /
1054
1055Create a new process and its primary thread.
1056
1057The return value is a tuple of the process handle, thread handle,
1058process ID, and thread ID.
1059[clinic start generated code]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001060
1061static PyObject *
Serhiy Storchakaafb3e712018-12-14 11:19:51 +02001062_winapi_CreateProcess_impl(PyObject *module,
1063 const Py_UNICODE *application_name,
Vladimir Matveev7b360162018-12-14 00:30:51 -08001064 PyObject *command_line, PyObject *proc_attrs,
Zachary Ware77772c02015-05-13 10:58:35 -05001065 PyObject *thread_attrs, BOOL inherit_handles,
1066 DWORD creation_flags, PyObject *env_mapping,
Serhiy Storchakaafb3e712018-12-14 11:19:51 +02001067 const Py_UNICODE *current_directory,
Zachary Ware77772c02015-05-13 10:58:35 -05001068 PyObject *startup_info)
Serhiy Storchakaafb3e712018-12-14 11:19:51 +02001069/*[clinic end generated code: output=9b2423a609230132 input=42ac293eaea03fc4]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001070{
Segev Finerb2a60832017-12-18 11:28:19 +02001071 PyObject *ret = NULL;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001072 BOOL result;
1073 PROCESS_INFORMATION pi;
Segev Finerb2a60832017-12-18 11:28:19 +02001074 STARTUPINFOEXW si;
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +02001075 wchar_t *wenvironment = NULL;
Vladimir Matveev7b360162018-12-14 00:30:51 -08001076 wchar_t *command_line_copy = NULL;
Segev Finerb2a60832017-12-18 11:28:19 +02001077 AttributeList attribute_list = {0};
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001078
Steve Dowerb82e17e2019-05-23 08:45:22 -07001079 if (PySys_Audit("_winapi.CreateProcess", "uuu", application_name,
1080 command_line, current_directory) < 0) {
1081 return NULL;
1082 }
1083
Victor Stinner252346a2020-05-01 11:33:44 +02001084 PyInterpreterState *interp = PyInterpreterState_Get();
1085 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
1086 if (config->_isolated_interpreter) {
1087 PyErr_SetString(PyExc_RuntimeError,
1088 "subprocess not supported for isolated subinterpreters");
1089 return NULL;
1090 }
1091
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001092 ZeroMemory(&si, sizeof(si));
Segev Finerb2a60832017-12-18 11:28:19 +02001093 si.StartupInfo.cb = sizeof(si);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001094
1095 /* note: we only support a small subset of all SI attributes */
Segev Finerb2a60832017-12-18 11:28:19 +02001096 si.StartupInfo.dwFlags = getulong(startup_info, "dwFlags");
1097 si.StartupInfo.wShowWindow = (WORD)getulong(startup_info, "wShowWindow");
1098 si.StartupInfo.hStdInput = gethandle(startup_info, "hStdInput");
1099 si.StartupInfo.hStdOutput = gethandle(startup_info, "hStdOutput");
1100 si.StartupInfo.hStdError = gethandle(startup_info, "hStdError");
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001101 if (PyErr_Occurred())
Segev Finerb2a60832017-12-18 11:28:19 +02001102 goto cleanup;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001103
1104 if (env_mapping != Py_None) {
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +02001105 wenvironment = getenvironment(env_mapping);
Serhiy Storchakad174d242017-06-23 19:39:27 +03001106 if (wenvironment == NULL) {
Segev Finerb2a60832017-12-18 11:28:19 +02001107 goto cleanup;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001108 }
1109 }
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001110
Segev Finerb2a60832017-12-18 11:28:19 +02001111 if (getattributelist(startup_info, "lpAttributeList", &attribute_list) < 0)
1112 goto cleanup;
1113
1114 si.lpAttributeList = attribute_list.attribute_list;
Vladimir Matveev7b360162018-12-14 00:30:51 -08001115 if (PyUnicode_Check(command_line)) {
1116 command_line_copy = PyUnicode_AsWideCharString(command_line, NULL);
1117 if (command_line_copy == NULL) {
1118 goto cleanup;
1119 }
1120 }
1121 else if (command_line != Py_None) {
Victor Stinner4a21e572020-04-15 02:35:41 +02001122 PyErr_Format(PyExc_TypeError,
1123 "CreateProcess() argument 2 must be str or None, not %s",
Vladimir Matveev7b360162018-12-14 00:30:51 -08001124 Py_TYPE(command_line)->tp_name);
1125 goto cleanup;
1126 }
1127
Segev Finerb2a60832017-12-18 11:28:19 +02001128
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001129 Py_BEGIN_ALLOW_THREADS
1130 result = CreateProcessW(application_name,
Vladimir Matveev7b360162018-12-14 00:30:51 -08001131 command_line_copy,
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001132 NULL,
1133 NULL,
1134 inherit_handles,
Segev Finerb2a60832017-12-18 11:28:19 +02001135 creation_flags | EXTENDED_STARTUPINFO_PRESENT |
1136 CREATE_UNICODE_ENVIRONMENT,
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001137 wenvironment,
1138 current_directory,
Segev Finerb2a60832017-12-18 11:28:19 +02001139 (LPSTARTUPINFOW)&si,
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001140 &pi);
1141 Py_END_ALLOW_THREADS
1142
Segev Finerb2a60832017-12-18 11:28:19 +02001143 if (!result) {
1144 PyErr_SetFromWindowsErr(GetLastError());
1145 goto cleanup;
1146 }
1147
1148 ret = Py_BuildValue("NNkk",
1149 HANDLE_TO_PYNUM(pi.hProcess),
1150 HANDLE_TO_PYNUM(pi.hThread),
1151 pi.dwProcessId,
1152 pi.dwThreadId);
1153
1154cleanup:
Vladimir Matveev7b360162018-12-14 00:30:51 -08001155 PyMem_Free(command_line_copy);
Serhiy Storchaka8abd7c72019-03-28 16:01:34 +02001156 PyMem_Free(wenvironment);
Segev Finerb2a60832017-12-18 11:28:19 +02001157 freeattributelist(&attribute_list);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001158
Segev Finerb2a60832017-12-18 11:28:19 +02001159 return ret;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001160}
1161
Zachary Waref2244ea2015-05-13 01:22:54 -05001162/*[clinic input]
1163_winapi.DuplicateHandle -> HANDLE
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001164
Zachary Waref2244ea2015-05-13 01:22:54 -05001165 source_process_handle: HANDLE
1166 source_handle: HANDLE
1167 target_process_handle: HANDLE
1168 desired_access: DWORD
1169 inherit_handle: BOOL
1170 options: DWORD = 0
1171 /
1172
1173Return a duplicate handle object.
1174
1175The duplicate handle refers to the same object as the original
1176handle. Therefore, any changes to the object are reflected
1177through both handles.
1178[clinic start generated code]*/
1179
1180static HANDLE
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001181_winapi_DuplicateHandle_impl(PyObject *module, HANDLE source_process_handle,
Zachary Ware77772c02015-05-13 10:58:35 -05001182 HANDLE source_handle,
1183 HANDLE target_process_handle,
1184 DWORD desired_access, BOOL inherit_handle,
1185 DWORD options)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001186/*[clinic end generated code: output=ad9711397b5dcd4e input=b933e3f2356a8c12]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001187{
1188 HANDLE target_handle;
1189 BOOL result;
1190
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001191 Py_BEGIN_ALLOW_THREADS
1192 result = DuplicateHandle(
1193 source_process_handle,
1194 source_handle,
1195 target_process_handle,
1196 &target_handle,
1197 desired_access,
1198 inherit_handle,
1199 options
1200 );
1201 Py_END_ALLOW_THREADS
1202
Zachary Waref2244ea2015-05-13 01:22:54 -05001203 if (! result) {
1204 PyErr_SetFromWindowsErr(GetLastError());
1205 return INVALID_HANDLE_VALUE;
1206 }
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001207
Zachary Waref2244ea2015-05-13 01:22:54 -05001208 return target_handle;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001209}
1210
Zachary Waref2244ea2015-05-13 01:22:54 -05001211/*[clinic input]
1212_winapi.ExitProcess
1213
1214 ExitCode: UINT
1215 /
1216
1217[clinic start generated code]*/
1218
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001219static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001220_winapi_ExitProcess_impl(PyObject *module, UINT ExitCode)
1221/*[clinic end generated code: output=a387deb651175301 input=4f05466a9406c558]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001222{
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001223 #if defined(Py_DEBUG)
1224 SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOALIGNMENTFAULTEXCEPT|
1225 SEM_NOGPFAULTERRORBOX|SEM_NOOPENFILEERRORBOX);
1226 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
1227 #endif
1228
Zachary Waref2244ea2015-05-13 01:22:54 -05001229 ExitProcess(ExitCode);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001230
1231 return NULL;
1232}
1233
Zachary Waref2244ea2015-05-13 01:22:54 -05001234/*[clinic input]
1235_winapi.GetCurrentProcess -> HANDLE
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001236
Zachary Waref2244ea2015-05-13 01:22:54 -05001237Return a handle object for the current process.
1238[clinic start generated code]*/
1239
1240static HANDLE
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001241_winapi_GetCurrentProcess_impl(PyObject *module)
1242/*[clinic end generated code: output=ddeb4dd2ffadf344 input=b213403fd4b96b41]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001243{
Zachary Waref2244ea2015-05-13 01:22:54 -05001244 return GetCurrentProcess();
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001245}
1246
Zachary Waref2244ea2015-05-13 01:22:54 -05001247/*[clinic input]
1248_winapi.GetExitCodeProcess -> DWORD
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001249
Zachary Waref2244ea2015-05-13 01:22:54 -05001250 process: HANDLE
1251 /
1252
1253Return the termination status of the specified process.
1254[clinic start generated code]*/
1255
1256static DWORD
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001257_winapi_GetExitCodeProcess_impl(PyObject *module, HANDLE process)
1258/*[clinic end generated code: output=b4620bdf2bccf36b input=61b6bfc7dc2ee374]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001259{
1260 DWORD exit_code;
1261 BOOL result;
1262
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001263 result = GetExitCodeProcess(process, &exit_code);
1264
Zachary Waref2244ea2015-05-13 01:22:54 -05001265 if (! result) {
1266 PyErr_SetFromWindowsErr(GetLastError());
Victor Stinner850a18e2017-10-24 16:53:32 -07001267 exit_code = PY_DWORD_MAX;
Zachary Waref2244ea2015-05-13 01:22:54 -05001268 }
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001269
Zachary Waref2244ea2015-05-13 01:22:54 -05001270 return exit_code;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001271}
1272
Zachary Waref2244ea2015-05-13 01:22:54 -05001273/*[clinic input]
1274_winapi.GetLastError -> DWORD
1275[clinic start generated code]*/
1276
1277static DWORD
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001278_winapi_GetLastError_impl(PyObject *module)
1279/*[clinic end generated code: output=8585b827cb1a92c5 input=62d47fb9bce038ba]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001280{
Zachary Waref2244ea2015-05-13 01:22:54 -05001281 return GetLastError();
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001282}
1283
Zachary Waref2244ea2015-05-13 01:22:54 -05001284/*[clinic input]
1285_winapi.GetModuleFileName
1286
1287 module_handle: HMODULE
1288 /
1289
1290Return the fully-qualified path for the file that contains module.
1291
1292The module must have been loaded by the current process.
1293
1294The module parameter should be a handle to the loaded module
1295whose path is being requested. If this parameter is 0,
1296GetModuleFileName retrieves the path of the executable file
1297of the current process.
1298[clinic start generated code]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001299
1300static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001301_winapi_GetModuleFileName_impl(PyObject *module, HMODULE module_handle)
1302/*[clinic end generated code: output=85b4b728c5160306 input=6d66ff7deca5d11f]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001303{
1304 BOOL result;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001305 WCHAR filename[MAX_PATH];
1306
Steve Dowerb82e17e2019-05-23 08:45:22 -07001307 Py_BEGIN_ALLOW_THREADS
Zachary Waref2244ea2015-05-13 01:22:54 -05001308 result = GetModuleFileNameW(module_handle, filename, MAX_PATH);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001309 filename[MAX_PATH-1] = '\0';
Steve Dowerb82e17e2019-05-23 08:45:22 -07001310 Py_END_ALLOW_THREADS
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001311
1312 if (! result)
1313 return PyErr_SetFromWindowsErr(GetLastError());
1314
1315 return PyUnicode_FromWideChar(filename, wcslen(filename));
1316}
1317
Zachary Waref2244ea2015-05-13 01:22:54 -05001318/*[clinic input]
1319_winapi.GetStdHandle -> HANDLE
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001320
Zachary Waref2244ea2015-05-13 01:22:54 -05001321 std_handle: DWORD
1322 One of STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, or STD_ERROR_HANDLE.
1323 /
1324
1325Return a handle to the specified standard device.
1326
1327The integer associated with the handle object is returned.
1328[clinic start generated code]*/
1329
1330static HANDLE
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001331_winapi_GetStdHandle_impl(PyObject *module, DWORD std_handle)
1332/*[clinic end generated code: output=0e613001e73ab614 input=07016b06a2fc8826]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001333{
1334 HANDLE handle;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001335
1336 Py_BEGIN_ALLOW_THREADS
1337 handle = GetStdHandle(std_handle);
1338 Py_END_ALLOW_THREADS
1339
1340 if (handle == INVALID_HANDLE_VALUE)
Zachary Waref2244ea2015-05-13 01:22:54 -05001341 PyErr_SetFromWindowsErr(GetLastError());
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001342
Zachary Waref2244ea2015-05-13 01:22:54 -05001343 return handle;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001344}
1345
Zachary Waref2244ea2015-05-13 01:22:54 -05001346/*[clinic input]
1347_winapi.GetVersion -> long
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001348
Zachary Waref2244ea2015-05-13 01:22:54 -05001349Return the version number of the current operating system.
1350[clinic start generated code]*/
1351
1352static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001353_winapi_GetVersion_impl(PyObject *module)
1354/*[clinic end generated code: output=e41f0db5a3b82682 input=e21dff8d0baeded2]*/
Steve Dower3e96f322015-03-02 08:01:10 -08001355/* Disable deprecation warnings about GetVersionEx as the result is
1356 being passed straight through to the caller, who is responsible for
1357 using it correctly. */
1358#pragma warning(push)
1359#pragma warning(disable:4996)
1360
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001361{
Zachary Waref2244ea2015-05-13 01:22:54 -05001362 return GetVersion();
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001363}
1364
Steve Dower3e96f322015-03-02 08:01:10 -08001365#pragma warning(pop)
1366
Zachary Waref2244ea2015-05-13 01:22:54 -05001367/*[clinic input]
Davin Pottse895de32019-02-23 22:08:16 -06001368_winapi.MapViewOfFile -> LPVOID
1369
1370 file_map: HANDLE
1371 desired_access: DWORD
1372 file_offset_high: DWORD
1373 file_offset_low: DWORD
1374 number_bytes: size_t
1375 /
1376[clinic start generated code]*/
1377
1378static LPVOID
1379_winapi_MapViewOfFile_impl(PyObject *module, HANDLE file_map,
1380 DWORD desired_access, DWORD file_offset_high,
1381 DWORD file_offset_low, size_t number_bytes)
1382/*[clinic end generated code: output=f23b1ee4823663e3 input=177471073be1a103]*/
1383{
1384 LPVOID address;
1385
1386 Py_BEGIN_ALLOW_THREADS
1387 address = MapViewOfFile(file_map, desired_access, file_offset_high,
1388 file_offset_low, number_bytes);
1389 Py_END_ALLOW_THREADS
1390
1391 if (address == NULL)
1392 PyErr_SetFromWindowsErr(0);
1393
1394 return address;
1395}
1396
1397/*[clinic input]
1398_winapi.OpenFileMapping -> HANDLE
1399
1400 desired_access: DWORD
1401 inherit_handle: BOOL
1402 name: LPCWSTR
1403 /
1404[clinic start generated code]*/
1405
1406static HANDLE
1407_winapi_OpenFileMapping_impl(PyObject *module, DWORD desired_access,
1408 BOOL inherit_handle, LPCWSTR name)
1409/*[clinic end generated code: output=08cc44def1cb11f1 input=131f2a405359de7f]*/
1410{
1411 HANDLE handle;
1412
1413 Py_BEGIN_ALLOW_THREADS
1414 handle = OpenFileMappingW(desired_access, inherit_handle, name);
1415 Py_END_ALLOW_THREADS
1416
1417 if (handle == NULL) {
Zackery Spytzeda385c2019-05-30 01:58:50 -06001418 PyObject *temp = PyUnicode_FromWideChar(name, -1);
1419 PyErr_SetExcFromWindowsErrWithFilenameObject(PyExc_OSError, 0, temp);
1420 Py_XDECREF(temp);
Davin Pottse895de32019-02-23 22:08:16 -06001421 handle = INVALID_HANDLE_VALUE;
1422 }
1423
1424 return handle;
1425}
1426
1427/*[clinic input]
Zachary Waref2244ea2015-05-13 01:22:54 -05001428_winapi.OpenProcess -> HANDLE
1429
1430 desired_access: DWORD
1431 inherit_handle: BOOL
1432 process_id: DWORD
1433 /
1434[clinic start generated code]*/
1435
1436static HANDLE
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001437_winapi_OpenProcess_impl(PyObject *module, DWORD desired_access,
Zachary Ware77772c02015-05-13 10:58:35 -05001438 BOOL inherit_handle, DWORD process_id)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001439/*[clinic end generated code: output=b42b6b81ea5a0fc3 input=ec98c4cf4ea2ec36]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001440{
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001441 HANDLE handle;
1442
Steve Dowerb82e17e2019-05-23 08:45:22 -07001443 if (PySys_Audit("_winapi.OpenProcess", "II",
1444 process_id, desired_access) < 0) {
1445 return INVALID_HANDLE_VALUE;
1446 }
1447
1448 Py_BEGIN_ALLOW_THREADS
Zachary Waref2244ea2015-05-13 01:22:54 -05001449 handle = OpenProcess(desired_access, inherit_handle, process_id);
Steve Dowerb82e17e2019-05-23 08:45:22 -07001450 Py_END_ALLOW_THREADS
Zachary Waref2244ea2015-05-13 01:22:54 -05001451 if (handle == NULL) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001452 PyErr_SetFromWindowsErr(GetLastError());
Zachary Waref2244ea2015-05-13 01:22:54 -05001453 handle = INVALID_HANDLE_VALUE;
1454 }
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001455
Zachary Waref2244ea2015-05-13 01:22:54 -05001456 return handle;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001457}
1458
Zachary Waref2244ea2015-05-13 01:22:54 -05001459/*[clinic input]
1460_winapi.PeekNamedPipe
1461
1462 handle: HANDLE
1463 size: int = 0
1464 /
1465[clinic start generated code]*/
1466
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001467static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001468_winapi_PeekNamedPipe_impl(PyObject *module, HANDLE handle, int size)
1469/*[clinic end generated code: output=d0c3e29e49d323dd input=c7aa53bfbce69d70]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001470{
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001471 PyObject *buf = NULL;
1472 DWORD nread, navail, nleft;
1473 BOOL ret;
1474
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001475 if (size < 0) {
1476 PyErr_SetString(PyExc_ValueError, "negative size");
1477 return NULL;
1478 }
1479
1480 if (size) {
1481 buf = PyBytes_FromStringAndSize(NULL, size);
1482 if (!buf)
1483 return NULL;
1484 Py_BEGIN_ALLOW_THREADS
1485 ret = PeekNamedPipe(handle, PyBytes_AS_STRING(buf), size, &nread,
1486 &navail, &nleft);
1487 Py_END_ALLOW_THREADS
1488 if (!ret) {
1489 Py_DECREF(buf);
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03001490 return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001491 }
1492 if (_PyBytes_Resize(&buf, nread))
1493 return NULL;
Alexander Buchkovsky266f4902018-09-04 19:10:28 +03001494 return Py_BuildValue("NII", buf, navail, nleft);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001495 }
1496 else {
1497 Py_BEGIN_ALLOW_THREADS
1498 ret = PeekNamedPipe(handle, NULL, 0, NULL, &navail, &nleft);
1499 Py_END_ALLOW_THREADS
1500 if (!ret) {
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03001501 return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001502 }
Alexander Buchkovsky266f4902018-09-04 19:10:28 +03001503 return Py_BuildValue("II", navail, nleft);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001504 }
1505}
1506
Zachary Waref2244ea2015-05-13 01:22:54 -05001507/*[clinic input]
1508_winapi.ReadFile
1509
1510 handle: HANDLE
Alexander Buchkovsky266f4902018-09-04 19:10:28 +03001511 size: DWORD
Serhiy Storchaka202fda52017-03-12 10:10:47 +02001512 overlapped as use_overlapped: bool(accept={int}) = False
Zachary Waref2244ea2015-05-13 01:22:54 -05001513[clinic start generated code]*/
1514
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001515static PyObject *
Alexander Buchkovsky266f4902018-09-04 19:10:28 +03001516_winapi_ReadFile_impl(PyObject *module, HANDLE handle, DWORD size,
Zachary Ware77772c02015-05-13 10:58:35 -05001517 int use_overlapped)
Alexander Buchkovsky266f4902018-09-04 19:10:28 +03001518/*[clinic end generated code: output=d3d5b44a8201b944 input=08c439d03a11aac5]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001519{
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001520 DWORD nread;
1521 PyObject *buf;
1522 BOOL ret;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001523 DWORD err;
1524 OverlappedObject *overlapped = NULL;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001525
1526 buf = PyBytes_FromStringAndSize(NULL, size);
1527 if (!buf)
1528 return NULL;
1529 if (use_overlapped) {
1530 overlapped = new_overlapped(handle);
1531 if (!overlapped) {
1532 Py_DECREF(buf);
1533 return NULL;
1534 }
1535 /* Steals reference to buf */
1536 overlapped->read_buffer = buf;
1537 }
1538
1539 Py_BEGIN_ALLOW_THREADS
1540 ret = ReadFile(handle, PyBytes_AS_STRING(buf), size, &nread,
1541 overlapped ? &overlapped->overlapped : NULL);
1542 Py_END_ALLOW_THREADS
1543
1544 err = ret ? 0 : GetLastError();
1545
1546 if (overlapped) {
1547 if (!ret) {
1548 if (err == ERROR_IO_PENDING)
1549 overlapped->pending = 1;
1550 else if (err != ERROR_MORE_DATA) {
1551 Py_DECREF(overlapped);
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03001552 return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001553 }
1554 }
1555 return Py_BuildValue("NI", (PyObject *) overlapped, err);
1556 }
1557
1558 if (!ret && err != ERROR_MORE_DATA) {
1559 Py_DECREF(buf);
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03001560 return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001561 }
1562 if (_PyBytes_Resize(&buf, nread))
1563 return NULL;
1564 return Py_BuildValue("NI", buf, err);
1565}
1566
Zachary Waref2244ea2015-05-13 01:22:54 -05001567/*[clinic input]
1568_winapi.SetNamedPipeHandleState
1569
1570 named_pipe: HANDLE
1571 mode: object
1572 max_collection_count: object
1573 collect_data_timeout: object
1574 /
1575[clinic start generated code]*/
1576
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001577static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001578_winapi_SetNamedPipeHandleState_impl(PyObject *module, HANDLE named_pipe,
Zachary Ware77772c02015-05-13 10:58:35 -05001579 PyObject *mode,
1580 PyObject *max_collection_count,
1581 PyObject *collect_data_timeout)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001582/*[clinic end generated code: output=f2129d222cbfa095 input=9142d72163d0faa6]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001583{
Zachary Waref2244ea2015-05-13 01:22:54 -05001584 PyObject *oArgs[3] = {mode, max_collection_count, collect_data_timeout};
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001585 DWORD dwArgs[3], *pArgs[3] = {NULL, NULL, NULL};
1586 int i;
Steve Dowerb82e17e2019-05-23 08:45:22 -07001587 BOOL b;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001588
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001589 for (i = 0 ; i < 3 ; i++) {
1590 if (oArgs[i] != Py_None) {
1591 dwArgs[i] = PyLong_AsUnsignedLongMask(oArgs[i]);
1592 if (PyErr_Occurred())
1593 return NULL;
1594 pArgs[i] = &dwArgs[i];
1595 }
1596 }
1597
Steve Dowerb82e17e2019-05-23 08:45:22 -07001598 Py_BEGIN_ALLOW_THREADS
1599 b = SetNamedPipeHandleState(named_pipe, pArgs[0], pArgs[1], pArgs[2]);
1600 Py_END_ALLOW_THREADS
1601
1602 if (!b)
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001603 return PyErr_SetFromWindowsErr(0);
1604
1605 Py_RETURN_NONE;
1606}
1607
Zachary Waref2244ea2015-05-13 01:22:54 -05001608
1609/*[clinic input]
1610_winapi.TerminateProcess
1611
1612 handle: HANDLE
1613 exit_code: UINT
1614 /
1615
1616Terminate the specified process and all of its threads.
1617[clinic start generated code]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001618
1619static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001620_winapi_TerminateProcess_impl(PyObject *module, HANDLE handle,
Zachary Ware77772c02015-05-13 10:58:35 -05001621 UINT exit_code)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001622/*[clinic end generated code: output=f4e99ac3f0b1f34a input=d6bc0aa1ee3bb4df]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001623{
1624 BOOL result;
1625
Steve Dowerb82e17e2019-05-23 08:45:22 -07001626 if (PySys_Audit("_winapi.TerminateProcess", "nI",
1627 (Py_ssize_t)handle, exit_code) < 0) {
1628 return NULL;
1629 }
1630
Zachary Waref2244ea2015-05-13 01:22:54 -05001631 result = TerminateProcess(handle, exit_code);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001632
1633 if (! result)
1634 return PyErr_SetFromWindowsErr(GetLastError());
1635
Zachary Waref2244ea2015-05-13 01:22:54 -05001636 Py_RETURN_NONE;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001637}
1638
Zachary Waref2244ea2015-05-13 01:22:54 -05001639/*[clinic input]
Davin Pottse895de32019-02-23 22:08:16 -06001640_winapi.VirtualQuerySize -> size_t
1641
1642 address: LPCVOID
1643 /
1644[clinic start generated code]*/
1645
1646static size_t
1647_winapi_VirtualQuerySize_impl(PyObject *module, LPCVOID address)
1648/*[clinic end generated code: output=40c8e0ff5ec964df input=6b784a69755d0bb6]*/
1649{
1650 SIZE_T size_of_buf;
1651 MEMORY_BASIC_INFORMATION mem_basic_info;
1652 SIZE_T region_size;
1653
1654 Py_BEGIN_ALLOW_THREADS
1655 size_of_buf = VirtualQuery(address, &mem_basic_info, sizeof(mem_basic_info));
1656 Py_END_ALLOW_THREADS
1657
1658 if (size_of_buf == 0)
1659 PyErr_SetFromWindowsErr(0);
1660
1661 region_size = mem_basic_info.RegionSize;
1662 return region_size;
1663}
1664
1665/*[clinic input]
Zachary Waref2244ea2015-05-13 01:22:54 -05001666_winapi.WaitNamedPipe
1667
1668 name: LPCTSTR
1669 timeout: DWORD
1670 /
1671[clinic start generated code]*/
1672
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001673static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001674_winapi_WaitNamedPipe_impl(PyObject *module, LPCTSTR name, DWORD timeout)
1675/*[clinic end generated code: output=c2866f4439b1fe38 input=36fc781291b1862c]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001676{
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001677 BOOL success;
1678
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001679 Py_BEGIN_ALLOW_THREADS
Zachary Waref2244ea2015-05-13 01:22:54 -05001680 success = WaitNamedPipe(name, timeout);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001681 Py_END_ALLOW_THREADS
1682
1683 if (!success)
1684 return PyErr_SetFromWindowsErr(0);
1685
1686 Py_RETURN_NONE;
1687}
1688
Zachary Waref2244ea2015-05-13 01:22:54 -05001689/*[clinic input]
1690_winapi.WaitForMultipleObjects
1691
1692 handle_seq: object
1693 wait_flag: BOOL
1694 milliseconds: DWORD(c_default='INFINITE') = _winapi.INFINITE
1695 /
1696[clinic start generated code]*/
1697
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001698static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001699_winapi_WaitForMultipleObjects_impl(PyObject *module, PyObject *handle_seq,
1700 BOOL wait_flag, DWORD milliseconds)
1701/*[clinic end generated code: output=295e3f00b8e45899 input=36f76ca057cd28a0]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001702{
1703 DWORD result;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001704 HANDLE handles[MAXIMUM_WAIT_OBJECTS];
1705 HANDLE sigint_event = NULL;
1706 Py_ssize_t nhandles, i;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001707
1708 if (!PySequence_Check(handle_seq)) {
1709 PyErr_Format(PyExc_TypeError,
1710 "sequence type expected, got '%s'",
Richard Oudkerk67339272012-08-21 14:54:22 +01001711 Py_TYPE(handle_seq)->tp_name);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001712 return NULL;
1713 }
1714 nhandles = PySequence_Length(handle_seq);
1715 if (nhandles == -1)
1716 return NULL;
1717 if (nhandles < 0 || nhandles >= MAXIMUM_WAIT_OBJECTS - 1) {
1718 PyErr_Format(PyExc_ValueError,
1719 "need at most %zd handles, got a sequence of length %zd",
1720 MAXIMUM_WAIT_OBJECTS - 1, nhandles);
1721 return NULL;
1722 }
1723 for (i = 0; i < nhandles; i++) {
1724 HANDLE h;
1725 PyObject *v = PySequence_GetItem(handle_seq, i);
1726 if (v == NULL)
1727 return NULL;
1728 if (!PyArg_Parse(v, F_HANDLE, &h)) {
1729 Py_DECREF(v);
1730 return NULL;
1731 }
1732 handles[i] = h;
1733 Py_DECREF(v);
1734 }
1735 /* If this is the main thread then make the wait interruptible
1736 by Ctrl-C unless we are waiting for *all* handles */
1737 if (!wait_flag && _PyOS_IsMainThread()) {
1738 sigint_event = _PyOS_SigintEvent();
1739 assert(sigint_event != NULL);
1740 handles[nhandles++] = sigint_event;
1741 }
1742
1743 Py_BEGIN_ALLOW_THREADS
1744 if (sigint_event != NULL)
1745 ResetEvent(sigint_event);
1746 result = WaitForMultipleObjects((DWORD) nhandles, handles,
1747 wait_flag, milliseconds);
1748 Py_END_ALLOW_THREADS
1749
1750 if (result == WAIT_FAILED)
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03001751 return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001752 else if (sigint_event != NULL && result == WAIT_OBJECT_0 + nhandles - 1) {
1753 errno = EINTR;
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03001754 return PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001755 }
1756
1757 return PyLong_FromLong((int) result);
1758}
1759
Zachary Waref2244ea2015-05-13 01:22:54 -05001760/*[clinic input]
1761_winapi.WaitForSingleObject -> long
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001762
Zachary Waref2244ea2015-05-13 01:22:54 -05001763 handle: HANDLE
1764 milliseconds: DWORD
1765 /
1766
1767Wait for a single object.
1768
1769Wait until the specified object is in the signaled state or
1770the time-out interval elapses. The timeout value is specified
1771in milliseconds.
1772[clinic start generated code]*/
1773
1774static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001775_winapi_WaitForSingleObject_impl(PyObject *module, HANDLE handle,
Zachary Ware77772c02015-05-13 10:58:35 -05001776 DWORD milliseconds)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001777/*[clinic end generated code: output=3c4715d8f1b39859 input=443d1ab076edc7b1]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001778{
1779 DWORD result;
1780
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001781 Py_BEGIN_ALLOW_THREADS
1782 result = WaitForSingleObject(handle, milliseconds);
1783 Py_END_ALLOW_THREADS
1784
Zachary Waref2244ea2015-05-13 01:22:54 -05001785 if (result == WAIT_FAILED) {
1786 PyErr_SetFromWindowsErr(GetLastError());
1787 return -1;
1788 }
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001789
Zachary Waref2244ea2015-05-13 01:22:54 -05001790 return result;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001791}
1792
Zachary Waref2244ea2015-05-13 01:22:54 -05001793/*[clinic input]
1794_winapi.WriteFile
1795
1796 handle: HANDLE
1797 buffer: object
Serhiy Storchaka202fda52017-03-12 10:10:47 +02001798 overlapped as use_overlapped: bool(accept={int}) = False
Zachary Waref2244ea2015-05-13 01:22:54 -05001799[clinic start generated code]*/
1800
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001801static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001802_winapi_WriteFile_impl(PyObject *module, HANDLE handle, PyObject *buffer,
Zachary Ware77772c02015-05-13 10:58:35 -05001803 int use_overlapped)
Serhiy Storchaka202fda52017-03-12 10:10:47 +02001804/*[clinic end generated code: output=2ca80f6bf3fa92e3 input=11eae2a03aa32731]*/
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001805{
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001806 Py_buffer _buf, *buf;
Victor Stinner71765772013-06-24 23:13:24 +02001807 DWORD len, written;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001808 BOOL ret;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001809 DWORD err;
1810 OverlappedObject *overlapped = NULL;
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001811
1812 if (use_overlapped) {
1813 overlapped = new_overlapped(handle);
1814 if (!overlapped)
1815 return NULL;
1816 buf = &overlapped->write_buffer;
1817 }
1818 else
1819 buf = &_buf;
1820
Zachary Waref2244ea2015-05-13 01:22:54 -05001821 if (!PyArg_Parse(buffer, "y*", buf)) {
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001822 Py_XDECREF(overlapped);
1823 return NULL;
1824 }
1825
1826 Py_BEGIN_ALLOW_THREADS
Victor Stinner850a18e2017-10-24 16:53:32 -07001827 len = (DWORD)Py_MIN(buf->len, PY_DWORD_MAX);
Victor Stinner71765772013-06-24 23:13:24 +02001828 ret = WriteFile(handle, buf->buf, len, &written,
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001829 overlapped ? &overlapped->overlapped : NULL);
1830 Py_END_ALLOW_THREADS
1831
1832 err = ret ? 0 : GetLastError();
1833
1834 if (overlapped) {
1835 if (!ret) {
1836 if (err == ERROR_IO_PENDING)
1837 overlapped->pending = 1;
1838 else {
1839 Py_DECREF(overlapped);
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03001840 return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001841 }
1842 }
1843 return Py_BuildValue("NI", (PyObject *) overlapped, err);
1844 }
1845
1846 PyBuffer_Release(buf);
1847 if (!ret)
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03001848 return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001849 return Py_BuildValue("II", written, err);
1850}
1851
Victor Stinner91106cd2017-12-13 12:29:09 +01001852/*[clinic input]
1853_winapi.GetACP
1854
1855Get the current Windows ANSI code page identifier.
1856[clinic start generated code]*/
1857
1858static PyObject *
1859_winapi_GetACP_impl(PyObject *module)
1860/*[clinic end generated code: output=f7ee24bf705dbb88 input=1433c96d03a05229]*/
1861{
1862 return PyLong_FromUnsignedLong(GetACP());
1863}
1864
Segev Finerb2a60832017-12-18 11:28:19 +02001865/*[clinic input]
1866_winapi.GetFileType -> DWORD
1867
1868 handle: HANDLE
1869[clinic start generated code]*/
1870
1871static DWORD
1872_winapi_GetFileType_impl(PyObject *module, HANDLE handle)
1873/*[clinic end generated code: output=92b8466ac76ecc17 input=0058366bc40bbfbf]*/
1874{
1875 DWORD result;
1876
1877 Py_BEGIN_ALLOW_THREADS
1878 result = GetFileType(handle);
1879 Py_END_ALLOW_THREADS
1880
1881 if (result == FILE_TYPE_UNKNOWN && GetLastError() != NO_ERROR) {
1882 PyErr_SetFromWindowsErr(0);
1883 return -1;
1884 }
1885
1886 return result;
1887}
1888
Victor Stinner91106cd2017-12-13 12:29:09 +01001889
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001890static PyMethodDef winapi_functions[] = {
Zachary Waref2244ea2015-05-13 01:22:54 -05001891 _WINAPI_CLOSEHANDLE_METHODDEF
1892 _WINAPI_CONNECTNAMEDPIPE_METHODDEF
1893 _WINAPI_CREATEFILE_METHODDEF
Davin Pottse895de32019-02-23 22:08:16 -06001894 _WINAPI_CREATEFILEMAPPING_METHODDEF
Zachary Waref2244ea2015-05-13 01:22:54 -05001895 _WINAPI_CREATENAMEDPIPE_METHODDEF
1896 _WINAPI_CREATEPIPE_METHODDEF
1897 _WINAPI_CREATEPROCESS_METHODDEF
1898 _WINAPI_CREATEJUNCTION_METHODDEF
1899 _WINAPI_DUPLICATEHANDLE_METHODDEF
1900 _WINAPI_EXITPROCESS_METHODDEF
1901 _WINAPI_GETCURRENTPROCESS_METHODDEF
1902 _WINAPI_GETEXITCODEPROCESS_METHODDEF
1903 _WINAPI_GETLASTERROR_METHODDEF
1904 _WINAPI_GETMODULEFILENAME_METHODDEF
1905 _WINAPI_GETSTDHANDLE_METHODDEF
1906 _WINAPI_GETVERSION_METHODDEF
Davin Pottse895de32019-02-23 22:08:16 -06001907 _WINAPI_MAPVIEWOFFILE_METHODDEF
1908 _WINAPI_OPENFILEMAPPING_METHODDEF
Zachary Waref2244ea2015-05-13 01:22:54 -05001909 _WINAPI_OPENPROCESS_METHODDEF
1910 _WINAPI_PEEKNAMEDPIPE_METHODDEF
1911 _WINAPI_READFILE_METHODDEF
1912 _WINAPI_SETNAMEDPIPEHANDLESTATE_METHODDEF
1913 _WINAPI_TERMINATEPROCESS_METHODDEF
Davin Pottse895de32019-02-23 22:08:16 -06001914 _WINAPI_VIRTUALQUERYSIZE_METHODDEF
Zachary Waref2244ea2015-05-13 01:22:54 -05001915 _WINAPI_WAITNAMEDPIPE_METHODDEF
1916 _WINAPI_WAITFORMULTIPLEOBJECTS_METHODDEF
1917 _WINAPI_WAITFORSINGLEOBJECT_METHODDEF
1918 _WINAPI_WRITEFILE_METHODDEF
Victor Stinner91106cd2017-12-13 12:29:09 +01001919 _WINAPI_GETACP_METHODDEF
Segev Finerb2a60832017-12-18 11:28:19 +02001920 _WINAPI_GETFILETYPE_METHODDEF
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001921 {NULL, NULL}
1922};
1923
1924static struct PyModuleDef winapi_module = {
1925 PyModuleDef_HEAD_INIT,
1926 "_winapi",
1927 NULL,
1928 -1,
1929 winapi_functions,
1930 NULL,
1931 NULL,
1932 NULL,
1933 NULL
1934};
1935
1936#define WINAPI_CONSTANT(fmt, con) \
1937 PyDict_SetItemString(d, #con, Py_BuildValue(fmt, con))
1938
1939PyMODINIT_FUNC
1940PyInit__winapi(void)
1941{
1942 PyObject *d;
1943 PyObject *m;
1944
1945 if (PyType_Ready(&OverlappedType) < 0)
1946 return NULL;
1947
1948 m = PyModule_Create(&winapi_module);
1949 if (m == NULL)
1950 return NULL;
1951 d = PyModule_GetDict(m);
1952
1953 PyDict_SetItemString(d, "Overlapped", (PyObject *) &OverlappedType);
1954
1955 /* constants */
1956 WINAPI_CONSTANT(F_DWORD, CREATE_NEW_CONSOLE);
1957 WINAPI_CONSTANT(F_DWORD, CREATE_NEW_PROCESS_GROUP);
1958 WINAPI_CONSTANT(F_DWORD, DUPLICATE_SAME_ACCESS);
Antoine Pitrou5438ed12012-04-24 22:56:57 +02001959 WINAPI_CONSTANT(F_DWORD, DUPLICATE_CLOSE_SOURCE);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001960 WINAPI_CONSTANT(F_DWORD, ERROR_ALREADY_EXISTS);
1961 WINAPI_CONSTANT(F_DWORD, ERROR_BROKEN_PIPE);
1962 WINAPI_CONSTANT(F_DWORD, ERROR_IO_PENDING);
1963 WINAPI_CONSTANT(F_DWORD, ERROR_MORE_DATA);
1964 WINAPI_CONSTANT(F_DWORD, ERROR_NETNAME_DELETED);
1965 WINAPI_CONSTANT(F_DWORD, ERROR_NO_SYSTEM_RESOURCES);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001966 WINAPI_CONSTANT(F_DWORD, ERROR_MORE_DATA);
1967 WINAPI_CONSTANT(F_DWORD, ERROR_NETNAME_DELETED);
Richard Oudkerkfdb8dcf2012-05-05 19:45:37 +01001968 WINAPI_CONSTANT(F_DWORD, ERROR_NO_DATA);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001969 WINAPI_CONSTANT(F_DWORD, ERROR_NO_SYSTEM_RESOURCES);
1970 WINAPI_CONSTANT(F_DWORD, ERROR_OPERATION_ABORTED);
1971 WINAPI_CONSTANT(F_DWORD, ERROR_PIPE_BUSY);
1972 WINAPI_CONSTANT(F_DWORD, ERROR_PIPE_CONNECTED);
1973 WINAPI_CONSTANT(F_DWORD, ERROR_SEM_TIMEOUT);
1974 WINAPI_CONSTANT(F_DWORD, FILE_FLAG_FIRST_PIPE_INSTANCE);
1975 WINAPI_CONSTANT(F_DWORD, FILE_FLAG_OVERLAPPED);
Antoine Pitrou5438ed12012-04-24 22:56:57 +02001976 WINAPI_CONSTANT(F_DWORD, FILE_GENERIC_READ);
1977 WINAPI_CONSTANT(F_DWORD, FILE_GENERIC_WRITE);
Davin Pottse895de32019-02-23 22:08:16 -06001978 WINAPI_CONSTANT(F_DWORD, FILE_MAP_ALL_ACCESS);
1979 WINAPI_CONSTANT(F_DWORD, FILE_MAP_COPY);
1980 WINAPI_CONSTANT(F_DWORD, FILE_MAP_EXECUTE);
1981 WINAPI_CONSTANT(F_DWORD, FILE_MAP_READ);
1982 WINAPI_CONSTANT(F_DWORD, FILE_MAP_WRITE);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001983 WINAPI_CONSTANT(F_DWORD, GENERIC_READ);
1984 WINAPI_CONSTANT(F_DWORD, GENERIC_WRITE);
1985 WINAPI_CONSTANT(F_DWORD, INFINITE);
Davin Pottse895de32019-02-23 22:08:16 -06001986 WINAPI_CONSTANT(F_HANDLE, INVALID_HANDLE_VALUE);
1987 WINAPI_CONSTANT(F_DWORD, MEM_COMMIT);
1988 WINAPI_CONSTANT(F_DWORD, MEM_FREE);
1989 WINAPI_CONSTANT(F_DWORD, MEM_IMAGE);
1990 WINAPI_CONSTANT(F_DWORD, MEM_MAPPED);
1991 WINAPI_CONSTANT(F_DWORD, MEM_PRIVATE);
1992 WINAPI_CONSTANT(F_DWORD, MEM_RESERVE);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02001993 WINAPI_CONSTANT(F_DWORD, NMPWAIT_WAIT_FOREVER);
1994 WINAPI_CONSTANT(F_DWORD, OPEN_EXISTING);
Davin Pottse895de32019-02-23 22:08:16 -06001995 WINAPI_CONSTANT(F_DWORD, PAGE_EXECUTE);
1996 WINAPI_CONSTANT(F_DWORD, PAGE_EXECUTE_READ);
1997 WINAPI_CONSTANT(F_DWORD, PAGE_EXECUTE_READWRITE);
1998 WINAPI_CONSTANT(F_DWORD, PAGE_EXECUTE_WRITECOPY);
1999 WINAPI_CONSTANT(F_DWORD, PAGE_GUARD);
2000 WINAPI_CONSTANT(F_DWORD, PAGE_NOACCESS);
2001 WINAPI_CONSTANT(F_DWORD, PAGE_NOCACHE);
2002 WINAPI_CONSTANT(F_DWORD, PAGE_READONLY);
2003 WINAPI_CONSTANT(F_DWORD, PAGE_READWRITE);
2004 WINAPI_CONSTANT(F_DWORD, PAGE_WRITECOMBINE);
2005 WINAPI_CONSTANT(F_DWORD, PAGE_WRITECOPY);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02002006 WINAPI_CONSTANT(F_DWORD, PIPE_ACCESS_DUPLEX);
2007 WINAPI_CONSTANT(F_DWORD, PIPE_ACCESS_INBOUND);
2008 WINAPI_CONSTANT(F_DWORD, PIPE_READMODE_MESSAGE);
2009 WINAPI_CONSTANT(F_DWORD, PIPE_TYPE_MESSAGE);
2010 WINAPI_CONSTANT(F_DWORD, PIPE_UNLIMITED_INSTANCES);
2011 WINAPI_CONSTANT(F_DWORD, PIPE_WAIT);
2012 WINAPI_CONSTANT(F_DWORD, PROCESS_ALL_ACCESS);
Thomas Moreauc09a9f52019-05-20 21:37:05 +02002013 WINAPI_CONSTANT(F_DWORD, SYNCHRONIZE);
Antoine Pitrou5438ed12012-04-24 22:56:57 +02002014 WINAPI_CONSTANT(F_DWORD, PROCESS_DUP_HANDLE);
Davin Pottse895de32019-02-23 22:08:16 -06002015 WINAPI_CONSTANT(F_DWORD, SEC_COMMIT);
2016 WINAPI_CONSTANT(F_DWORD, SEC_IMAGE);
2017 WINAPI_CONSTANT(F_DWORD, SEC_LARGE_PAGES);
2018 WINAPI_CONSTANT(F_DWORD, SEC_NOCACHE);
2019 WINAPI_CONSTANT(F_DWORD, SEC_RESERVE);
2020 WINAPI_CONSTANT(F_DWORD, SEC_WRITECOMBINE);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02002021 WINAPI_CONSTANT(F_DWORD, STARTF_USESHOWWINDOW);
2022 WINAPI_CONSTANT(F_DWORD, STARTF_USESTDHANDLES);
2023 WINAPI_CONSTANT(F_DWORD, STD_INPUT_HANDLE);
2024 WINAPI_CONSTANT(F_DWORD, STD_OUTPUT_HANDLE);
2025 WINAPI_CONSTANT(F_DWORD, STD_ERROR_HANDLE);
2026 WINAPI_CONSTANT(F_DWORD, STILL_ACTIVE);
2027 WINAPI_CONSTANT(F_DWORD, SW_HIDE);
2028 WINAPI_CONSTANT(F_DWORD, WAIT_OBJECT_0);
Victor Stinner373f0a92014-03-20 09:26:55 +01002029 WINAPI_CONSTANT(F_DWORD, WAIT_ABANDONED_0);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02002030 WINAPI_CONSTANT(F_DWORD, WAIT_TIMEOUT);
Victor Stinner91106cd2017-12-13 12:29:09 +01002031
Jamesb5d9e082017-11-08 14:18:59 +00002032 WINAPI_CONSTANT(F_DWORD, ABOVE_NORMAL_PRIORITY_CLASS);
2033 WINAPI_CONSTANT(F_DWORD, BELOW_NORMAL_PRIORITY_CLASS);
2034 WINAPI_CONSTANT(F_DWORD, HIGH_PRIORITY_CLASS);
2035 WINAPI_CONSTANT(F_DWORD, IDLE_PRIORITY_CLASS);
2036 WINAPI_CONSTANT(F_DWORD, NORMAL_PRIORITY_CLASS);
2037 WINAPI_CONSTANT(F_DWORD, REALTIME_PRIORITY_CLASS);
Victor Stinner91106cd2017-12-13 12:29:09 +01002038
Jamesb5d9e082017-11-08 14:18:59 +00002039 WINAPI_CONSTANT(F_DWORD, CREATE_NO_WINDOW);
2040 WINAPI_CONSTANT(F_DWORD, DETACHED_PROCESS);
2041 WINAPI_CONSTANT(F_DWORD, CREATE_DEFAULT_ERROR_MODE);
2042 WINAPI_CONSTANT(F_DWORD, CREATE_BREAKAWAY_FROM_JOB);
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02002043
Segev Finerb2a60832017-12-18 11:28:19 +02002044 WINAPI_CONSTANT(F_DWORD, FILE_TYPE_UNKNOWN);
2045 WINAPI_CONSTANT(F_DWORD, FILE_TYPE_DISK);
2046 WINAPI_CONSTANT(F_DWORD, FILE_TYPE_CHAR);
2047 WINAPI_CONSTANT(F_DWORD, FILE_TYPE_PIPE);
2048 WINAPI_CONSTANT(F_DWORD, FILE_TYPE_REMOTE);
2049
Antoine Pitrou23bba4c2012-04-18 20:51:15 +02002050 WINAPI_CONSTANT("i", NULL);
2051
2052 return m;
2053}