You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1585 lines
46 KiB

  1. /*
  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. /* Licensed to PSF under a Contributor Agreement. */
  34. /* See http://www.python.org/2.4/license for licensing details. */
  35. #include "Python.h"
  36. #include "structmember.h"
  37. #define WINDOWS_LEAN_AND_MEAN
  38. #include "windows.h"
  39. #include <crtdbg.h>
  40. #include "winreparse.h"
  41. #if defined(MS_WIN32) && !defined(MS_WIN64)
  42. #define HANDLE_TO_PYNUM(handle) \
  43. PyLong_FromUnsignedLong((unsigned long) handle)
  44. #define PYNUM_TO_HANDLE(obj) ((HANDLE)PyLong_AsUnsignedLong(obj))
  45. #define F_POINTER "k"
  46. #define T_POINTER T_ULONG
  47. #else
  48. #define HANDLE_TO_PYNUM(handle) \
  49. PyLong_FromUnsignedLongLong((unsigned long long) handle)
  50. #define PYNUM_TO_HANDLE(obj) ((HANDLE)PyLong_AsUnsignedLongLong(obj))
  51. #define F_POINTER "K"
  52. #define T_POINTER T_ULONGLONG
  53. #endif
  54. #define F_HANDLE F_POINTER
  55. #define F_DWORD "k"
  56. #define T_HANDLE T_POINTER
  57. #define DWORD_MAX 4294967295U
  58. /* Grab CancelIoEx dynamically from kernel32 */
  59. static int has_CancelIoEx = -1;
  60. static BOOL (CALLBACK *Py_CancelIoEx)(HANDLE, LPOVERLAPPED);
  61. static int
  62. check_CancelIoEx()
  63. {
  64. if (has_CancelIoEx == -1)
  65. {
  66. HINSTANCE hKernel32 = GetModuleHandle("KERNEL32");
  67. * (FARPROC *) &Py_CancelIoEx = GetProcAddress(hKernel32,
  68. "CancelIoEx");
  69. has_CancelIoEx = (Py_CancelIoEx != NULL);
  70. }
  71. return has_CancelIoEx;
  72. }
  73. /*
  74. * A Python object wrapping an OVERLAPPED structure and other useful data
  75. * for overlapped I/O
  76. */
  77. typedef struct {
  78. PyObject_HEAD
  79. OVERLAPPED overlapped;
  80. /* For convenience, we store the file handle too */
  81. HANDLE handle;
  82. /* Whether there's I/O in flight */
  83. int pending;
  84. /* Whether I/O completed successfully */
  85. int completed;
  86. /* Buffer used for reading (optional) */
  87. PyObject *read_buffer;
  88. /* Buffer used for writing (optional) */
  89. Py_buffer write_buffer;
  90. } OverlappedObject;
  91. static void
  92. overlapped_dealloc(OverlappedObject *self)
  93. {
  94. DWORD bytes;
  95. int err = GetLastError();
  96. if (self->pending) {
  97. if (check_CancelIoEx() &&
  98. Py_CancelIoEx(self->handle, &self->overlapped) &&
  99. GetOverlappedResult(self->handle, &self->overlapped, &bytes, TRUE))
  100. {
  101. /* The operation is no longer pending -- nothing to do. */
  102. }
  103. else if (_Py_Finalizing == NULL)
  104. {
  105. /* The operation is still pending -- give a warning. This
  106. will probably only happen on Windows XP. */
  107. PyErr_SetString(PyExc_RuntimeError,
  108. "I/O operations still in flight while destroying "
  109. "Overlapped object, the process may crash");
  110. PyErr_WriteUnraisable(NULL);
  111. }
  112. else
  113. {
  114. /* The operation is still pending, but the process is
  115. probably about to exit, so we need not worry too much
  116. about memory leaks. Leaking self prevents a potential
  117. crash. This can happen when a daemon thread is cleaned
  118. up at exit -- see #19565. We only expect to get here
  119. on Windows XP. */
  120. CloseHandle(self->overlapped.hEvent);
  121. SetLastError(err);
  122. return;
  123. }
  124. }
  125. CloseHandle(self->overlapped.hEvent);
  126. SetLastError(err);
  127. if (self->write_buffer.obj)
  128. PyBuffer_Release(&self->write_buffer);
  129. Py_CLEAR(self->read_buffer);
  130. PyObject_Del(self);
  131. }
  132. /*[clinic input]
  133. module _winapi
  134. class _winapi.Overlapped "OverlappedObject *" "&OverlappedType"
  135. [clinic start generated code]*/
  136. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=c13d3f5fd1dabb84]*/
  137. /*[python input]
  138. def create_converter(type_, format_unit):
  139. name = type_ + '_converter'
  140. # registered upon creation by CConverter's metaclass
  141. type(name, (CConverter,), {'type': type_, 'format_unit': format_unit})
  142. # format unit differs between platforms for these
  143. create_converter('HANDLE', '" F_HANDLE "')
  144. create_converter('HMODULE', '" F_HANDLE "')
  145. create_converter('LPSECURITY_ATTRIBUTES', '" F_POINTER "')
  146. create_converter('BOOL', 'i') # F_BOOL used previously (always 'i')
  147. create_converter('DWORD', 'k') # F_DWORD is always "k" (which is much shorter)
  148. create_converter('LPCTSTR', 's')
  149. create_converter('LPWSTR', 'u')
  150. create_converter('UINT', 'I') # F_UINT used previously (always 'I')
  151. class HANDLE_return_converter(CReturnConverter):
  152. type = 'HANDLE'
  153. def render(self, function, data):
  154. self.declare(data)
  155. self.err_occurred_if("_return_value == INVALID_HANDLE_VALUE", data)
  156. data.return_conversion.append(
  157. 'if (_return_value == NULL) {\n Py_RETURN_NONE;\n}\n')
  158. data.return_conversion.append(
  159. 'return_value = HANDLE_TO_PYNUM(_return_value);\n')
  160. class DWORD_return_converter(CReturnConverter):
  161. type = 'DWORD'
  162. def render(self, function, data):
  163. self.declare(data)
  164. self.err_occurred_if("_return_value == DWORD_MAX", data)
  165. data.return_conversion.append(
  166. 'return_value = Py_BuildValue("k", _return_value);\n')
  167. [python start generated code]*/
  168. /*[python end generated code: output=da39a3ee5e6b4b0d input=94819e72d2c6d558]*/
  169. #include "clinic/_winapi.c.h"
  170. /*[clinic input]
  171. _winapi.Overlapped.GetOverlappedResult
  172. wait: bool
  173. /
  174. [clinic start generated code]*/
  175. static PyObject *
  176. _winapi_Overlapped_GetOverlappedResult_impl(OverlappedObject *self, int wait)
  177. /*[clinic end generated code: output=bdd0c1ed6518cd03 input=194505ee8e0e3565]*/
  178. {
  179. BOOL res;
  180. DWORD transferred = 0;
  181. DWORD err;
  182. Py_BEGIN_ALLOW_THREADS
  183. res = GetOverlappedResult(self->handle, &self->overlapped, &transferred,
  184. wait != 0);
  185. Py_END_ALLOW_THREADS
  186. err = res ? ERROR_SUCCESS : GetLastError();
  187. switch (err) {
  188. case ERROR_SUCCESS:
  189. case ERROR_MORE_DATA:
  190. case ERROR_OPERATION_ABORTED:
  191. self->completed = 1;
  192. self->pending = 0;
  193. break;
  194. case ERROR_IO_INCOMPLETE:
  195. break;
  196. default:
  197. self->pending = 0;
  198. return PyErr_SetExcFromWindowsErr(PyExc_OSError, err);
  199. }
  200. if (self->completed && self->read_buffer != NULL) {
  201. assert(PyBytes_CheckExact(self->read_buffer));
  202. if (transferred != PyBytes_GET_SIZE(self->read_buffer) &&
  203. _PyBytes_Resize(&self->read_buffer, transferred))
  204. return NULL;
  205. }
  206. return Py_BuildValue("II", (unsigned) transferred, (unsigned) err);
  207. }
  208. /*[clinic input]
  209. _winapi.Overlapped.getbuffer
  210. [clinic start generated code]*/
  211. static PyObject *
  212. _winapi_Overlapped_getbuffer_impl(OverlappedObject *self)
  213. /*[clinic end generated code: output=95a3eceefae0f748 input=347fcfd56b4ceabd]*/
  214. {
  215. PyObject *res;
  216. if (!self->completed) {
  217. PyErr_SetString(PyExc_ValueError,
  218. "can't get read buffer before GetOverlappedResult() "
  219. "signals the operation completed");
  220. return NULL;
  221. }
  222. res = self->read_buffer ? self->read_buffer : Py_None;
  223. Py_INCREF(res);
  224. return res;
  225. }
  226. /*[clinic input]
  227. _winapi.Overlapped.cancel
  228. [clinic start generated code]*/
  229. static PyObject *
  230. _winapi_Overlapped_cancel_impl(OverlappedObject *self)
  231. /*[clinic end generated code: output=fcb9ab5df4ebdae5 input=cbf3da142290039f]*/
  232. {
  233. BOOL res = TRUE;
  234. if (self->pending) {
  235. Py_BEGIN_ALLOW_THREADS
  236. if (check_CancelIoEx())
  237. res = Py_CancelIoEx(self->handle, &self->overlapped);
  238. else
  239. res = CancelIo(self->handle);
  240. Py_END_ALLOW_THREADS
  241. }
  242. /* CancelIoEx returns ERROR_NOT_FOUND if the I/O completed in-between */
  243. if (!res && GetLastError() != ERROR_NOT_FOUND)
  244. return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
  245. self->pending = 0;
  246. Py_RETURN_NONE;
  247. }
  248. static PyMethodDef overlapped_methods[] = {
  249. _WINAPI_OVERLAPPED_GETOVERLAPPEDRESULT_METHODDEF
  250. _WINAPI_OVERLAPPED_GETBUFFER_METHODDEF
  251. _WINAPI_OVERLAPPED_CANCEL_METHODDEF
  252. {NULL}
  253. };
  254. static PyMemberDef overlapped_members[] = {
  255. {"event", T_HANDLE,
  256. offsetof(OverlappedObject, overlapped) + offsetof(OVERLAPPED, hEvent),
  257. READONLY, "overlapped event handle"},
  258. {NULL}
  259. };
  260. PyTypeObject OverlappedType = {
  261. PyVarObject_HEAD_INIT(NULL, 0)
  262. /* tp_name */ "_winapi.Overlapped",
  263. /* tp_basicsize */ sizeof(OverlappedObject),
  264. /* tp_itemsize */ 0,
  265. /* tp_dealloc */ (destructor) overlapped_dealloc,
  266. /* tp_print */ 0,
  267. /* tp_getattr */ 0,
  268. /* tp_setattr */ 0,
  269. /* tp_reserved */ 0,
  270. /* tp_repr */ 0,
  271. /* tp_as_number */ 0,
  272. /* tp_as_sequence */ 0,
  273. /* tp_as_mapping */ 0,
  274. /* tp_hash */ 0,
  275. /* tp_call */ 0,
  276. /* tp_str */ 0,
  277. /* tp_getattro */ 0,
  278. /* tp_setattro */ 0,
  279. /* tp_as_buffer */ 0,
  280. /* tp_flags */ Py_TPFLAGS_DEFAULT,
  281. /* tp_doc */ "OVERLAPPED structure wrapper",
  282. /* tp_traverse */ 0,
  283. /* tp_clear */ 0,
  284. /* tp_richcompare */ 0,
  285. /* tp_weaklistoffset */ 0,
  286. /* tp_iter */ 0,
  287. /* tp_iternext */ 0,
  288. /* tp_methods */ overlapped_methods,
  289. /* tp_members */ overlapped_members,
  290. /* tp_getset */ 0,
  291. /* tp_base */ 0,
  292. /* tp_dict */ 0,
  293. /* tp_descr_get */ 0,
  294. /* tp_descr_set */ 0,
  295. /* tp_dictoffset */ 0,
  296. /* tp_init */ 0,
  297. /* tp_alloc */ 0,
  298. /* tp_new */ 0,
  299. };
  300. static OverlappedObject *
  301. new_overlapped(HANDLE handle)
  302. {
  303. OverlappedObject *self;
  304. self = PyObject_New(OverlappedObject, &OverlappedType);
  305. if (!self)
  306. return NULL;
  307. self->handle = handle;
  308. self->read_buffer = NULL;
  309. self->pending = 0;
  310. self->completed = 0;
  311. memset(&self->overlapped, 0, sizeof(OVERLAPPED));
  312. memset(&self->write_buffer, 0, sizeof(Py_buffer));
  313. /* Manual reset, initially non-signalled */
  314. self->overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
  315. return self;
  316. }
  317. /* -------------------------------------------------------------------- */
  318. /* windows API functions */
  319. /*[clinic input]
  320. _winapi.CloseHandle
  321. handle: HANDLE
  322. /
  323. Close handle.
  324. [clinic start generated code]*/
  325. static PyObject *
  326. _winapi_CloseHandle_impl(PyObject *module, HANDLE handle)
  327. /*[clinic end generated code: output=7ad37345f07bd782 input=7f0e4ac36e0352b8]*/
  328. {
  329. BOOL success;
  330. Py_BEGIN_ALLOW_THREADS
  331. success = CloseHandle(handle);
  332. Py_END_ALLOW_THREADS
  333. if (!success)
  334. return PyErr_SetFromWindowsErr(0);
  335. Py_RETURN_NONE;
  336. }
  337. /*[clinic input]
  338. _winapi.ConnectNamedPipe
  339. handle: HANDLE
  340. overlapped as use_overlapped: bool(accept={int}) = False
  341. [clinic start generated code]*/
  342. static PyObject *
  343. _winapi_ConnectNamedPipe_impl(PyObject *module, HANDLE handle,
  344. int use_overlapped)
  345. /*[clinic end generated code: output=335a0e7086800671 input=34f937c1c86e5e68]*/
  346. {
  347. BOOL success;
  348. OverlappedObject *overlapped = NULL;
  349. if (use_overlapped) {
  350. overlapped = new_overlapped(handle);
  351. if (!overlapped)
  352. return NULL;
  353. }
  354. Py_BEGIN_ALLOW_THREADS
  355. success = ConnectNamedPipe(handle,
  356. overlapped ? &overlapped->overlapped : NULL);
  357. Py_END_ALLOW_THREADS
  358. if (overlapped) {
  359. int err = GetLastError();
  360. /* Overlapped ConnectNamedPipe never returns a success code */
  361. assert(success == 0);
  362. if (err == ERROR_IO_PENDING)
  363. overlapped->pending = 1;
  364. else if (err == ERROR_PIPE_CONNECTED)
  365. SetEvent(overlapped->overlapped.hEvent);
  366. else {
  367. Py_DECREF(overlapped);
  368. return PyErr_SetFromWindowsErr(err);
  369. }
  370. return (PyObject *) overlapped;
  371. }
  372. if (!success)
  373. return PyErr_SetFromWindowsErr(0);
  374. Py_RETURN_NONE;
  375. }
  376. /*[clinic input]
  377. _winapi.CreateFile -> HANDLE
  378. file_name: LPCTSTR
  379. desired_access: DWORD
  380. share_mode: DWORD
  381. security_attributes: LPSECURITY_ATTRIBUTES
  382. creation_disposition: DWORD
  383. flags_and_attributes: DWORD
  384. template_file: HANDLE
  385. /
  386. [clinic start generated code]*/
  387. static HANDLE
  388. _winapi_CreateFile_impl(PyObject *module, LPCTSTR file_name,
  389. DWORD desired_access, DWORD share_mode,
  390. LPSECURITY_ATTRIBUTES security_attributes,
  391. DWORD creation_disposition,
  392. DWORD flags_and_attributes, HANDLE template_file)
  393. /*[clinic end generated code: output=417ddcebfc5a3d53 input=6423c3e40372dbd5]*/
  394. {
  395. HANDLE handle;
  396. Py_BEGIN_ALLOW_THREADS
  397. handle = CreateFile(file_name, desired_access,
  398. share_mode, security_attributes,
  399. creation_disposition,
  400. flags_and_attributes, template_file);
  401. Py_END_ALLOW_THREADS
  402. if (handle == INVALID_HANDLE_VALUE)
  403. PyErr_SetFromWindowsErr(0);
  404. return handle;
  405. }
  406. /*[clinic input]
  407. _winapi.CreateJunction
  408. src_path: LPWSTR
  409. dst_path: LPWSTR
  410. /
  411. [clinic start generated code]*/
  412. static PyObject *
  413. _winapi_CreateJunction_impl(PyObject *module, LPWSTR src_path,
  414. LPWSTR dst_path)
  415. /*[clinic end generated code: output=66b7eb746e1dfa25 input=8cd1f9964b6e3d36]*/
  416. {
  417. /* Privilege adjustment */
  418. HANDLE token = NULL;
  419. TOKEN_PRIVILEGES tp;
  420. /* Reparse data buffer */
  421. const USHORT prefix_len = 4;
  422. USHORT print_len = 0;
  423. USHORT rdb_size = 0;
  424. _Py_PREPARSE_DATA_BUFFER rdb = NULL;
  425. /* Junction point creation */
  426. HANDLE junction = NULL;
  427. DWORD ret = 0;
  428. if (src_path == NULL || dst_path == NULL)
  429. return PyErr_SetFromWindowsErr(ERROR_INVALID_PARAMETER);
  430. if (wcsncmp(src_path, L"\\??\\", prefix_len) == 0)
  431. return PyErr_SetFromWindowsErr(ERROR_INVALID_PARAMETER);
  432. /* Adjust privileges to allow rewriting directory entry as a
  433. junction point. */
  434. if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &token))
  435. goto cleanup;
  436. if (!LookupPrivilegeValue(NULL, SE_RESTORE_NAME, &tp.Privileges[0].Luid))
  437. goto cleanup;
  438. tp.PrivilegeCount = 1;
  439. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  440. if (!AdjustTokenPrivileges(token, FALSE, &tp, sizeof(TOKEN_PRIVILEGES),
  441. NULL, NULL))
  442. goto cleanup;
  443. if (GetFileAttributesW(src_path) == INVALID_FILE_ATTRIBUTES)
  444. goto cleanup;
  445. /* Store the absolute link target path length in print_len. */
  446. print_len = (USHORT)GetFullPathNameW(src_path, 0, NULL, NULL);
  447. if (print_len == 0)
  448. goto cleanup;
  449. /* NUL terminator should not be part of print_len. */
  450. --print_len;
  451. /* REPARSE_DATA_BUFFER usage is heavily under-documented, especially for
  452. junction points. Here's what I've learned along the way:
  453. - A junction point has two components: a print name and a substitute
  454. name. They both describe the link target, but the substitute name is
  455. the physical target and the print name is shown in directory listings.
  456. - The print name must be a native name, prefixed with "\??\".
  457. - Both names are stored after each other in the same buffer (the
  458. PathBuffer) and both must be NUL-terminated.
  459. - There are four members defining their respective offset and length
  460. inside PathBuffer: SubstituteNameOffset, SubstituteNameLength,
  461. PrintNameOffset and PrintNameLength.
  462. - The total size we need to allocate for the REPARSE_DATA_BUFFER, thus,
  463. is the sum of:
  464. - the fixed header size (REPARSE_DATA_BUFFER_HEADER_SIZE)
  465. - the size of the MountPointReparseBuffer member without the PathBuffer
  466. - the size of the prefix ("\??\") in bytes
  467. - the size of the print name in bytes
  468. - the size of the substitute name in bytes
  469. - the size of two NUL terminators in bytes */
  470. rdb_size = _Py_REPARSE_DATA_BUFFER_HEADER_SIZE +
  471. sizeof(rdb->MountPointReparseBuffer) -
  472. sizeof(rdb->MountPointReparseBuffer.PathBuffer) +
  473. /* Two +1's for NUL terminators. */
  474. (prefix_len + print_len + 1 + print_len + 1) * sizeof(WCHAR);
  475. rdb = (_Py_PREPARSE_DATA_BUFFER)PyMem_RawMalloc(rdb_size);
  476. if (rdb == NULL)
  477. goto cleanup;
  478. memset(rdb, 0, rdb_size);
  479. rdb->ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
  480. rdb->ReparseDataLength = rdb_size - _Py_REPARSE_DATA_BUFFER_HEADER_SIZE;
  481. rdb->MountPointReparseBuffer.SubstituteNameOffset = 0;
  482. rdb->MountPointReparseBuffer.SubstituteNameLength =
  483. (prefix_len + print_len) * sizeof(WCHAR);
  484. rdb->MountPointReparseBuffer.PrintNameOffset =
  485. rdb->MountPointReparseBuffer.SubstituteNameLength + sizeof(WCHAR);
  486. rdb->MountPointReparseBuffer.PrintNameLength = print_len * sizeof(WCHAR);
  487. /* Store the full native path of link target at the substitute name
  488. offset (0). */
  489. wcscpy(rdb->MountPointReparseBuffer.PathBuffer, L"\\??\\");
  490. if (GetFullPathNameW(src_path, print_len + 1,
  491. rdb->MountPointReparseBuffer.PathBuffer + prefix_len,
  492. NULL) == 0)
  493. goto cleanup;
  494. /* Copy everything but the native prefix to the print name offset. */
  495. wcscpy(rdb->MountPointReparseBuffer.PathBuffer +
  496. prefix_len + print_len + 1,
  497. rdb->MountPointReparseBuffer.PathBuffer + prefix_len);
  498. /* Create a directory for the junction point. */
  499. if (!CreateDirectoryW(dst_path, NULL))
  500. goto cleanup;
  501. junction = CreateFileW(dst_path, GENERIC_READ | GENERIC_WRITE, 0, NULL,
  502. OPEN_EXISTING,
  503. FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, NULL);
  504. if (junction == INVALID_HANDLE_VALUE)
  505. goto cleanup;
  506. /* Make the directory entry a junction point. */
  507. if (!DeviceIoControl(junction, FSCTL_SET_REPARSE_POINT, rdb, rdb_size,
  508. NULL, 0, &ret, NULL))
  509. goto cleanup;
  510. cleanup:
  511. ret = GetLastError();
  512. CloseHandle(token);
  513. CloseHandle(junction);
  514. PyMem_RawFree(rdb);
  515. if (ret != 0)
  516. return PyErr_SetFromWindowsErr(ret);
  517. Py_RETURN_NONE;
  518. }
  519. /*[clinic input]
  520. _winapi.CreateNamedPipe -> HANDLE
  521. name: LPCTSTR
  522. open_mode: DWORD
  523. pipe_mode: DWORD
  524. max_instances: DWORD
  525. out_buffer_size: DWORD
  526. in_buffer_size: DWORD
  527. default_timeout: DWORD
  528. security_attributes: LPSECURITY_ATTRIBUTES
  529. /
  530. [clinic start generated code]*/
  531. static HANDLE
  532. _winapi_CreateNamedPipe_impl(PyObject *module, LPCTSTR name, DWORD open_mode,
  533. DWORD pipe_mode, DWORD max_instances,
  534. DWORD out_buffer_size, DWORD in_buffer_size,
  535. DWORD default_timeout,
  536. LPSECURITY_ATTRIBUTES security_attributes)
  537. /*[clinic end generated code: output=80f8c07346a94fbc input=5a73530b84d8bc37]*/
  538. {
  539. HANDLE handle;
  540. Py_BEGIN_ALLOW_THREADS
  541. handle = CreateNamedPipe(name, open_mode, pipe_mode,
  542. max_instances, out_buffer_size,
  543. in_buffer_size, default_timeout,
  544. security_attributes);
  545. Py_END_ALLOW_THREADS
  546. if (handle == INVALID_HANDLE_VALUE)
  547. PyErr_SetFromWindowsErr(0);
  548. return handle;
  549. }
  550. /*[clinic input]
  551. _winapi.CreatePipe
  552. pipe_attrs: object
  553. Ignored internally, can be None.
  554. size: DWORD
  555. /
  556. Create an anonymous pipe.
  557. Returns a 2-tuple of handles, to the read and write ends of the pipe.
  558. [clinic start generated code]*/
  559. static PyObject *
  560. _winapi_CreatePipe_impl(PyObject *module, PyObject *pipe_attrs, DWORD size)
  561. /*[clinic end generated code: output=1c4411d8699f0925 input=c4f2cfa56ef68d90]*/
  562. {
  563. HANDLE read_pipe;
  564. HANDLE write_pipe;
  565. BOOL result;
  566. Py_BEGIN_ALLOW_THREADS
  567. result = CreatePipe(&read_pipe, &write_pipe, NULL, size);
  568. Py_END_ALLOW_THREADS
  569. if (! result)
  570. return PyErr_SetFromWindowsErr(GetLastError());
  571. return Py_BuildValue(
  572. "NN", HANDLE_TO_PYNUM(read_pipe), HANDLE_TO_PYNUM(write_pipe));
  573. }
  574. /* helpers for createprocess */
  575. static unsigned long
  576. getulong(PyObject* obj, const char* name)
  577. {
  578. PyObject* value;
  579. unsigned long ret;
  580. value = PyObject_GetAttrString(obj, name);
  581. if (! value) {
  582. PyErr_Clear(); /* FIXME: propagate error? */
  583. return 0;
  584. }
  585. ret = PyLong_AsUnsignedLong(value);
  586. Py_DECREF(value);
  587. return ret;
  588. }
  589. static HANDLE
  590. gethandle(PyObject* obj, const char* name)
  591. {
  592. PyObject* value;
  593. HANDLE ret;
  594. value = PyObject_GetAttrString(obj, name);
  595. if (! value) {
  596. PyErr_Clear(); /* FIXME: propagate error? */
  597. return NULL;
  598. }
  599. if (value == Py_None)
  600. ret = NULL;
  601. else
  602. ret = PYNUM_TO_HANDLE(value);
  603. Py_DECREF(value);
  604. return ret;
  605. }
  606. static PyObject*
  607. getenvironment(PyObject* environment)
  608. {
  609. Py_ssize_t i, envsize, totalsize;
  610. Py_UCS4 *buffer = NULL, *p, *end;
  611. PyObject *keys, *values, *res;
  612. /* convert environment dictionary to windows environment string */
  613. if (! PyMapping_Check(environment)) {
  614. PyErr_SetString(
  615. PyExc_TypeError, "environment must be dictionary or None");
  616. return NULL;
  617. }
  618. keys = PyMapping_Keys(environment);
  619. values = PyMapping_Values(environment);
  620. if (!keys || !values)
  621. goto error;
  622. envsize = PySequence_Fast_GET_SIZE(keys);
  623. if (PySequence_Fast_GET_SIZE(values) != envsize) {
  624. PyErr_SetString(PyExc_RuntimeError,
  625. "environment changed size during iteration");
  626. goto error;
  627. }
  628. totalsize = 1; /* trailing null character */
  629. for (i = 0; i < envsize; i++) {
  630. PyObject* key = PySequence_Fast_GET_ITEM(keys, i);
  631. PyObject* value = PySequence_Fast_GET_ITEM(values, i);
  632. if (! PyUnicode_Check(key) || ! PyUnicode_Check(value)) {
  633. PyErr_SetString(PyExc_TypeError,
  634. "environment can only contain strings");
  635. goto error;
  636. }
  637. if (totalsize > PY_SSIZE_T_MAX - PyUnicode_GET_LENGTH(key) - 1) {
  638. PyErr_SetString(PyExc_OverflowError, "environment too long");
  639. goto error;
  640. }
  641. totalsize += PyUnicode_GET_LENGTH(key) + 1; /* +1 for '=' */
  642. if (totalsize > PY_SSIZE_T_MAX - PyUnicode_GET_LENGTH(value) - 1) {
  643. PyErr_SetString(PyExc_OverflowError, "environment too long");
  644. goto error;
  645. }
  646. totalsize += PyUnicode_GET_LENGTH(value) + 1; /* +1 for '\0' */
  647. }
  648. buffer = PyMem_NEW(Py_UCS4, totalsize);
  649. if (! buffer) {
  650. PyErr_NoMemory();
  651. goto error;
  652. }
  653. p = buffer;
  654. end = buffer + totalsize;
  655. for (i = 0; i < envsize; i++) {
  656. PyObject* key = PySequence_Fast_GET_ITEM(keys, i);
  657. PyObject* value = PySequence_Fast_GET_ITEM(values, i);
  658. if (!PyUnicode_AsUCS4(key, p, end - p, 0))
  659. goto error;
  660. p += PyUnicode_GET_LENGTH(key);
  661. *p++ = '=';
  662. if (!PyUnicode_AsUCS4(value, p, end - p, 0))
  663. goto error;
  664. p += PyUnicode_GET_LENGTH(value);
  665. *p++ = '\0';
  666. }
  667. /* add trailing null byte */
  668. *p++ = '\0';
  669. assert(p == end);
  670. Py_XDECREF(keys);
  671. Py_XDECREF(values);
  672. res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, buffer, p - buffer);
  673. PyMem_Free(buffer);
  674. return res;
  675. error:
  676. PyMem_Free(buffer);
  677. Py_XDECREF(keys);
  678. Py_XDECREF(values);
  679. return NULL;
  680. }
  681. /*[clinic input]
  682. _winapi.CreateProcess
  683. application_name: Py_UNICODE(accept={str, NoneType})
  684. command_line: Py_UNICODE(accept={str, NoneType})
  685. proc_attrs: object
  686. Ignored internally, can be None.
  687. thread_attrs: object
  688. Ignored internally, can be None.
  689. inherit_handles: BOOL
  690. creation_flags: DWORD
  691. env_mapping: object
  692. current_directory: Py_UNICODE(accept={str, NoneType})
  693. startup_info: object
  694. /
  695. Create a new process and its primary thread.
  696. The return value is a tuple of the process handle, thread handle,
  697. process ID, and thread ID.
  698. [clinic start generated code]*/
  699. static PyObject *
  700. _winapi_CreateProcess_impl(PyObject *module, Py_UNICODE *application_name,
  701. Py_UNICODE *command_line, PyObject *proc_attrs,
  702. PyObject *thread_attrs, BOOL inherit_handles,
  703. DWORD creation_flags, PyObject *env_mapping,
  704. Py_UNICODE *current_directory,
  705. PyObject *startup_info)
  706. /*[clinic end generated code: output=4652a33aff4b0ae1 input=4a43b05038d639bb]*/
  707. {
  708. BOOL result;
  709. PROCESS_INFORMATION pi;
  710. STARTUPINFOW si;
  711. PyObject* environment;
  712. wchar_t *wenvironment;
  713. ZeroMemory(&si, sizeof(si));
  714. si.cb = sizeof(si);
  715. /* note: we only support a small subset of all SI attributes */
  716. si.dwFlags = getulong(startup_info, "dwFlags");
  717. si.wShowWindow = (WORD)getulong(startup_info, "wShowWindow");
  718. si.hStdInput = gethandle(startup_info, "hStdInput");
  719. si.hStdOutput = gethandle(startup_info, "hStdOutput");
  720. si.hStdError = gethandle(startup_info, "hStdError");
  721. if (PyErr_Occurred())
  722. return NULL;
  723. if (env_mapping != Py_None) {
  724. environment = getenvironment(env_mapping);
  725. if (! environment)
  726. return NULL;
  727. wenvironment = PyUnicode_AsUnicode(environment);
  728. if (wenvironment == NULL)
  729. {
  730. Py_XDECREF(environment);
  731. return NULL;
  732. }
  733. }
  734. else {
  735. environment = NULL;
  736. wenvironment = NULL;
  737. }
  738. Py_BEGIN_ALLOW_THREADS
  739. result = CreateProcessW(application_name,
  740. command_line,
  741. NULL,
  742. NULL,
  743. inherit_handles,
  744. creation_flags | CREATE_UNICODE_ENVIRONMENT,
  745. wenvironment,
  746. current_directory,
  747. &si,
  748. &pi);
  749. Py_END_ALLOW_THREADS
  750. Py_XDECREF(environment);
  751. if (! result)
  752. return PyErr_SetFromWindowsErr(GetLastError());
  753. return Py_BuildValue("NNkk",
  754. HANDLE_TO_PYNUM(pi.hProcess),
  755. HANDLE_TO_PYNUM(pi.hThread),
  756. pi.dwProcessId,
  757. pi.dwThreadId);
  758. }
  759. /*[clinic input]
  760. _winapi.DuplicateHandle -> HANDLE
  761. source_process_handle: HANDLE
  762. source_handle: HANDLE
  763. target_process_handle: HANDLE
  764. desired_access: DWORD
  765. inherit_handle: BOOL
  766. options: DWORD = 0
  767. /
  768. Return a duplicate handle object.
  769. The duplicate handle refers to the same object as the original
  770. handle. Therefore, any changes to the object are reflected
  771. through both handles.
  772. [clinic start generated code]*/
  773. static HANDLE
  774. _winapi_DuplicateHandle_impl(PyObject *module, HANDLE source_process_handle,
  775. HANDLE source_handle,
  776. HANDLE target_process_handle,
  777. DWORD desired_access, BOOL inherit_handle,
  778. DWORD options)
  779. /*[clinic end generated code: output=ad9711397b5dcd4e input=b933e3f2356a8c12]*/
  780. {
  781. HANDLE target_handle;
  782. BOOL result;
  783. Py_BEGIN_ALLOW_THREADS
  784. result = DuplicateHandle(
  785. source_process_handle,
  786. source_handle,
  787. target_process_handle,
  788. &target_handle,
  789. desired_access,
  790. inherit_handle,
  791. options
  792. );
  793. Py_END_ALLOW_THREADS
  794. if (! result) {
  795. PyErr_SetFromWindowsErr(GetLastError());
  796. return INVALID_HANDLE_VALUE;
  797. }
  798. return target_handle;
  799. }
  800. /*[clinic input]
  801. _winapi.ExitProcess
  802. ExitCode: UINT
  803. /
  804. [clinic start generated code]*/
  805. static PyObject *
  806. _winapi_ExitProcess_impl(PyObject *module, UINT ExitCode)
  807. /*[clinic end generated code: output=a387deb651175301 input=4f05466a9406c558]*/
  808. {
  809. #if defined(Py_DEBUG)
  810. SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOALIGNMENTFAULTEXCEPT|
  811. SEM_NOGPFAULTERRORBOX|SEM_NOOPENFILEERRORBOX);
  812. _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
  813. #endif
  814. ExitProcess(ExitCode);
  815. return NULL;
  816. }
  817. /*[clinic input]
  818. _winapi.GetCurrentProcess -> HANDLE
  819. Return a handle object for the current process.
  820. [clinic start generated code]*/
  821. static HANDLE
  822. _winapi_GetCurrentProcess_impl(PyObject *module)
  823. /*[clinic end generated code: output=ddeb4dd2ffadf344 input=b213403fd4b96b41]*/
  824. {
  825. return GetCurrentProcess();
  826. }
  827. /*[clinic input]
  828. _winapi.GetExitCodeProcess -> DWORD
  829. process: HANDLE
  830. /
  831. Return the termination status of the specified process.
  832. [clinic start generated code]*/
  833. static DWORD
  834. _winapi_GetExitCodeProcess_impl(PyObject *module, HANDLE process)
  835. /*[clinic end generated code: output=b4620bdf2bccf36b input=61b6bfc7dc2ee374]*/
  836. {
  837. DWORD exit_code;
  838. BOOL result;
  839. result = GetExitCodeProcess(process, &exit_code);
  840. if (! result) {
  841. PyErr_SetFromWindowsErr(GetLastError());
  842. exit_code = DWORD_MAX;
  843. }
  844. return exit_code;
  845. }
  846. /*[clinic input]
  847. _winapi.GetLastError -> DWORD
  848. [clinic start generated code]*/
  849. static DWORD
  850. _winapi_GetLastError_impl(PyObject *module)
  851. /*[clinic end generated code: output=8585b827cb1a92c5 input=62d47fb9bce038ba]*/
  852. {
  853. return GetLastError();
  854. }
  855. /*[clinic input]
  856. _winapi.GetModuleFileName
  857. module_handle: HMODULE
  858. /
  859. Return the fully-qualified path for the file that contains module.
  860. The module must have been loaded by the current process.
  861. The module parameter should be a handle to the loaded module
  862. whose path is being requested. If this parameter is 0,
  863. GetModuleFileName retrieves the path of the executable file
  864. of the current process.
  865. [clinic start generated code]*/
  866. static PyObject *
  867. _winapi_GetModuleFileName_impl(PyObject *module, HMODULE module_handle)
  868. /*[clinic end generated code: output=85b4b728c5160306 input=6d66ff7deca5d11f]*/
  869. {
  870. BOOL result;
  871. WCHAR filename[MAX_PATH];
  872. result = GetModuleFileNameW(module_handle, filename, MAX_PATH);
  873. filename[MAX_PATH-1] = '\0';
  874. if (! result)
  875. return PyErr_SetFromWindowsErr(GetLastError());
  876. return PyUnicode_FromWideChar(filename, wcslen(filename));
  877. }
  878. /*[clinic input]
  879. _winapi.GetStdHandle -> HANDLE
  880. std_handle: DWORD
  881. One of STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, or STD_ERROR_HANDLE.
  882. /
  883. Return a handle to the specified standard device.
  884. The integer associated with the handle object is returned.
  885. [clinic start generated code]*/
  886. static HANDLE
  887. _winapi_GetStdHandle_impl(PyObject *module, DWORD std_handle)
  888. /*[clinic end generated code: output=0e613001e73ab614 input=07016b06a2fc8826]*/
  889. {
  890. HANDLE handle;
  891. Py_BEGIN_ALLOW_THREADS
  892. handle = GetStdHandle(std_handle);
  893. Py_END_ALLOW_THREADS
  894. if (handle == INVALID_HANDLE_VALUE)
  895. PyErr_SetFromWindowsErr(GetLastError());
  896. return handle;
  897. }
  898. /*[clinic input]
  899. _winapi.GetVersion -> long
  900. Return the version number of the current operating system.
  901. [clinic start generated code]*/
  902. static long
  903. _winapi_GetVersion_impl(PyObject *module)
  904. /*[clinic end generated code: output=e41f0db5a3b82682 input=e21dff8d0baeded2]*/
  905. /* Disable deprecation warnings about GetVersionEx as the result is
  906. being passed straight through to the caller, who is responsible for
  907. using it correctly. */
  908. #pragma warning(push)
  909. #pragma warning(disable:4996)
  910. {
  911. return GetVersion();
  912. }
  913. #pragma warning(pop)
  914. /*[clinic input]
  915. _winapi.OpenProcess -> HANDLE
  916. desired_access: DWORD
  917. inherit_handle: BOOL
  918. process_id: DWORD
  919. /
  920. [clinic start generated code]*/
  921. static HANDLE
  922. _winapi_OpenProcess_impl(PyObject *module, DWORD desired_access,
  923. BOOL inherit_handle, DWORD process_id)
  924. /*[clinic end generated code: output=b42b6b81ea5a0fc3 input=ec98c4cf4ea2ec36]*/
  925. {
  926. HANDLE handle;
  927. handle = OpenProcess(desired_access, inherit_handle, process_id);
  928. if (handle == NULL) {
  929. PyErr_SetFromWindowsErr(0);
  930. handle = INVALID_HANDLE_VALUE;
  931. }
  932. return handle;
  933. }
  934. /*[clinic input]
  935. _winapi.PeekNamedPipe
  936. handle: HANDLE
  937. size: int = 0
  938. /
  939. [clinic start generated code]*/
  940. static PyObject *
  941. _winapi_PeekNamedPipe_impl(PyObject *module, HANDLE handle, int size)
  942. /*[clinic end generated code: output=d0c3e29e49d323dd input=c7aa53bfbce69d70]*/
  943. {
  944. PyObject *buf = NULL;
  945. DWORD nread, navail, nleft;
  946. BOOL ret;
  947. if (size < 0) {
  948. PyErr_SetString(PyExc_ValueError, "negative size");
  949. return NULL;
  950. }
  951. if (size) {
  952. buf = PyBytes_FromStringAndSize(NULL, size);
  953. if (!buf)
  954. return NULL;
  955. Py_BEGIN_ALLOW_THREADS
  956. ret = PeekNamedPipe(handle, PyBytes_AS_STRING(buf), size, &nread,
  957. &navail, &nleft);
  958. Py_END_ALLOW_THREADS
  959. if (!ret) {
  960. Py_DECREF(buf);
  961. return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
  962. }
  963. if (_PyBytes_Resize(&buf, nread))
  964. return NULL;
  965. return Py_BuildValue("Nii", buf, navail, nleft);
  966. }
  967. else {
  968. Py_BEGIN_ALLOW_THREADS
  969. ret = PeekNamedPipe(handle, NULL, 0, NULL, &navail, &nleft);
  970. Py_END_ALLOW_THREADS
  971. if (!ret) {
  972. return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
  973. }
  974. return Py_BuildValue("ii", navail, nleft);
  975. }
  976. }
  977. /*[clinic input]
  978. _winapi.ReadFile
  979. handle: HANDLE
  980. size: int
  981. overlapped as use_overlapped: bool(accept={int}) = False
  982. [clinic start generated code]*/
  983. static PyObject *
  984. _winapi_ReadFile_impl(PyObject *module, HANDLE handle, int size,
  985. int use_overlapped)
  986. /*[clinic end generated code: output=492029ca98161d84 input=3f0fde92f74de59a]*/
  987. {
  988. DWORD nread;
  989. PyObject *buf;
  990. BOOL ret;
  991. DWORD err;
  992. OverlappedObject *overlapped = NULL;
  993. buf = PyBytes_FromStringAndSize(NULL, size);
  994. if (!buf)
  995. return NULL;
  996. if (use_overlapped) {
  997. overlapped = new_overlapped(handle);
  998. if (!overlapped) {
  999. Py_DECREF(buf);
  1000. return NULL;
  1001. }
  1002. /* Steals reference to buf */
  1003. overlapped->read_buffer = buf;
  1004. }
  1005. Py_BEGIN_ALLOW_THREADS
  1006. ret = ReadFile(handle, PyBytes_AS_STRING(buf), size, &nread,
  1007. overlapped ? &overlapped->overlapped : NULL);
  1008. Py_END_ALLOW_THREADS
  1009. err = ret ? 0 : GetLastError();
  1010. if (overlapped) {
  1011. if (!ret) {
  1012. if (err == ERROR_IO_PENDING)
  1013. overlapped->pending = 1;
  1014. else if (err != ERROR_MORE_DATA) {
  1015. Py_DECREF(overlapped);
  1016. return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
  1017. }
  1018. }
  1019. return Py_BuildValue("NI", (PyObject *) overlapped, err);
  1020. }
  1021. if (!ret && err != ERROR_MORE_DATA) {
  1022. Py_DECREF(buf);
  1023. return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
  1024. }
  1025. if (_PyBytes_Resize(&buf, nread))
  1026. return NULL;
  1027. return Py_BuildValue("NI", buf, err);
  1028. }
  1029. /*[clinic input]
  1030. _winapi.SetNamedPipeHandleState
  1031. named_pipe: HANDLE
  1032. mode: object
  1033. max_collection_count: object
  1034. collect_data_timeout: object
  1035. /
  1036. [clinic start generated code]*/
  1037. static PyObject *
  1038. _winapi_SetNamedPipeHandleState_impl(PyObject *module, HANDLE named_pipe,
  1039. PyObject *mode,
  1040. PyObject *max_collection_count,
  1041. PyObject *collect_data_timeout)
  1042. /*[clinic end generated code: output=f2129d222cbfa095 input=9142d72163d0faa6]*/
  1043. {
  1044. PyObject *oArgs[3] = {mode, max_collection_count, collect_data_timeout};
  1045. DWORD dwArgs[3], *pArgs[3] = {NULL, NULL, NULL};
  1046. int i;
  1047. PyErr_Clear();
  1048. for (i = 0 ; i < 3 ; i++) {
  1049. if (oArgs[i] != Py_None) {
  1050. dwArgs[i] = PyLong_AsUnsignedLongMask(oArgs[i]);
  1051. if (PyErr_Occurred())
  1052. return NULL;
  1053. pArgs[i] = &dwArgs[i];
  1054. }
  1055. }
  1056. if (!SetNamedPipeHandleState(named_pipe, pArgs[0], pArgs[1], pArgs[2]))
  1057. return PyErr_SetFromWindowsErr(0);
  1058. Py_RETURN_NONE;
  1059. }
  1060. /*[clinic input]
  1061. _winapi.TerminateProcess
  1062. handle: HANDLE
  1063. exit_code: UINT
  1064. /
  1065. Terminate the specified process and all of its threads.
  1066. [clinic start generated code]*/
  1067. static PyObject *
  1068. _winapi_TerminateProcess_impl(PyObject *module, HANDLE handle,
  1069. UINT exit_code)
  1070. /*[clinic end generated code: output=f4e99ac3f0b1f34a input=d6bc0aa1ee3bb4df]*/
  1071. {
  1072. BOOL result;
  1073. result = TerminateProcess(handle, exit_code);
  1074. if (! result)
  1075. return PyErr_SetFromWindowsErr(GetLastError());
  1076. Py_RETURN_NONE;
  1077. }
  1078. /*[clinic input]
  1079. _winapi.WaitNamedPipe
  1080. name: LPCTSTR
  1081. timeout: DWORD
  1082. /
  1083. [clinic start generated code]*/
  1084. static PyObject *
  1085. _winapi_WaitNamedPipe_impl(PyObject *module, LPCTSTR name, DWORD timeout)
  1086. /*[clinic end generated code: output=c2866f4439b1fe38 input=36fc781291b1862c]*/
  1087. {
  1088. BOOL success;
  1089. Py_BEGIN_ALLOW_THREADS
  1090. success = WaitNamedPipe(name, timeout);
  1091. Py_END_ALLOW_THREADS
  1092. if (!success)
  1093. return PyErr_SetFromWindowsErr(0);
  1094. Py_RETURN_NONE;
  1095. }
  1096. /*[clinic input]
  1097. _winapi.WaitForMultipleObjects
  1098. handle_seq: object
  1099. wait_flag: BOOL
  1100. milliseconds: DWORD(c_default='INFINITE') = _winapi.INFINITE
  1101. /
  1102. [clinic start generated code]*/
  1103. static PyObject *
  1104. _winapi_WaitForMultipleObjects_impl(PyObject *module, PyObject *handle_seq,
  1105. BOOL wait_flag, DWORD milliseconds)
  1106. /*[clinic end generated code: output=295e3f00b8e45899 input=36f76ca057cd28a0]*/
  1107. {
  1108. DWORD result;
  1109. HANDLE handles[MAXIMUM_WAIT_OBJECTS];
  1110. HANDLE sigint_event = NULL;
  1111. Py_ssize_t nhandles, i;
  1112. if (!PySequence_Check(handle_seq)) {
  1113. PyErr_Format(PyExc_TypeError,
  1114. "sequence type expected, got '%s'",
  1115. Py_TYPE(handle_seq)->tp_name);
  1116. return NULL;
  1117. }
  1118. nhandles = PySequence_Length(handle_seq);
  1119. if (nhandles == -1)
  1120. return NULL;
  1121. if (nhandles < 0 || nhandles >= MAXIMUM_WAIT_OBJECTS - 1) {
  1122. PyErr_Format(PyExc_ValueError,
  1123. "need at most %zd handles, got a sequence of length %zd",
  1124. MAXIMUM_WAIT_OBJECTS - 1, nhandles);
  1125. return NULL;
  1126. }
  1127. for (i = 0; i < nhandles; i++) {
  1128. HANDLE h;
  1129. PyObject *v = PySequence_GetItem(handle_seq, i);
  1130. if (v == NULL)
  1131. return NULL;
  1132. if (!PyArg_Parse(v, F_HANDLE, &h)) {
  1133. Py_DECREF(v);
  1134. return NULL;
  1135. }
  1136. handles[i] = h;
  1137. Py_DECREF(v);
  1138. }
  1139. /* If this is the main thread then make the wait interruptible
  1140. by Ctrl-C unless we are waiting for *all* handles */
  1141. if (!wait_flag && _PyOS_IsMainThread()) {
  1142. sigint_event = _PyOS_SigintEvent();
  1143. assert(sigint_event != NULL);
  1144. handles[nhandles++] = sigint_event;
  1145. }
  1146. Py_BEGIN_ALLOW_THREADS
  1147. if (sigint_event != NULL)
  1148. ResetEvent(sigint_event);
  1149. result = WaitForMultipleObjects((DWORD) nhandles, handles,
  1150. wait_flag, milliseconds);
  1151. Py_END_ALLOW_THREADS
  1152. if (result == WAIT_FAILED)
  1153. return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
  1154. else if (sigint_event != NULL && result == WAIT_OBJECT_0 + nhandles - 1) {
  1155. errno = EINTR;
  1156. return PyErr_SetFromErrno(PyExc_OSError);
  1157. }
  1158. return PyLong_FromLong((int) result);
  1159. }
  1160. /*[clinic input]
  1161. _winapi.WaitForSingleObject -> long
  1162. handle: HANDLE
  1163. milliseconds: DWORD
  1164. /
  1165. Wait for a single object.
  1166. Wait until the specified object is in the signaled state or
  1167. the time-out interval elapses. The timeout value is specified
  1168. in milliseconds.
  1169. [clinic start generated code]*/
  1170. static long
  1171. _winapi_WaitForSingleObject_impl(PyObject *module, HANDLE handle,
  1172. DWORD milliseconds)
  1173. /*[clinic end generated code: output=3c4715d8f1b39859 input=443d1ab076edc7b1]*/
  1174. {
  1175. DWORD result;
  1176. Py_BEGIN_ALLOW_THREADS
  1177. result = WaitForSingleObject(handle, milliseconds);
  1178. Py_END_ALLOW_THREADS
  1179. if (result == WAIT_FAILED) {
  1180. PyErr_SetFromWindowsErr(GetLastError());
  1181. return -1;
  1182. }
  1183. return result;
  1184. }
  1185. /*[clinic input]
  1186. _winapi.WriteFile
  1187. handle: HANDLE
  1188. buffer: object
  1189. overlapped as use_overlapped: bool(accept={int}) = False
  1190. [clinic start generated code]*/
  1191. static PyObject *
  1192. _winapi_WriteFile_impl(PyObject *module, HANDLE handle, PyObject *buffer,
  1193. int use_overlapped)
  1194. /*[clinic end generated code: output=2ca80f6bf3fa92e3 input=11eae2a03aa32731]*/
  1195. {
  1196. Py_buffer _buf, *buf;
  1197. DWORD len, written;
  1198. BOOL ret;
  1199. DWORD err;
  1200. OverlappedObject *overlapped = NULL;
  1201. if (use_overlapped) {
  1202. overlapped = new_overlapped(handle);
  1203. if (!overlapped)
  1204. return NULL;
  1205. buf = &overlapped->write_buffer;
  1206. }
  1207. else
  1208. buf = &_buf;
  1209. if (!PyArg_Parse(buffer, "y*", buf)) {
  1210. Py_XDECREF(overlapped);
  1211. return NULL;
  1212. }
  1213. Py_BEGIN_ALLOW_THREADS
  1214. len = (DWORD)Py_MIN(buf->len, DWORD_MAX);
  1215. ret = WriteFile(handle, buf->buf, len, &written,
  1216. overlapped ? &overlapped->overlapped : NULL);
  1217. Py_END_ALLOW_THREADS
  1218. err = ret ? 0 : GetLastError();
  1219. if (overlapped) {
  1220. if (!ret) {
  1221. if (err == ERROR_IO_PENDING)
  1222. overlapped->pending = 1;
  1223. else {
  1224. Py_DECREF(overlapped);
  1225. return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
  1226. }
  1227. }
  1228. return Py_BuildValue("NI", (PyObject *) overlapped, err);
  1229. }
  1230. PyBuffer_Release(buf);
  1231. if (!ret)
  1232. return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
  1233. return Py_BuildValue("II", written, err);
  1234. }
  1235. static PyMethodDef winapi_functions[] = {
  1236. _WINAPI_CLOSEHANDLE_METHODDEF
  1237. _WINAPI_CONNECTNAMEDPIPE_METHODDEF
  1238. _WINAPI_CREATEFILE_METHODDEF
  1239. _WINAPI_CREATENAMEDPIPE_METHODDEF
  1240. _WINAPI_CREATEPIPE_METHODDEF
  1241. _WINAPI_CREATEPROCESS_METHODDEF
  1242. _WINAPI_CREATEJUNCTION_METHODDEF
  1243. _WINAPI_DUPLICATEHANDLE_METHODDEF
  1244. _WINAPI_EXITPROCESS_METHODDEF
  1245. _WINAPI_GETCURRENTPROCESS_METHODDEF
  1246. _WINAPI_GETEXITCODEPROCESS_METHODDEF
  1247. _WINAPI_GETLASTERROR_METHODDEF
  1248. _WINAPI_GETMODULEFILENAME_METHODDEF
  1249. _WINAPI_GETSTDHANDLE_METHODDEF
  1250. _WINAPI_GETVERSION_METHODDEF
  1251. _WINAPI_OPENPROCESS_METHODDEF
  1252. _WINAPI_PEEKNAMEDPIPE_METHODDEF
  1253. _WINAPI_READFILE_METHODDEF
  1254. _WINAPI_SETNAMEDPIPEHANDLESTATE_METHODDEF
  1255. _WINAPI_TERMINATEPROCESS_METHODDEF
  1256. _WINAPI_WAITNAMEDPIPE_METHODDEF
  1257. _WINAPI_WAITFORMULTIPLEOBJECTS_METHODDEF
  1258. _WINAPI_WAITFORSINGLEOBJECT_METHODDEF
  1259. _WINAPI_WRITEFILE_METHODDEF
  1260. {NULL, NULL}
  1261. };
  1262. static struct PyModuleDef winapi_module = {
  1263. PyModuleDef_HEAD_INIT,
  1264. "_winapi",
  1265. NULL,
  1266. -1,
  1267. winapi_functions,
  1268. NULL,
  1269. NULL,
  1270. NULL,
  1271. NULL
  1272. };
  1273. #define WINAPI_CONSTANT(fmt, con) \
  1274. PyDict_SetItemString(d, #con, Py_BuildValue(fmt, con))
  1275. PyMODINIT_FUNC
  1276. PyInit__winapi(void)
  1277. {
  1278. PyObject *d;
  1279. PyObject *m;
  1280. if (PyType_Ready(&OverlappedType) < 0)
  1281. return NULL;
  1282. m = PyModule_Create(&winapi_module);
  1283. if (m == NULL)
  1284. return NULL;
  1285. d = PyModule_GetDict(m);
  1286. PyDict_SetItemString(d, "Overlapped", (PyObject *) &OverlappedType);
  1287. /* constants */
  1288. WINAPI_CONSTANT(F_DWORD, CREATE_NEW_CONSOLE);
  1289. WINAPI_CONSTANT(F_DWORD, CREATE_NEW_PROCESS_GROUP);
  1290. WINAPI_CONSTANT(F_DWORD, DUPLICATE_SAME_ACCESS);
  1291. WINAPI_CONSTANT(F_DWORD, DUPLICATE_CLOSE_SOURCE);
  1292. WINAPI_CONSTANT(F_DWORD, ERROR_ALREADY_EXISTS);
  1293. WINAPI_CONSTANT(F_DWORD, ERROR_BROKEN_PIPE);
  1294. WINAPI_CONSTANT(F_DWORD, ERROR_IO_PENDING);
  1295. WINAPI_CONSTANT(F_DWORD, ERROR_MORE_DATA);
  1296. WINAPI_CONSTANT(F_DWORD, ERROR_NETNAME_DELETED);
  1297. WINAPI_CONSTANT(F_DWORD, ERROR_NO_SYSTEM_RESOURCES);
  1298. WINAPI_CONSTANT(F_DWORD, ERROR_MORE_DATA);
  1299. WINAPI_CONSTANT(F_DWORD, ERROR_NETNAME_DELETED);
  1300. WINAPI_CONSTANT(F_DWORD, ERROR_NO_DATA);
  1301. WINAPI_CONSTANT(F_DWORD, ERROR_NO_SYSTEM_RESOURCES);
  1302. WINAPI_CONSTANT(F_DWORD, ERROR_OPERATION_ABORTED);
  1303. WINAPI_CONSTANT(F_DWORD, ERROR_PIPE_BUSY);
  1304. WINAPI_CONSTANT(F_DWORD, ERROR_PIPE_CONNECTED);
  1305. WINAPI_CONSTANT(F_DWORD, ERROR_SEM_TIMEOUT);
  1306. WINAPI_CONSTANT(F_DWORD, FILE_FLAG_FIRST_PIPE_INSTANCE);
  1307. WINAPI_CONSTANT(F_DWORD, FILE_FLAG_OVERLAPPED);
  1308. WINAPI_CONSTANT(F_DWORD, FILE_GENERIC_READ);
  1309. WINAPI_CONSTANT(F_DWORD, FILE_GENERIC_WRITE);
  1310. WINAPI_CONSTANT(F_DWORD, GENERIC_READ);
  1311. WINAPI_CONSTANT(F_DWORD, GENERIC_WRITE);
  1312. WINAPI_CONSTANT(F_DWORD, INFINITE);
  1313. WINAPI_CONSTANT(F_DWORD, NMPWAIT_WAIT_FOREVER);
  1314. WINAPI_CONSTANT(F_DWORD, OPEN_EXISTING);
  1315. WINAPI_CONSTANT(F_DWORD, PIPE_ACCESS_DUPLEX);
  1316. WINAPI_CONSTANT(F_DWORD, PIPE_ACCESS_INBOUND);
  1317. WINAPI_CONSTANT(F_DWORD, PIPE_READMODE_MESSAGE);
  1318. WINAPI_CONSTANT(F_DWORD, PIPE_TYPE_MESSAGE);
  1319. WINAPI_CONSTANT(F_DWORD, PIPE_UNLIMITED_INSTANCES);
  1320. WINAPI_CONSTANT(F_DWORD, PIPE_WAIT);
  1321. WINAPI_CONSTANT(F_DWORD, PROCESS_ALL_ACCESS);
  1322. WINAPI_CONSTANT(F_DWORD, PROCESS_DUP_HANDLE);
  1323. WINAPI_CONSTANT(F_DWORD, STARTF_USESHOWWINDOW);
  1324. WINAPI_CONSTANT(F_DWORD, STARTF_USESTDHANDLES);
  1325. WINAPI_CONSTANT(F_DWORD, STD_INPUT_HANDLE);
  1326. WINAPI_CONSTANT(F_DWORD, STD_OUTPUT_HANDLE);
  1327. WINAPI_CONSTANT(F_DWORD, STD_ERROR_HANDLE);
  1328. WINAPI_CONSTANT(F_DWORD, STILL_ACTIVE);
  1329. WINAPI_CONSTANT(F_DWORD, SW_HIDE);
  1330. WINAPI_CONSTANT(F_DWORD, WAIT_OBJECT_0);
  1331. WINAPI_CONSTANT(F_DWORD, WAIT_ABANDONED_0);
  1332. WINAPI_CONSTANT(F_DWORD, WAIT_TIMEOUT);
  1333. WINAPI_CONSTANT("i", NULL);
  1334. return m;
  1335. }