_winapi.c 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590
  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 https://www.python.org/2.4/license for licensing details. */
  35. #include "Python.h"
  36. #include "pycore_moduleobject.h" // _PyModule_GetState()
  37. #include "structmember.h" // PyMemberDef
  38. #ifndef WINDOWS_LEAN_AND_MEAN
  39. #define WINDOWS_LEAN_AND_MEAN
  40. #endif
  41. #include "windows.h"
  42. #include <winioctl.h>
  43. #include <crtdbg.h>
  44. #include "winreparse.h"
  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. #define F_HANDLE F_POINTER
  59. #define F_DWORD "k"
  60. #define T_HANDLE T_POINTER
  61. // winbase.h limits the STARTF_* flags to the desktop API as of 10.0.19041.
  62. #ifndef STARTF_USESHOWWINDOW
  63. #define STARTF_USESHOWWINDOW 0x00000001
  64. #endif
  65. #ifndef STARTF_USESTDHANDLES
  66. #define STARTF_USESTDHANDLES 0x00000100
  67. #endif
  68. typedef struct {
  69. PyTypeObject *overlapped_type;
  70. } WinApiState;
  71. static inline WinApiState*
  72. winapi_get_state(PyObject *module)
  73. {
  74. void *state = _PyModule_GetState(module);
  75. assert(state != NULL);
  76. return (WinApiState *)state;
  77. }
  78. /*
  79. * A Python object wrapping an OVERLAPPED structure and other useful data
  80. * for overlapped I/O
  81. */
  82. typedef struct {
  83. PyObject_HEAD
  84. OVERLAPPED overlapped;
  85. /* For convenience, we store the file handle too */
  86. HANDLE handle;
  87. /* Whether there's I/O in flight */
  88. int pending;
  89. /* Whether I/O completed successfully */
  90. int completed;
  91. /* Buffer used for reading (optional) */
  92. PyObject *read_buffer;
  93. /* Buffer used for writing (optional) */
  94. Py_buffer write_buffer;
  95. } OverlappedObject;
  96. /*
  97. Note: tp_clear (overlapped_clear) is not implemented because it
  98. requires cancelling the IO operation if it's pending and the cancellation is
  99. quite complex and can fail (see: overlapped_dealloc).
  100. */
  101. static int
  102. overlapped_traverse(OverlappedObject *self, visitproc visit, void *arg)
  103. {
  104. Py_VISIT(self->read_buffer);
  105. Py_VISIT(self->write_buffer.obj);
  106. Py_VISIT(Py_TYPE(self));
  107. return 0;
  108. }
  109. static void
  110. overlapped_dealloc(OverlappedObject *self)
  111. {
  112. DWORD bytes;
  113. int err = GetLastError();
  114. PyObject_GC_UnTrack(self);
  115. if (self->pending) {
  116. if (CancelIoEx(self->handle, &self->overlapped) &&
  117. GetOverlappedResult(self->handle, &self->overlapped, &bytes, TRUE))
  118. {
  119. /* The operation is no longer pending -- nothing to do. */
  120. }
  121. else if (_Py_IsInterpreterFinalizing(PyInterpreterState_Get()))
  122. {
  123. /* The operation is still pending -- give a warning. This
  124. will probably only happen on Windows XP. */
  125. PyErr_SetString(PyExc_RuntimeError,
  126. "I/O operations still in flight while destroying "
  127. "Overlapped object, the process may crash");
  128. PyErr_WriteUnraisable(NULL);
  129. }
  130. else
  131. {
  132. /* The operation is still pending, but the process is
  133. probably about to exit, so we need not worry too much
  134. about memory leaks. Leaking self prevents a potential
  135. crash. This can happen when a daemon thread is cleaned
  136. up at exit -- see #19565. We only expect to get here
  137. on Windows XP. */
  138. CloseHandle(self->overlapped.hEvent);
  139. SetLastError(err);
  140. return;
  141. }
  142. }
  143. CloseHandle(self->overlapped.hEvent);
  144. SetLastError(err);
  145. if (self->write_buffer.obj)
  146. PyBuffer_Release(&self->write_buffer);
  147. Py_CLEAR(self->read_buffer);
  148. PyTypeObject *tp = Py_TYPE(self);
  149. tp->tp_free(self);
  150. Py_DECREF(tp);
  151. }
  152. /*[clinic input]
  153. module _winapi
  154. class _winapi.Overlapped "OverlappedObject *" "&OverlappedType"
  155. [clinic start generated code]*/
  156. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=c13d3f5fd1dabb84]*/
  157. /*[python input]
  158. def create_converter(type_, format_unit):
  159. name = type_ + '_converter'
  160. # registered upon creation by CConverter's metaclass
  161. type(name, (CConverter,), {'type': type_, 'format_unit': format_unit})
  162. # format unit differs between platforms for these
  163. create_converter('HANDLE', '" F_HANDLE "')
  164. create_converter('HMODULE', '" F_HANDLE "')
  165. create_converter('LPSECURITY_ATTRIBUTES', '" F_POINTER "')
  166. create_converter('LPCVOID', '" F_POINTER "')
  167. create_converter('BOOL', 'i') # F_BOOL used previously (always 'i')
  168. create_converter('DWORD', 'k') # F_DWORD is always "k" (which is much shorter)
  169. create_converter('LPCTSTR', 's')
  170. create_converter('UINT', 'I') # F_UINT used previously (always 'I')
  171. class LPCWSTR_converter(Py_UNICODE_converter):
  172. type = 'LPCWSTR'
  173. class HANDLE_return_converter(CReturnConverter):
  174. type = 'HANDLE'
  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(
  179. 'if (_return_value == NULL) {\n Py_RETURN_NONE;\n}\n')
  180. data.return_conversion.append(
  181. 'return_value = HANDLE_TO_PYNUM(_return_value);\n')
  182. class DWORD_return_converter(CReturnConverter):
  183. type = 'DWORD'
  184. def render(self, function, data):
  185. self.declare(data)
  186. self.err_occurred_if("_return_value == PY_DWORD_MAX", data)
  187. data.return_conversion.append(
  188. 'return_value = Py_BuildValue("k", _return_value);\n')
  189. class LPVOID_return_converter(CReturnConverter):
  190. type = 'LPVOID'
  191. def render(self, function, data):
  192. self.declare(data)
  193. self.err_occurred_if("_return_value == NULL", data)
  194. data.return_conversion.append(
  195. 'return_value = HANDLE_TO_PYNUM(_return_value);\n')
  196. [python start generated code]*/
  197. /*[python end generated code: output=da39a3ee5e6b4b0d input=011ee0c3a2244bfe]*/
  198. #include "clinic/_winapi.c.h"
  199. /*[clinic input]
  200. _winapi.Overlapped.GetOverlappedResult
  201. wait: bool
  202. /
  203. [clinic start generated code]*/
  204. static PyObject *
  205. _winapi_Overlapped_GetOverlappedResult_impl(OverlappedObject *self, int wait)
  206. /*[clinic end generated code: output=bdd0c1ed6518cd03 input=194505ee8e0e3565]*/
  207. {
  208. BOOL res;
  209. DWORD transferred = 0;
  210. DWORD err;
  211. Py_BEGIN_ALLOW_THREADS
  212. res = GetOverlappedResult(self->handle, &self->overlapped, &transferred,
  213. wait != 0);
  214. Py_END_ALLOW_THREADS
  215. err = res ? ERROR_SUCCESS : GetLastError();
  216. switch (err) {
  217. case ERROR_SUCCESS:
  218. case ERROR_MORE_DATA:
  219. case ERROR_OPERATION_ABORTED:
  220. self->completed = 1;
  221. self->pending = 0;
  222. break;
  223. case ERROR_IO_INCOMPLETE:
  224. break;
  225. default:
  226. self->pending = 0;
  227. return PyErr_SetExcFromWindowsErr(PyExc_OSError, err);
  228. }
  229. if (self->completed && self->read_buffer != NULL) {
  230. assert(PyBytes_CheckExact(self->read_buffer));
  231. if (transferred != PyBytes_GET_SIZE(self->read_buffer) &&
  232. _PyBytes_Resize(&self->read_buffer, transferred))
  233. return NULL;
  234. }
  235. return Py_BuildValue("II", (unsigned) transferred, (unsigned) err);
  236. }
  237. /*[clinic input]
  238. _winapi.Overlapped.getbuffer
  239. [clinic start generated code]*/
  240. static PyObject *
  241. _winapi_Overlapped_getbuffer_impl(OverlappedObject *self)
  242. /*[clinic end generated code: output=95a3eceefae0f748 input=347fcfd56b4ceabd]*/
  243. {
  244. PyObject *res;
  245. if (!self->completed) {
  246. PyErr_SetString(PyExc_ValueError,
  247. "can't get read buffer before GetOverlappedResult() "
  248. "signals the operation completed");
  249. return NULL;
  250. }
  251. res = self->read_buffer ? self->read_buffer : Py_None;
  252. return Py_NewRef(res);
  253. }
  254. /*[clinic input]
  255. _winapi.Overlapped.cancel
  256. [clinic start generated code]*/
  257. static PyObject *
  258. _winapi_Overlapped_cancel_impl(OverlappedObject *self)
  259. /*[clinic end generated code: output=fcb9ab5df4ebdae5 input=cbf3da142290039f]*/
  260. {
  261. BOOL res = TRUE;
  262. if (self->pending) {
  263. Py_BEGIN_ALLOW_THREADS
  264. res = CancelIoEx(self->handle, &self->overlapped);
  265. Py_END_ALLOW_THREADS
  266. }
  267. /* CancelIoEx returns ERROR_NOT_FOUND if the I/O completed in-between */
  268. if (!res && GetLastError() != ERROR_NOT_FOUND)
  269. return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
  270. self->pending = 0;
  271. Py_RETURN_NONE;
  272. }
  273. static PyMethodDef overlapped_methods[] = {
  274. _WINAPI_OVERLAPPED_GETOVERLAPPEDRESULT_METHODDEF
  275. _WINAPI_OVERLAPPED_GETBUFFER_METHODDEF
  276. _WINAPI_OVERLAPPED_CANCEL_METHODDEF
  277. {NULL}
  278. };
  279. static PyMemberDef overlapped_members[] = {
  280. {"event", T_HANDLE,
  281. offsetof(OverlappedObject, overlapped) + offsetof(OVERLAPPED, hEvent),
  282. READONLY, "overlapped event handle"},
  283. {NULL}
  284. };
  285. static PyType_Slot winapi_overlapped_type_slots[] = {
  286. {Py_tp_traverse, overlapped_traverse},
  287. {Py_tp_dealloc, overlapped_dealloc},
  288. {Py_tp_doc, "OVERLAPPED structure wrapper"},
  289. {Py_tp_methods, overlapped_methods},
  290. {Py_tp_members, overlapped_members},
  291. {0,0}
  292. };
  293. static PyType_Spec winapi_overlapped_type_spec = {
  294. .name = "_winapi.Overlapped",
  295. .basicsize = sizeof(OverlappedObject),
  296. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_DISALLOW_INSTANTIATION |
  297. Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_IMMUTABLETYPE),
  298. .slots = winapi_overlapped_type_slots,
  299. };
  300. static OverlappedObject *
  301. new_overlapped(PyObject *module, HANDLE handle)
  302. {
  303. WinApiState *st = winapi_get_state(module);
  304. OverlappedObject *self = PyObject_GC_New(OverlappedObject, st->overlapped_type);
  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. PyObject_GC_Track(self);
  316. return self;
  317. }
  318. /* -------------------------------------------------------------------- */
  319. /* windows API functions */
  320. /*[clinic input]
  321. _winapi.CloseHandle
  322. handle: HANDLE
  323. /
  324. Close handle.
  325. [clinic start generated code]*/
  326. static PyObject *
  327. _winapi_CloseHandle_impl(PyObject *module, HANDLE handle)
  328. /*[clinic end generated code: output=7ad37345f07bd782 input=7f0e4ac36e0352b8]*/
  329. {
  330. BOOL success;
  331. Py_BEGIN_ALLOW_THREADS
  332. success = CloseHandle(handle);
  333. Py_END_ALLOW_THREADS
  334. if (!success)
  335. return PyErr_SetFromWindowsErr(0);
  336. Py_RETURN_NONE;
  337. }
  338. /*[clinic input]
  339. _winapi.ConnectNamedPipe
  340. handle: HANDLE
  341. overlapped as use_overlapped: bool = False
  342. [clinic start generated code]*/
  343. static PyObject *
  344. _winapi_ConnectNamedPipe_impl(PyObject *module, HANDLE handle,
  345. int use_overlapped)
  346. /*[clinic end generated code: output=335a0e7086800671 input=a80e56e8bd370e31]*/
  347. {
  348. BOOL success;
  349. OverlappedObject *overlapped = NULL;
  350. if (use_overlapped) {
  351. overlapped = new_overlapped(module, handle);
  352. if (!overlapped)
  353. return NULL;
  354. }
  355. Py_BEGIN_ALLOW_THREADS
  356. success = ConnectNamedPipe(handle,
  357. overlapped ? &overlapped->overlapped : NULL);
  358. Py_END_ALLOW_THREADS
  359. if (overlapped) {
  360. int err = GetLastError();
  361. /* Overlapped ConnectNamedPipe never returns a success code */
  362. assert(success == 0);
  363. if (err == ERROR_IO_PENDING)
  364. overlapped->pending = 1;
  365. else if (err == ERROR_PIPE_CONNECTED)
  366. SetEvent(overlapped->overlapped.hEvent);
  367. else {
  368. Py_DECREF(overlapped);
  369. return PyErr_SetFromWindowsErr(err);
  370. }
  371. return (PyObject *) overlapped;
  372. }
  373. if (!success)
  374. return PyErr_SetFromWindowsErr(0);
  375. Py_RETURN_NONE;
  376. }
  377. /*[clinic input]
  378. _winapi.CreateFile -> HANDLE
  379. file_name: LPCWSTR
  380. desired_access: DWORD
  381. share_mode: DWORD
  382. security_attributes: LPSECURITY_ATTRIBUTES
  383. creation_disposition: DWORD
  384. flags_and_attributes: DWORD
  385. template_file: HANDLE
  386. /
  387. [clinic start generated code]*/
  388. static HANDLE
  389. _winapi_CreateFile_impl(PyObject *module, LPCWSTR file_name,
  390. DWORD desired_access, DWORD share_mode,
  391. LPSECURITY_ATTRIBUTES security_attributes,
  392. DWORD creation_disposition,
  393. DWORD flags_and_attributes, HANDLE template_file)
  394. /*[clinic end generated code: output=818c811e5e04d550 input=1fa870ed1c2e3d69]*/
  395. {
  396. HANDLE handle;
  397. if (PySys_Audit("_winapi.CreateFile", "uIIII",
  398. file_name, desired_access, share_mode,
  399. creation_disposition, flags_and_attributes) < 0) {
  400. return INVALID_HANDLE_VALUE;
  401. }
  402. Py_BEGIN_ALLOW_THREADS
  403. handle = CreateFileW(file_name, desired_access,
  404. share_mode, security_attributes,
  405. creation_disposition,
  406. flags_and_attributes, template_file);
  407. Py_END_ALLOW_THREADS
  408. if (handle == INVALID_HANDLE_VALUE) {
  409. PyErr_SetFromWindowsErr(0);
  410. }
  411. return handle;
  412. }
  413. /*[clinic input]
  414. _winapi.CreateFileMapping -> HANDLE
  415. file_handle: HANDLE
  416. security_attributes: LPSECURITY_ATTRIBUTES
  417. protect: DWORD
  418. max_size_high: DWORD
  419. max_size_low: DWORD
  420. name: LPCWSTR
  421. /
  422. [clinic start generated code]*/
  423. static HANDLE
  424. _winapi_CreateFileMapping_impl(PyObject *module, HANDLE file_handle,
  425. LPSECURITY_ATTRIBUTES security_attributes,
  426. DWORD protect, DWORD max_size_high,
  427. DWORD max_size_low, LPCWSTR name)
  428. /*[clinic end generated code: output=6c0a4d5cf7f6fcc6 input=3dc5cf762a74dee8]*/
  429. {
  430. HANDLE handle;
  431. Py_BEGIN_ALLOW_THREADS
  432. handle = CreateFileMappingW(file_handle, security_attributes,
  433. protect, max_size_high, max_size_low,
  434. name);
  435. Py_END_ALLOW_THREADS
  436. if (handle == NULL) {
  437. PyObject *temp = PyUnicode_FromWideChar(name, -1);
  438. PyErr_SetExcFromWindowsErrWithFilenameObject(PyExc_OSError, 0, temp);
  439. Py_XDECREF(temp);
  440. handle = INVALID_HANDLE_VALUE;
  441. }
  442. return handle;
  443. }
  444. /*[clinic input]
  445. _winapi.CreateJunction
  446. src_path: LPCWSTR
  447. dst_path: LPCWSTR
  448. /
  449. [clinic start generated code]*/
  450. static PyObject *
  451. _winapi_CreateJunction_impl(PyObject *module, LPCWSTR src_path,
  452. LPCWSTR dst_path)
  453. /*[clinic end generated code: output=44b3f5e9bbcc4271 input=963d29b44b9384a7]*/
  454. {
  455. /* Privilege adjustment */
  456. HANDLE token = NULL;
  457. struct {
  458. TOKEN_PRIVILEGES base;
  459. /* overallocate by a few array elements */
  460. LUID_AND_ATTRIBUTES privs[4];
  461. } tp, previousTp;
  462. int previousTpSize = 0;
  463. /* Reparse data buffer */
  464. const USHORT prefix_len = 4;
  465. USHORT print_len = 0;
  466. USHORT rdb_size = 0;
  467. _Py_PREPARSE_DATA_BUFFER rdb = NULL;
  468. /* Junction point creation */
  469. HANDLE junction = NULL;
  470. DWORD ret = 0;
  471. if (src_path == NULL || dst_path == NULL)
  472. return PyErr_SetFromWindowsErr(ERROR_INVALID_PARAMETER);
  473. if (wcsncmp(src_path, L"\\??\\", prefix_len) == 0)
  474. return PyErr_SetFromWindowsErr(ERROR_INVALID_PARAMETER);
  475. if (PySys_Audit("_winapi.CreateJunction", "uu", src_path, dst_path) < 0) {
  476. return NULL;
  477. }
  478. /* Adjust privileges to allow rewriting directory entry as a
  479. junction point. */
  480. if (!OpenProcessToken(GetCurrentProcess(),
  481. TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &token)) {
  482. goto cleanup;
  483. }
  484. if (!LookupPrivilegeValue(NULL, SE_RESTORE_NAME, &tp.base.Privileges[0].Luid)) {
  485. goto cleanup;
  486. }
  487. tp.base.PrivilegeCount = 1;
  488. tp.base.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  489. if (!AdjustTokenPrivileges(token, FALSE, &tp.base, sizeof(previousTp),
  490. &previousTp.base, &previousTpSize)) {
  491. goto cleanup;
  492. }
  493. if (GetFileAttributesW(src_path) == INVALID_FILE_ATTRIBUTES)
  494. goto cleanup;
  495. /* Store the absolute link target path length in print_len. */
  496. print_len = (USHORT)GetFullPathNameW(src_path, 0, NULL, NULL);
  497. if (print_len == 0)
  498. goto cleanup;
  499. /* NUL terminator should not be part of print_len. */
  500. --print_len;
  501. /* REPARSE_DATA_BUFFER usage is heavily under-documented, especially for
  502. junction points. Here's what I've learned along the way:
  503. - A junction point has two components: a print name and a substitute
  504. name. They both describe the link target, but the substitute name is
  505. the physical target and the print name is shown in directory listings.
  506. - The print name must be a native name, prefixed with "\??\".
  507. - Both names are stored after each other in the same buffer (the
  508. PathBuffer) and both must be NUL-terminated.
  509. - There are four members defining their respective offset and length
  510. inside PathBuffer: SubstituteNameOffset, SubstituteNameLength,
  511. PrintNameOffset and PrintNameLength.
  512. - The total size we need to allocate for the REPARSE_DATA_BUFFER, thus,
  513. is the sum of:
  514. - the fixed header size (REPARSE_DATA_BUFFER_HEADER_SIZE)
  515. - the size of the MountPointReparseBuffer member without the PathBuffer
  516. - the size of the prefix ("\??\") in bytes
  517. - the size of the print name in bytes
  518. - the size of the substitute name in bytes
  519. - the size of two NUL terminators in bytes */
  520. rdb_size = _Py_REPARSE_DATA_BUFFER_HEADER_SIZE +
  521. sizeof(rdb->MountPointReparseBuffer) -
  522. sizeof(rdb->MountPointReparseBuffer.PathBuffer) +
  523. /* Two +1's for NUL terminators. */
  524. (prefix_len + print_len + 1 + print_len + 1) * sizeof(WCHAR);
  525. rdb = (_Py_PREPARSE_DATA_BUFFER)PyMem_RawCalloc(1, rdb_size);
  526. if (rdb == NULL)
  527. goto cleanup;
  528. rdb->ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
  529. rdb->ReparseDataLength = rdb_size - _Py_REPARSE_DATA_BUFFER_HEADER_SIZE;
  530. rdb->MountPointReparseBuffer.SubstituteNameOffset = 0;
  531. rdb->MountPointReparseBuffer.SubstituteNameLength =
  532. (prefix_len + print_len) * sizeof(WCHAR);
  533. rdb->MountPointReparseBuffer.PrintNameOffset =
  534. rdb->MountPointReparseBuffer.SubstituteNameLength + sizeof(WCHAR);
  535. rdb->MountPointReparseBuffer.PrintNameLength = print_len * sizeof(WCHAR);
  536. /* Store the full native path of link target at the substitute name
  537. offset (0). */
  538. wcscpy(rdb->MountPointReparseBuffer.PathBuffer, L"\\??\\");
  539. if (GetFullPathNameW(src_path, print_len + 1,
  540. rdb->MountPointReparseBuffer.PathBuffer + prefix_len,
  541. NULL) == 0)
  542. goto cleanup;
  543. /* Copy everything but the native prefix to the print name offset. */
  544. wcscpy(rdb->MountPointReparseBuffer.PathBuffer +
  545. prefix_len + print_len + 1,
  546. rdb->MountPointReparseBuffer.PathBuffer + prefix_len);
  547. /* Create a directory for the junction point. */
  548. if (!CreateDirectoryW(dst_path, NULL))
  549. goto cleanup;
  550. junction = CreateFileW(dst_path, GENERIC_READ | GENERIC_WRITE, 0, NULL,
  551. OPEN_EXISTING,
  552. FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, NULL);
  553. if (junction == INVALID_HANDLE_VALUE)
  554. goto cleanup;
  555. /* Make the directory entry a junction point. */
  556. if (!DeviceIoControl(junction, FSCTL_SET_REPARSE_POINT, rdb, rdb_size,
  557. NULL, 0, &ret, NULL))
  558. goto cleanup;
  559. cleanup:
  560. ret = GetLastError();
  561. if (previousTpSize) {
  562. AdjustTokenPrivileges(token, FALSE, &previousTp.base, previousTpSize,
  563. NULL, NULL);
  564. }
  565. if (token != NULL)
  566. CloseHandle(token);
  567. if (junction != NULL)
  568. CloseHandle(junction);
  569. PyMem_RawFree(rdb);
  570. if (ret != 0)
  571. return PyErr_SetFromWindowsErr(ret);
  572. Py_RETURN_NONE;
  573. }
  574. /*[clinic input]
  575. _winapi.CreateNamedPipe -> HANDLE
  576. name: LPCTSTR
  577. open_mode: DWORD
  578. pipe_mode: DWORD
  579. max_instances: DWORD
  580. out_buffer_size: DWORD
  581. in_buffer_size: DWORD
  582. default_timeout: DWORD
  583. security_attributes: LPSECURITY_ATTRIBUTES
  584. /
  585. [clinic start generated code]*/
  586. static HANDLE
  587. _winapi_CreateNamedPipe_impl(PyObject *module, LPCTSTR name, DWORD open_mode,
  588. DWORD pipe_mode, DWORD max_instances,
  589. DWORD out_buffer_size, DWORD in_buffer_size,
  590. DWORD default_timeout,
  591. LPSECURITY_ATTRIBUTES security_attributes)
  592. /*[clinic end generated code: output=80f8c07346a94fbc input=5a73530b84d8bc37]*/
  593. {
  594. HANDLE handle;
  595. if (PySys_Audit("_winapi.CreateNamedPipe", "uII",
  596. name, open_mode, pipe_mode) < 0) {
  597. return INVALID_HANDLE_VALUE;
  598. }
  599. Py_BEGIN_ALLOW_THREADS
  600. handle = CreateNamedPipe(name, open_mode, pipe_mode,
  601. max_instances, out_buffer_size,
  602. in_buffer_size, default_timeout,
  603. security_attributes);
  604. Py_END_ALLOW_THREADS
  605. if (handle == INVALID_HANDLE_VALUE)
  606. PyErr_SetFromWindowsErr(0);
  607. return handle;
  608. }
  609. /*[clinic input]
  610. _winapi.CreatePipe
  611. pipe_attrs: object
  612. Ignored internally, can be None.
  613. size: DWORD
  614. /
  615. Create an anonymous pipe.
  616. Returns a 2-tuple of handles, to the read and write ends of the pipe.
  617. [clinic start generated code]*/
  618. static PyObject *
  619. _winapi_CreatePipe_impl(PyObject *module, PyObject *pipe_attrs, DWORD size)
  620. /*[clinic end generated code: output=1c4411d8699f0925 input=c4f2cfa56ef68d90]*/
  621. {
  622. HANDLE read_pipe;
  623. HANDLE write_pipe;
  624. BOOL result;
  625. if (PySys_Audit("_winapi.CreatePipe", NULL) < 0) {
  626. return NULL;
  627. }
  628. Py_BEGIN_ALLOW_THREADS
  629. result = CreatePipe(&read_pipe, &write_pipe, NULL, size);
  630. Py_END_ALLOW_THREADS
  631. if (! result)
  632. return PyErr_SetFromWindowsErr(GetLastError());
  633. return Py_BuildValue(
  634. "NN", HANDLE_TO_PYNUM(read_pipe), HANDLE_TO_PYNUM(write_pipe));
  635. }
  636. /* helpers for createprocess */
  637. static unsigned long
  638. getulong(PyObject* obj, const char* name)
  639. {
  640. PyObject* value;
  641. unsigned long ret;
  642. value = PyObject_GetAttrString(obj, name);
  643. if (! value) {
  644. PyErr_Clear(); /* FIXME: propagate error? */
  645. return 0;
  646. }
  647. ret = PyLong_AsUnsignedLong(value);
  648. Py_DECREF(value);
  649. return ret;
  650. }
  651. static HANDLE
  652. gethandle(PyObject* obj, const char* name)
  653. {
  654. PyObject* value;
  655. HANDLE ret;
  656. value = PyObject_GetAttrString(obj, name);
  657. if (! value) {
  658. PyErr_Clear(); /* FIXME: propagate error? */
  659. return NULL;
  660. }
  661. if (value == Py_None)
  662. ret = NULL;
  663. else
  664. ret = PYNUM_TO_HANDLE(value);
  665. Py_DECREF(value);
  666. return ret;
  667. }
  668. static PyObject *
  669. sortenvironmentkey(PyObject *module, PyObject *item)
  670. {
  671. return _winapi_LCMapStringEx_impl(NULL, LOCALE_NAME_INVARIANT,
  672. LCMAP_UPPERCASE, item);
  673. }
  674. static PyMethodDef sortenvironmentkey_def = {
  675. "sortenvironmentkey", _PyCFunction_CAST(sortenvironmentkey), METH_O, "",
  676. };
  677. static int
  678. sort_environment_keys(PyObject *keys)
  679. {
  680. PyObject *keyfunc = PyCFunction_New(&sortenvironmentkey_def, NULL);
  681. if (keyfunc == NULL) {
  682. return -1;
  683. }
  684. PyObject *kwnames = Py_BuildValue("(s)", "key");
  685. if (kwnames == NULL) {
  686. Py_DECREF(keyfunc);
  687. return -1;
  688. }
  689. PyObject *args[] = { keys, keyfunc };
  690. PyObject *ret = PyObject_VectorcallMethod(&_Py_ID(sort), args, 1, kwnames);
  691. Py_DECREF(keyfunc);
  692. Py_DECREF(kwnames);
  693. if (ret == NULL) {
  694. return -1;
  695. }
  696. Py_DECREF(ret);
  697. return 0;
  698. }
  699. static int
  700. compare_string_ordinal(PyObject *str1, PyObject *str2, int *result)
  701. {
  702. wchar_t *s1 = PyUnicode_AsWideCharString(str1, NULL);
  703. if (s1 == NULL) {
  704. return -1;
  705. }
  706. wchar_t *s2 = PyUnicode_AsWideCharString(str2, NULL);
  707. if (s2 == NULL) {
  708. PyMem_Free(s1);
  709. return -1;
  710. }
  711. *result = CompareStringOrdinal(s1, -1, s2, -1, TRUE);
  712. PyMem_Free(s1);
  713. PyMem_Free(s2);
  714. return 0;
  715. }
  716. static PyObject *
  717. dedup_environment_keys(PyObject *keys)
  718. {
  719. PyObject *result = PyList_New(0);
  720. if (result == NULL) {
  721. return NULL;
  722. }
  723. // Iterate over the pre-ordered keys, check whether the current key is equal
  724. // to the next key (ignoring case), if different, insert the current value
  725. // into the result list. If they are equal, do nothing because we always
  726. // want to keep the last inserted one.
  727. for (Py_ssize_t i = 0; i < PyList_GET_SIZE(keys); i++) {
  728. PyObject *key = PyList_GET_ITEM(keys, i);
  729. // The last key will always be kept.
  730. if (i + 1 == PyList_GET_SIZE(keys)) {
  731. if (PyList_Append(result, key) < 0) {
  732. Py_DECREF(result);
  733. return NULL;
  734. }
  735. continue;
  736. }
  737. PyObject *next_key = PyList_GET_ITEM(keys, i + 1);
  738. int compare_result;
  739. if (compare_string_ordinal(key, next_key, &compare_result) < 0) {
  740. Py_DECREF(result);
  741. return NULL;
  742. }
  743. if (compare_result == CSTR_EQUAL) {
  744. continue;
  745. }
  746. if (PyList_Append(result, key) < 0) {
  747. Py_DECREF(result);
  748. return NULL;
  749. }
  750. }
  751. return result;
  752. }
  753. static PyObject *
  754. normalize_environment(PyObject *environment)
  755. {
  756. PyObject *keys = PyMapping_Keys(environment);
  757. if (keys == NULL) {
  758. return NULL;
  759. }
  760. if (sort_environment_keys(keys) < 0) {
  761. Py_DECREF(keys);
  762. return NULL;
  763. }
  764. PyObject *normalized_keys = dedup_environment_keys(keys);
  765. Py_DECREF(keys);
  766. if (normalized_keys == NULL) {
  767. return NULL;
  768. }
  769. PyObject *result = PyDict_New();
  770. if (result == NULL) {
  771. Py_DECREF(normalized_keys);
  772. return NULL;
  773. }
  774. for (int i = 0; i < PyList_GET_SIZE(normalized_keys); i++) {
  775. PyObject *key = PyList_GET_ITEM(normalized_keys, i);
  776. PyObject *value = PyObject_GetItem(environment, key);
  777. if (value == NULL) {
  778. Py_DECREF(normalized_keys);
  779. Py_DECREF(result);
  780. return NULL;
  781. }
  782. int ret = PyObject_SetItem(result, key, value);
  783. Py_DECREF(value);
  784. if (ret < 0) {
  785. Py_DECREF(normalized_keys);
  786. Py_DECREF(result);
  787. return NULL;
  788. }
  789. }
  790. Py_DECREF(normalized_keys);
  791. return result;
  792. }
  793. static wchar_t *
  794. getenvironment(PyObject* environment)
  795. {
  796. Py_ssize_t i, envsize, totalsize;
  797. wchar_t *buffer = NULL, *p, *end;
  798. PyObject *normalized_environment = NULL;
  799. PyObject *keys = NULL;
  800. PyObject *values = NULL;
  801. /* convert environment dictionary to windows environment string */
  802. if (! PyMapping_Check(environment)) {
  803. PyErr_SetString(
  804. PyExc_TypeError, "environment must be dictionary or None");
  805. return NULL;
  806. }
  807. normalized_environment = normalize_environment(environment);
  808. if (normalize_environment == NULL) {
  809. return NULL;
  810. }
  811. keys = PyMapping_Keys(normalized_environment);
  812. if (!keys) {
  813. goto error;
  814. }
  815. values = PyMapping_Values(normalized_environment);
  816. if (!values) {
  817. goto error;
  818. }
  819. envsize = PyList_GET_SIZE(keys);
  820. if (envsize == 0) {
  821. // A environment block must be terminated by two null characters --
  822. // one for the last string and one for the block.
  823. buffer = PyMem_Calloc(2, sizeof(wchar_t));
  824. if (!buffer) {
  825. PyErr_NoMemory();
  826. }
  827. goto cleanup;
  828. }
  829. if (PyList_GET_SIZE(values) != envsize) {
  830. PyErr_SetString(PyExc_RuntimeError,
  831. "environment changed size during iteration");
  832. goto error;
  833. }
  834. totalsize = 1; /* trailing null character */
  835. for (i = 0; i < envsize; i++) {
  836. PyObject* key = PyList_GET_ITEM(keys, i);
  837. PyObject* value = PyList_GET_ITEM(values, i);
  838. Py_ssize_t size;
  839. if (! PyUnicode_Check(key) || ! PyUnicode_Check(value)) {
  840. PyErr_SetString(PyExc_TypeError,
  841. "environment can only contain strings");
  842. goto error;
  843. }
  844. if (PyUnicode_FindChar(key, '\0', 0, PyUnicode_GET_LENGTH(key), 1) != -1 ||
  845. PyUnicode_FindChar(value, '\0', 0, PyUnicode_GET_LENGTH(value), 1) != -1)
  846. {
  847. PyErr_SetString(PyExc_ValueError, "embedded null character");
  848. goto error;
  849. }
  850. /* Search from index 1 because on Windows starting '=' is allowed for
  851. defining hidden environment variables. */
  852. if (PyUnicode_GET_LENGTH(key) == 0 ||
  853. PyUnicode_FindChar(key, '=', 1, PyUnicode_GET_LENGTH(key), 1) != -1)
  854. {
  855. PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
  856. goto error;
  857. }
  858. size = PyUnicode_AsWideChar(key, NULL, 0);
  859. assert(size > 1);
  860. if (totalsize > PY_SSIZE_T_MAX - size) {
  861. PyErr_SetString(PyExc_OverflowError, "environment too long");
  862. goto error;
  863. }
  864. totalsize += size; /* including '=' */
  865. size = PyUnicode_AsWideChar(value, NULL, 0);
  866. assert(size > 0);
  867. if (totalsize > PY_SSIZE_T_MAX - size) {
  868. PyErr_SetString(PyExc_OverflowError, "environment too long");
  869. goto error;
  870. }
  871. totalsize += size; /* including trailing '\0' */
  872. }
  873. buffer = PyMem_NEW(wchar_t, totalsize);
  874. if (! buffer) {
  875. PyErr_NoMemory();
  876. goto error;
  877. }
  878. p = buffer;
  879. end = buffer + totalsize;
  880. for (i = 0; i < envsize; i++) {
  881. PyObject* key = PyList_GET_ITEM(keys, i);
  882. PyObject* value = PyList_GET_ITEM(values, i);
  883. Py_ssize_t size = PyUnicode_AsWideChar(key, p, end - p);
  884. assert(1 <= size && size < end - p);
  885. p += size;
  886. *p++ = L'=';
  887. size = PyUnicode_AsWideChar(value, p, end - p);
  888. assert(0 <= size && size < end - p);
  889. p += size + 1;
  890. }
  891. /* add trailing null character */
  892. *p++ = L'\0';
  893. assert(p == end);
  894. cleanup:
  895. error:
  896. Py_XDECREF(normalized_environment);
  897. Py_XDECREF(keys);
  898. Py_XDECREF(values);
  899. return buffer;
  900. }
  901. static LPHANDLE
  902. gethandlelist(PyObject *mapping, const char *name, Py_ssize_t *size)
  903. {
  904. LPHANDLE ret = NULL;
  905. PyObject *value_fast = NULL;
  906. PyObject *value;
  907. Py_ssize_t i;
  908. value = PyMapping_GetItemString(mapping, name);
  909. if (!value) {
  910. PyErr_Clear();
  911. return NULL;
  912. }
  913. if (value == Py_None) {
  914. goto cleanup;
  915. }
  916. value_fast = PySequence_Fast(value, "handle_list must be a sequence or None");
  917. if (value_fast == NULL)
  918. goto cleanup;
  919. *size = PySequence_Fast_GET_SIZE(value_fast) * sizeof(HANDLE);
  920. /* Passing an empty array causes CreateProcess to fail so just don't set it */
  921. if (*size == 0) {
  922. goto cleanup;
  923. }
  924. ret = PyMem_Malloc(*size);
  925. if (ret == NULL)
  926. goto cleanup;
  927. for (i = 0; i < PySequence_Fast_GET_SIZE(value_fast); i++) {
  928. ret[i] = PYNUM_TO_HANDLE(PySequence_Fast_GET_ITEM(value_fast, i));
  929. if (ret[i] == (HANDLE)-1 && PyErr_Occurred()) {
  930. PyMem_Free(ret);
  931. ret = NULL;
  932. goto cleanup;
  933. }
  934. }
  935. cleanup:
  936. Py_DECREF(value);
  937. Py_XDECREF(value_fast);
  938. return ret;
  939. }
  940. typedef struct {
  941. LPPROC_THREAD_ATTRIBUTE_LIST attribute_list;
  942. LPHANDLE handle_list;
  943. } AttributeList;
  944. static void
  945. freeattributelist(AttributeList *attribute_list)
  946. {
  947. if (attribute_list->attribute_list != NULL) {
  948. DeleteProcThreadAttributeList(attribute_list->attribute_list);
  949. PyMem_Free(attribute_list->attribute_list);
  950. }
  951. PyMem_Free(attribute_list->handle_list);
  952. memset(attribute_list, 0, sizeof(*attribute_list));
  953. }
  954. static int
  955. getattributelist(PyObject *obj, const char *name, AttributeList *attribute_list)
  956. {
  957. int ret = 0;
  958. DWORD err;
  959. BOOL result;
  960. PyObject *value;
  961. Py_ssize_t handle_list_size;
  962. DWORD attribute_count = 0;
  963. SIZE_T attribute_list_size = 0;
  964. value = PyObject_GetAttrString(obj, name);
  965. if (!value) {
  966. PyErr_Clear(); /* FIXME: propagate error? */
  967. return 0;
  968. }
  969. if (value == Py_None) {
  970. ret = 0;
  971. goto cleanup;
  972. }
  973. if (!PyMapping_Check(value)) {
  974. ret = -1;
  975. PyErr_Format(PyExc_TypeError, "%s must be a mapping or None", name);
  976. goto cleanup;
  977. }
  978. attribute_list->handle_list = gethandlelist(value, "handle_list", &handle_list_size);
  979. if (attribute_list->handle_list == NULL && PyErr_Occurred()) {
  980. ret = -1;
  981. goto cleanup;
  982. }
  983. if (attribute_list->handle_list != NULL)
  984. ++attribute_count;
  985. /* Get how many bytes we need for the attribute list */
  986. result = InitializeProcThreadAttributeList(NULL, attribute_count, 0, &attribute_list_size);
  987. if (result || GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
  988. ret = -1;
  989. PyErr_SetFromWindowsErr(GetLastError());
  990. goto cleanup;
  991. }
  992. attribute_list->attribute_list = PyMem_Malloc(attribute_list_size);
  993. if (attribute_list->attribute_list == NULL) {
  994. ret = -1;
  995. goto cleanup;
  996. }
  997. result = InitializeProcThreadAttributeList(
  998. attribute_list->attribute_list,
  999. attribute_count,
  1000. 0,
  1001. &attribute_list_size);
  1002. if (!result) {
  1003. err = GetLastError();
  1004. /* So that we won't call DeleteProcThreadAttributeList */
  1005. PyMem_Free(attribute_list->attribute_list);
  1006. attribute_list->attribute_list = NULL;
  1007. ret = -1;
  1008. PyErr_SetFromWindowsErr(err);
  1009. goto cleanup;
  1010. }
  1011. if (attribute_list->handle_list != NULL) {
  1012. result = UpdateProcThreadAttribute(
  1013. attribute_list->attribute_list,
  1014. 0,
  1015. PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
  1016. attribute_list->handle_list,
  1017. handle_list_size,
  1018. NULL,
  1019. NULL);
  1020. if (!result) {
  1021. ret = -1;
  1022. PyErr_SetFromWindowsErr(GetLastError());
  1023. goto cleanup;
  1024. }
  1025. }
  1026. cleanup:
  1027. Py_DECREF(value);
  1028. if (ret < 0)
  1029. freeattributelist(attribute_list);
  1030. return ret;
  1031. }
  1032. /*[clinic input]
  1033. _winapi.CreateProcess
  1034. application_name: Py_UNICODE(accept={str, NoneType})
  1035. command_line: object
  1036. Can be str or None
  1037. proc_attrs: object
  1038. Ignored internally, can be None.
  1039. thread_attrs: object
  1040. Ignored internally, can be None.
  1041. inherit_handles: BOOL
  1042. creation_flags: DWORD
  1043. env_mapping: object
  1044. current_directory: Py_UNICODE(accept={str, NoneType})
  1045. startup_info: object
  1046. /
  1047. Create a new process and its primary thread.
  1048. The return value is a tuple of the process handle, thread handle,
  1049. process ID, and thread ID.
  1050. [clinic start generated code]*/
  1051. static PyObject *
  1052. _winapi_CreateProcess_impl(PyObject *module,
  1053. const Py_UNICODE *application_name,
  1054. PyObject *command_line, PyObject *proc_attrs,
  1055. PyObject *thread_attrs, BOOL inherit_handles,
  1056. DWORD creation_flags, PyObject *env_mapping,
  1057. const Py_UNICODE *current_directory,
  1058. PyObject *startup_info)
  1059. /*[clinic end generated code: output=9b2423a609230132 input=42ac293eaea03fc4]*/
  1060. {
  1061. PyObject *ret = NULL;
  1062. BOOL result;
  1063. PROCESS_INFORMATION pi;
  1064. STARTUPINFOEXW si;
  1065. wchar_t *wenvironment = NULL;
  1066. wchar_t *command_line_copy = NULL;
  1067. AttributeList attribute_list = {0};
  1068. if (PySys_Audit("_winapi.CreateProcess", "uuu", application_name,
  1069. command_line, current_directory) < 0) {
  1070. return NULL;
  1071. }
  1072. ZeroMemory(&si, sizeof(si));
  1073. si.StartupInfo.cb = sizeof(si);
  1074. /* note: we only support a small subset of all SI attributes */
  1075. si.StartupInfo.dwFlags = getulong(startup_info, "dwFlags");
  1076. si.StartupInfo.wShowWindow = (WORD)getulong(startup_info, "wShowWindow");
  1077. si.StartupInfo.hStdInput = gethandle(startup_info, "hStdInput");
  1078. si.StartupInfo.hStdOutput = gethandle(startup_info, "hStdOutput");
  1079. si.StartupInfo.hStdError = gethandle(startup_info, "hStdError");
  1080. if (PyErr_Occurred())
  1081. goto cleanup;
  1082. if (env_mapping != Py_None) {
  1083. wenvironment = getenvironment(env_mapping);
  1084. if (wenvironment == NULL) {
  1085. goto cleanup;
  1086. }
  1087. }
  1088. if (getattributelist(startup_info, "lpAttributeList", &attribute_list) < 0)
  1089. goto cleanup;
  1090. si.lpAttributeList = attribute_list.attribute_list;
  1091. if (PyUnicode_Check(command_line)) {
  1092. command_line_copy = PyUnicode_AsWideCharString(command_line, NULL);
  1093. if (command_line_copy == NULL) {
  1094. goto cleanup;
  1095. }
  1096. }
  1097. else if (command_line != Py_None) {
  1098. PyErr_Format(PyExc_TypeError,
  1099. "CreateProcess() argument 2 must be str or None, not %s",
  1100. Py_TYPE(command_line)->tp_name);
  1101. goto cleanup;
  1102. }
  1103. Py_BEGIN_ALLOW_THREADS
  1104. result = CreateProcessW(application_name,
  1105. command_line_copy,
  1106. NULL,
  1107. NULL,
  1108. inherit_handles,
  1109. creation_flags | EXTENDED_STARTUPINFO_PRESENT |
  1110. CREATE_UNICODE_ENVIRONMENT,
  1111. wenvironment,
  1112. current_directory,
  1113. (LPSTARTUPINFOW)&si,
  1114. &pi);
  1115. Py_END_ALLOW_THREADS
  1116. if (!result) {
  1117. PyErr_SetFromWindowsErr(GetLastError());
  1118. goto cleanup;
  1119. }
  1120. ret = Py_BuildValue("NNkk",
  1121. HANDLE_TO_PYNUM(pi.hProcess),
  1122. HANDLE_TO_PYNUM(pi.hThread),
  1123. pi.dwProcessId,
  1124. pi.dwThreadId);
  1125. cleanup:
  1126. PyMem_Free(command_line_copy);
  1127. PyMem_Free(wenvironment);
  1128. freeattributelist(&attribute_list);
  1129. return ret;
  1130. }
  1131. /*[clinic input]
  1132. _winapi.DuplicateHandle -> HANDLE
  1133. source_process_handle: HANDLE
  1134. source_handle: HANDLE
  1135. target_process_handle: HANDLE
  1136. desired_access: DWORD
  1137. inherit_handle: BOOL
  1138. options: DWORD = 0
  1139. /
  1140. Return a duplicate handle object.
  1141. The duplicate handle refers to the same object as the original
  1142. handle. Therefore, any changes to the object are reflected
  1143. through both handles.
  1144. [clinic start generated code]*/
  1145. static HANDLE
  1146. _winapi_DuplicateHandle_impl(PyObject *module, HANDLE source_process_handle,
  1147. HANDLE source_handle,
  1148. HANDLE target_process_handle,
  1149. DWORD desired_access, BOOL inherit_handle,
  1150. DWORD options)
  1151. /*[clinic end generated code: output=ad9711397b5dcd4e input=b933e3f2356a8c12]*/
  1152. {
  1153. HANDLE target_handle;
  1154. BOOL result;
  1155. Py_BEGIN_ALLOW_THREADS
  1156. result = DuplicateHandle(
  1157. source_process_handle,
  1158. source_handle,
  1159. target_process_handle,
  1160. &target_handle,
  1161. desired_access,
  1162. inherit_handle,
  1163. options
  1164. );
  1165. Py_END_ALLOW_THREADS
  1166. if (! result) {
  1167. PyErr_SetFromWindowsErr(GetLastError());
  1168. return INVALID_HANDLE_VALUE;
  1169. }
  1170. return target_handle;
  1171. }
  1172. /*[clinic input]
  1173. _winapi.ExitProcess
  1174. ExitCode: UINT
  1175. /
  1176. [clinic start generated code]*/
  1177. static PyObject *
  1178. _winapi_ExitProcess_impl(PyObject *module, UINT ExitCode)
  1179. /*[clinic end generated code: output=a387deb651175301 input=4f05466a9406c558]*/
  1180. {
  1181. #if defined(Py_DEBUG)
  1182. #ifdef MS_WINDOWS_DESKTOP
  1183. SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOALIGNMENTFAULTEXCEPT|
  1184. SEM_NOGPFAULTERRORBOX|SEM_NOOPENFILEERRORBOX);
  1185. #endif
  1186. _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
  1187. #endif
  1188. ExitProcess(ExitCode);
  1189. return NULL;
  1190. }
  1191. /*[clinic input]
  1192. _winapi.GetCurrentProcess -> HANDLE
  1193. Return a handle object for the current process.
  1194. [clinic start generated code]*/
  1195. static HANDLE
  1196. _winapi_GetCurrentProcess_impl(PyObject *module)
  1197. /*[clinic end generated code: output=ddeb4dd2ffadf344 input=b213403fd4b96b41]*/
  1198. {
  1199. return GetCurrentProcess();
  1200. }
  1201. /*[clinic input]
  1202. _winapi.GetExitCodeProcess -> DWORD
  1203. process: HANDLE
  1204. /
  1205. Return the termination status of the specified process.
  1206. [clinic start generated code]*/
  1207. static DWORD
  1208. _winapi_GetExitCodeProcess_impl(PyObject *module, HANDLE process)
  1209. /*[clinic end generated code: output=b4620bdf2bccf36b input=61b6bfc7dc2ee374]*/
  1210. {
  1211. DWORD exit_code;
  1212. BOOL result;
  1213. result = GetExitCodeProcess(process, &exit_code);
  1214. if (! result) {
  1215. PyErr_SetFromWindowsErr(GetLastError());
  1216. exit_code = PY_DWORD_MAX;
  1217. }
  1218. return exit_code;
  1219. }
  1220. /*[clinic input]
  1221. _winapi.GetLastError -> DWORD
  1222. [clinic start generated code]*/
  1223. static DWORD
  1224. _winapi_GetLastError_impl(PyObject *module)
  1225. /*[clinic end generated code: output=8585b827cb1a92c5 input=62d47fb9bce038ba]*/
  1226. {
  1227. return GetLastError();
  1228. }
  1229. /*[clinic input]
  1230. _winapi.GetModuleFileName
  1231. module_handle: HMODULE
  1232. /
  1233. Return the fully-qualified path for the file that contains module.
  1234. The module must have been loaded by the current process.
  1235. The module parameter should be a handle to the loaded module
  1236. whose path is being requested. If this parameter is 0,
  1237. GetModuleFileName retrieves the path of the executable file
  1238. of the current process.
  1239. [clinic start generated code]*/
  1240. static PyObject *
  1241. _winapi_GetModuleFileName_impl(PyObject *module, HMODULE module_handle)
  1242. /*[clinic end generated code: output=85b4b728c5160306 input=6d66ff7deca5d11f]*/
  1243. {
  1244. BOOL result;
  1245. WCHAR filename[MAX_PATH];
  1246. Py_BEGIN_ALLOW_THREADS
  1247. result = GetModuleFileNameW(module_handle, filename, MAX_PATH);
  1248. filename[MAX_PATH-1] = '\0';
  1249. Py_END_ALLOW_THREADS
  1250. if (! result)
  1251. return PyErr_SetFromWindowsErr(GetLastError());
  1252. return PyUnicode_FromWideChar(filename, wcslen(filename));
  1253. }
  1254. /*[clinic input]
  1255. _winapi.GetStdHandle -> HANDLE
  1256. std_handle: DWORD
  1257. One of STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, or STD_ERROR_HANDLE.
  1258. /
  1259. Return a handle to the specified standard device.
  1260. The integer associated with the handle object is returned.
  1261. [clinic start generated code]*/
  1262. static HANDLE
  1263. _winapi_GetStdHandle_impl(PyObject *module, DWORD std_handle)
  1264. /*[clinic end generated code: output=0e613001e73ab614 input=07016b06a2fc8826]*/
  1265. {
  1266. HANDLE handle;
  1267. Py_BEGIN_ALLOW_THREADS
  1268. handle = GetStdHandle(std_handle);
  1269. Py_END_ALLOW_THREADS
  1270. if (handle == INVALID_HANDLE_VALUE)
  1271. PyErr_SetFromWindowsErr(GetLastError());
  1272. return handle;
  1273. }
  1274. /*[clinic input]
  1275. _winapi.GetVersion -> long
  1276. Return the version number of the current operating system.
  1277. [clinic start generated code]*/
  1278. static long
  1279. _winapi_GetVersion_impl(PyObject *module)
  1280. /*[clinic end generated code: output=e41f0db5a3b82682 input=e21dff8d0baeded2]*/
  1281. /* Disable deprecation warnings about GetVersionEx as the result is
  1282. being passed straight through to the caller, who is responsible for
  1283. using it correctly. */
  1284. #pragma warning(push)
  1285. #pragma warning(disable:4996)
  1286. {
  1287. return GetVersion();
  1288. }
  1289. #pragma warning(pop)
  1290. /*[clinic input]
  1291. _winapi.MapViewOfFile -> LPVOID
  1292. file_map: HANDLE
  1293. desired_access: DWORD
  1294. file_offset_high: DWORD
  1295. file_offset_low: DWORD
  1296. number_bytes: size_t
  1297. /
  1298. [clinic start generated code]*/
  1299. static LPVOID
  1300. _winapi_MapViewOfFile_impl(PyObject *module, HANDLE file_map,
  1301. DWORD desired_access, DWORD file_offset_high,
  1302. DWORD file_offset_low, size_t number_bytes)
  1303. /*[clinic end generated code: output=f23b1ee4823663e3 input=177471073be1a103]*/
  1304. {
  1305. LPVOID address;
  1306. Py_BEGIN_ALLOW_THREADS
  1307. address = MapViewOfFile(file_map, desired_access, file_offset_high,
  1308. file_offset_low, number_bytes);
  1309. Py_END_ALLOW_THREADS
  1310. if (address == NULL)
  1311. PyErr_SetFromWindowsErr(0);
  1312. return address;
  1313. }
  1314. /*[clinic input]
  1315. _winapi.UnmapViewOfFile
  1316. address: LPCVOID
  1317. /
  1318. [clinic start generated code]*/
  1319. static PyObject *
  1320. _winapi_UnmapViewOfFile_impl(PyObject *module, LPCVOID address)
  1321. /*[clinic end generated code: output=4f7e18ac75d19744 input=8c4b6119ad9288a3]*/
  1322. {
  1323. BOOL success;
  1324. Py_BEGIN_ALLOW_THREADS
  1325. success = UnmapViewOfFile(address);
  1326. Py_END_ALLOW_THREADS
  1327. if (!success) {
  1328. return PyErr_SetFromWindowsErr(0);
  1329. }
  1330. Py_RETURN_NONE;
  1331. }
  1332. /*[clinic input]
  1333. _winapi.OpenFileMapping -> HANDLE
  1334. desired_access: DWORD
  1335. inherit_handle: BOOL
  1336. name: LPCWSTR
  1337. /
  1338. [clinic start generated code]*/
  1339. static HANDLE
  1340. _winapi_OpenFileMapping_impl(PyObject *module, DWORD desired_access,
  1341. BOOL inherit_handle, LPCWSTR name)
  1342. /*[clinic end generated code: output=08cc44def1cb11f1 input=131f2a405359de7f]*/
  1343. {
  1344. HANDLE handle;
  1345. Py_BEGIN_ALLOW_THREADS
  1346. handle = OpenFileMappingW(desired_access, inherit_handle, name);
  1347. Py_END_ALLOW_THREADS
  1348. if (handle == NULL) {
  1349. PyObject *temp = PyUnicode_FromWideChar(name, -1);
  1350. PyErr_SetExcFromWindowsErrWithFilenameObject(PyExc_OSError, 0, temp);
  1351. Py_XDECREF(temp);
  1352. handle = INVALID_HANDLE_VALUE;
  1353. }
  1354. return handle;
  1355. }
  1356. /*[clinic input]
  1357. _winapi.OpenProcess -> HANDLE
  1358. desired_access: DWORD
  1359. inherit_handle: BOOL
  1360. process_id: DWORD
  1361. /
  1362. [clinic start generated code]*/
  1363. static HANDLE
  1364. _winapi_OpenProcess_impl(PyObject *module, DWORD desired_access,
  1365. BOOL inherit_handle, DWORD process_id)
  1366. /*[clinic end generated code: output=b42b6b81ea5a0fc3 input=ec98c4cf4ea2ec36]*/
  1367. {
  1368. HANDLE handle;
  1369. if (PySys_Audit("_winapi.OpenProcess", "II",
  1370. process_id, desired_access) < 0) {
  1371. return INVALID_HANDLE_VALUE;
  1372. }
  1373. Py_BEGIN_ALLOW_THREADS
  1374. handle = OpenProcess(desired_access, inherit_handle, process_id);
  1375. Py_END_ALLOW_THREADS
  1376. if (handle == NULL) {
  1377. PyErr_SetFromWindowsErr(GetLastError());
  1378. handle = INVALID_HANDLE_VALUE;
  1379. }
  1380. return handle;
  1381. }
  1382. /*[clinic input]
  1383. _winapi.PeekNamedPipe
  1384. handle: HANDLE
  1385. size: int = 0
  1386. /
  1387. [clinic start generated code]*/
  1388. static PyObject *
  1389. _winapi_PeekNamedPipe_impl(PyObject *module, HANDLE handle, int size)
  1390. /*[clinic end generated code: output=d0c3e29e49d323dd input=c7aa53bfbce69d70]*/
  1391. {
  1392. PyObject *buf = NULL;
  1393. DWORD nread, navail, nleft;
  1394. BOOL ret;
  1395. if (size < 0) {
  1396. PyErr_SetString(PyExc_ValueError, "negative size");
  1397. return NULL;
  1398. }
  1399. if (size) {
  1400. buf = PyBytes_FromStringAndSize(NULL, size);
  1401. if (!buf)
  1402. return NULL;
  1403. Py_BEGIN_ALLOW_THREADS
  1404. ret = PeekNamedPipe(handle, PyBytes_AS_STRING(buf), size, &nread,
  1405. &navail, &nleft);
  1406. Py_END_ALLOW_THREADS
  1407. if (!ret) {
  1408. Py_DECREF(buf);
  1409. return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
  1410. }
  1411. if (_PyBytes_Resize(&buf, nread))
  1412. return NULL;
  1413. return Py_BuildValue("NII", buf, navail, nleft);
  1414. }
  1415. else {
  1416. Py_BEGIN_ALLOW_THREADS
  1417. ret = PeekNamedPipe(handle, NULL, 0, NULL, &navail, &nleft);
  1418. Py_END_ALLOW_THREADS
  1419. if (!ret) {
  1420. return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
  1421. }
  1422. return Py_BuildValue("II", navail, nleft);
  1423. }
  1424. }
  1425. /*[clinic input]
  1426. _winapi.LCMapStringEx
  1427. locale: LPCWSTR
  1428. flags: DWORD
  1429. src: unicode
  1430. [clinic start generated code]*/
  1431. static PyObject *
  1432. _winapi_LCMapStringEx_impl(PyObject *module, LPCWSTR locale, DWORD flags,
  1433. PyObject *src)
  1434. /*[clinic end generated code: output=b90e6b26e028ff0a input=3e3dcd9b8164012f]*/
  1435. {
  1436. if (flags & (LCMAP_SORTHANDLE | LCMAP_HASH | LCMAP_BYTEREV |
  1437. LCMAP_SORTKEY)) {
  1438. return PyErr_Format(PyExc_ValueError, "unsupported flags");
  1439. }
  1440. Py_ssize_t src_size;
  1441. wchar_t *src_ = PyUnicode_AsWideCharString(src, &src_size);
  1442. if (!src_) {
  1443. return NULL;
  1444. }
  1445. if (src_size > INT_MAX) {
  1446. PyMem_Free(src_);
  1447. PyErr_SetString(PyExc_OverflowError, "input string is too long");
  1448. return NULL;
  1449. }
  1450. int dest_size = LCMapStringEx(locale, flags, src_, (int)src_size, NULL, 0,
  1451. NULL, NULL, 0);
  1452. if (dest_size <= 0) {
  1453. DWORD error = GetLastError();
  1454. PyMem_Free(src_);
  1455. return PyErr_SetFromWindowsErr(error);
  1456. }
  1457. wchar_t* dest = PyMem_NEW(wchar_t, dest_size);
  1458. if (dest == NULL) {
  1459. PyMem_Free(src_);
  1460. return PyErr_NoMemory();
  1461. }
  1462. int nmapped = LCMapStringEx(locale, flags, src_, (int)src_size, dest, dest_size,
  1463. NULL, NULL, 0);
  1464. if (nmapped <= 0) {
  1465. DWORD error = GetLastError();
  1466. PyMem_Free(src_);
  1467. PyMem_DEL(dest);
  1468. return PyErr_SetFromWindowsErr(error);
  1469. }
  1470. PyMem_Free(src_);
  1471. PyObject *ret = PyUnicode_FromWideChar(dest, nmapped);
  1472. PyMem_DEL(dest);
  1473. return ret;
  1474. }
  1475. /*[clinic input]
  1476. _winapi.ReadFile
  1477. handle: HANDLE
  1478. size: DWORD
  1479. overlapped as use_overlapped: bool = False
  1480. [clinic start generated code]*/
  1481. static PyObject *
  1482. _winapi_ReadFile_impl(PyObject *module, HANDLE handle, DWORD size,
  1483. int use_overlapped)
  1484. /*[clinic end generated code: output=d3d5b44a8201b944 input=4f82f8e909ad91ad]*/
  1485. {
  1486. DWORD nread;
  1487. PyObject *buf;
  1488. BOOL ret;
  1489. DWORD err;
  1490. OverlappedObject *overlapped = NULL;
  1491. buf = PyBytes_FromStringAndSize(NULL, size);
  1492. if (!buf)
  1493. return NULL;
  1494. if (use_overlapped) {
  1495. overlapped = new_overlapped(module, handle);
  1496. if (!overlapped) {
  1497. Py_DECREF(buf);
  1498. return NULL;
  1499. }
  1500. /* Steals reference to buf */
  1501. overlapped->read_buffer = buf;
  1502. }
  1503. Py_BEGIN_ALLOW_THREADS
  1504. ret = ReadFile(handle, PyBytes_AS_STRING(buf), size, &nread,
  1505. overlapped ? &overlapped->overlapped : NULL);
  1506. Py_END_ALLOW_THREADS
  1507. err = ret ? 0 : GetLastError();
  1508. if (overlapped) {
  1509. if (!ret) {
  1510. if (err == ERROR_IO_PENDING)
  1511. overlapped->pending = 1;
  1512. else if (err != ERROR_MORE_DATA) {
  1513. Py_DECREF(overlapped);
  1514. return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
  1515. }
  1516. }
  1517. return Py_BuildValue("NI", (PyObject *) overlapped, err);
  1518. }
  1519. if (!ret && err != ERROR_MORE_DATA) {
  1520. Py_DECREF(buf);
  1521. return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
  1522. }
  1523. if (_PyBytes_Resize(&buf, nread))
  1524. return NULL;
  1525. return Py_BuildValue("NI", buf, err);
  1526. }
  1527. /*[clinic input]
  1528. _winapi.SetNamedPipeHandleState
  1529. named_pipe: HANDLE
  1530. mode: object
  1531. max_collection_count: object
  1532. collect_data_timeout: object
  1533. /
  1534. [clinic start generated code]*/
  1535. static PyObject *
  1536. _winapi_SetNamedPipeHandleState_impl(PyObject *module, HANDLE named_pipe,
  1537. PyObject *mode,
  1538. PyObject *max_collection_count,
  1539. PyObject *collect_data_timeout)
  1540. /*[clinic end generated code: output=f2129d222cbfa095 input=9142d72163d0faa6]*/
  1541. {
  1542. PyObject *oArgs[3] = {mode, max_collection_count, collect_data_timeout};
  1543. DWORD dwArgs[3], *pArgs[3] = {NULL, NULL, NULL};
  1544. int i;
  1545. BOOL b;
  1546. for (i = 0 ; i < 3 ; i++) {
  1547. if (oArgs[i] != Py_None) {
  1548. dwArgs[i] = PyLong_AsUnsignedLongMask(oArgs[i]);
  1549. if (PyErr_Occurred())
  1550. return NULL;
  1551. pArgs[i] = &dwArgs[i];
  1552. }
  1553. }
  1554. Py_BEGIN_ALLOW_THREADS
  1555. b = SetNamedPipeHandleState(named_pipe, pArgs[0], pArgs[1], pArgs[2]);
  1556. Py_END_ALLOW_THREADS
  1557. if (!b)
  1558. return PyErr_SetFromWindowsErr(0);
  1559. Py_RETURN_NONE;
  1560. }
  1561. /*[clinic input]
  1562. _winapi.TerminateProcess
  1563. handle: HANDLE
  1564. exit_code: UINT
  1565. /
  1566. Terminate the specified process and all of its threads.
  1567. [clinic start generated code]*/
  1568. static PyObject *
  1569. _winapi_TerminateProcess_impl(PyObject *module, HANDLE handle,
  1570. UINT exit_code)
  1571. /*[clinic end generated code: output=f4e99ac3f0b1f34a input=d6bc0aa1ee3bb4df]*/
  1572. {
  1573. BOOL result;
  1574. if (PySys_Audit("_winapi.TerminateProcess", "nI",
  1575. (Py_ssize_t)handle, exit_code) < 0) {
  1576. return NULL;
  1577. }
  1578. result = TerminateProcess(handle, exit_code);
  1579. if (! result)
  1580. return PyErr_SetFromWindowsErr(GetLastError());
  1581. Py_RETURN_NONE;
  1582. }
  1583. /*[clinic input]
  1584. _winapi.VirtualQuerySize -> size_t
  1585. address: LPCVOID
  1586. /
  1587. [clinic start generated code]*/
  1588. static size_t
  1589. _winapi_VirtualQuerySize_impl(PyObject *module, LPCVOID address)
  1590. /*[clinic end generated code: output=40c8e0ff5ec964df input=6b784a69755d0bb6]*/
  1591. {
  1592. SIZE_T size_of_buf;
  1593. MEMORY_BASIC_INFORMATION mem_basic_info;
  1594. SIZE_T region_size;
  1595. Py_BEGIN_ALLOW_THREADS
  1596. size_of_buf = VirtualQuery(address, &mem_basic_info, sizeof(mem_basic_info));
  1597. Py_END_ALLOW_THREADS
  1598. if (size_of_buf == 0)
  1599. PyErr_SetFromWindowsErr(0);
  1600. region_size = mem_basic_info.RegionSize;
  1601. return region_size;
  1602. }
  1603. /*[clinic input]
  1604. _winapi.WaitNamedPipe
  1605. name: LPCTSTR
  1606. timeout: DWORD
  1607. /
  1608. [clinic start generated code]*/
  1609. static PyObject *
  1610. _winapi_WaitNamedPipe_impl(PyObject *module, LPCTSTR name, DWORD timeout)
  1611. /*[clinic end generated code: output=c2866f4439b1fe38 input=36fc781291b1862c]*/
  1612. {
  1613. BOOL success;
  1614. Py_BEGIN_ALLOW_THREADS
  1615. success = WaitNamedPipe(name, timeout);
  1616. Py_END_ALLOW_THREADS
  1617. if (!success)
  1618. return PyErr_SetFromWindowsErr(0);
  1619. Py_RETURN_NONE;
  1620. }
  1621. /*[clinic input]
  1622. _winapi.WaitForMultipleObjects
  1623. handle_seq: object
  1624. wait_flag: BOOL
  1625. milliseconds: DWORD(c_default='INFINITE') = _winapi.INFINITE
  1626. /
  1627. [clinic start generated code]*/
  1628. static PyObject *
  1629. _winapi_WaitForMultipleObjects_impl(PyObject *module, PyObject *handle_seq,
  1630. BOOL wait_flag, DWORD milliseconds)
  1631. /*[clinic end generated code: output=295e3f00b8e45899 input=36f76ca057cd28a0]*/
  1632. {
  1633. DWORD result;
  1634. HANDLE handles[MAXIMUM_WAIT_OBJECTS];
  1635. HANDLE sigint_event = NULL;
  1636. Py_ssize_t nhandles, i;
  1637. if (!PySequence_Check(handle_seq)) {
  1638. PyErr_Format(PyExc_TypeError,
  1639. "sequence type expected, got '%s'",
  1640. Py_TYPE(handle_seq)->tp_name);
  1641. return NULL;
  1642. }
  1643. nhandles = PySequence_Length(handle_seq);
  1644. if (nhandles == -1)
  1645. return NULL;
  1646. if (nhandles < 0 || nhandles > MAXIMUM_WAIT_OBJECTS - 1) {
  1647. PyErr_Format(PyExc_ValueError,
  1648. "need at most %zd handles, got a sequence of length %zd",
  1649. MAXIMUM_WAIT_OBJECTS - 1, nhandles);
  1650. return NULL;
  1651. }
  1652. for (i = 0; i < nhandles; i++) {
  1653. HANDLE h;
  1654. PyObject *v = PySequence_GetItem(handle_seq, i);
  1655. if (v == NULL)
  1656. return NULL;
  1657. if (!PyArg_Parse(v, F_HANDLE, &h)) {
  1658. Py_DECREF(v);
  1659. return NULL;
  1660. }
  1661. handles[i] = h;
  1662. Py_DECREF(v);
  1663. }
  1664. /* If this is the main thread then make the wait interruptible
  1665. by Ctrl-C unless we are waiting for *all* handles */
  1666. if (!wait_flag && _PyOS_IsMainThread()) {
  1667. sigint_event = _PyOS_SigintEvent();
  1668. assert(sigint_event != NULL);
  1669. handles[nhandles++] = sigint_event;
  1670. }
  1671. Py_BEGIN_ALLOW_THREADS
  1672. if (sigint_event != NULL)
  1673. ResetEvent(sigint_event);
  1674. result = WaitForMultipleObjects((DWORD) nhandles, handles,
  1675. wait_flag, milliseconds);
  1676. Py_END_ALLOW_THREADS
  1677. if (result == WAIT_FAILED)
  1678. return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
  1679. else if (sigint_event != NULL && result == WAIT_OBJECT_0 + nhandles - 1) {
  1680. errno = EINTR;
  1681. return PyErr_SetFromErrno(PyExc_OSError);
  1682. }
  1683. return PyLong_FromLong((int) result);
  1684. }
  1685. /*[clinic input]
  1686. _winapi.WaitForSingleObject -> long
  1687. handle: HANDLE
  1688. milliseconds: DWORD
  1689. /
  1690. Wait for a single object.
  1691. Wait until the specified object is in the signaled state or
  1692. the time-out interval elapses. The timeout value is specified
  1693. in milliseconds.
  1694. [clinic start generated code]*/
  1695. static long
  1696. _winapi_WaitForSingleObject_impl(PyObject *module, HANDLE handle,
  1697. DWORD milliseconds)
  1698. /*[clinic end generated code: output=3c4715d8f1b39859 input=443d1ab076edc7b1]*/
  1699. {
  1700. DWORD result;
  1701. Py_BEGIN_ALLOW_THREADS
  1702. result = WaitForSingleObject(handle, milliseconds);
  1703. Py_END_ALLOW_THREADS
  1704. if (result == WAIT_FAILED) {
  1705. PyErr_SetFromWindowsErr(GetLastError());
  1706. return -1;
  1707. }
  1708. return result;
  1709. }
  1710. /*[clinic input]
  1711. _winapi.WriteFile
  1712. handle: HANDLE
  1713. buffer: object
  1714. overlapped as use_overlapped: bool = False
  1715. [clinic start generated code]*/
  1716. static PyObject *
  1717. _winapi_WriteFile_impl(PyObject *module, HANDLE handle, PyObject *buffer,
  1718. int use_overlapped)
  1719. /*[clinic end generated code: output=2ca80f6bf3fa92e3 input=2badb008c8a2e2a0]*/
  1720. {
  1721. Py_buffer _buf, *buf;
  1722. DWORD len, written;
  1723. BOOL ret;
  1724. DWORD err;
  1725. OverlappedObject *overlapped = NULL;
  1726. if (use_overlapped) {
  1727. overlapped = new_overlapped(module, handle);
  1728. if (!overlapped)
  1729. return NULL;
  1730. buf = &overlapped->write_buffer;
  1731. }
  1732. else
  1733. buf = &_buf;
  1734. if (!PyArg_Parse(buffer, "y*", buf)) {
  1735. Py_XDECREF(overlapped);
  1736. return NULL;
  1737. }
  1738. Py_BEGIN_ALLOW_THREADS
  1739. len = (DWORD)Py_MIN(buf->len, PY_DWORD_MAX);
  1740. ret = WriteFile(handle, buf->buf, len, &written,
  1741. overlapped ? &overlapped->overlapped : NULL);
  1742. Py_END_ALLOW_THREADS
  1743. err = ret ? 0 : GetLastError();
  1744. if (overlapped) {
  1745. if (!ret) {
  1746. if (err == ERROR_IO_PENDING)
  1747. overlapped->pending = 1;
  1748. else {
  1749. Py_DECREF(overlapped);
  1750. return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
  1751. }
  1752. }
  1753. return Py_BuildValue("NI", (PyObject *) overlapped, err);
  1754. }
  1755. PyBuffer_Release(buf);
  1756. if (!ret)
  1757. return PyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
  1758. return Py_BuildValue("II", written, err);
  1759. }
  1760. /*[clinic input]
  1761. _winapi.GetACP
  1762. Get the current Windows ANSI code page identifier.
  1763. [clinic start generated code]*/
  1764. static PyObject *
  1765. _winapi_GetACP_impl(PyObject *module)
  1766. /*[clinic end generated code: output=f7ee24bf705dbb88 input=1433c96d03a05229]*/
  1767. {
  1768. return PyLong_FromUnsignedLong(GetACP());
  1769. }
  1770. /*[clinic input]
  1771. _winapi.GetFileType -> DWORD
  1772. handle: HANDLE
  1773. [clinic start generated code]*/
  1774. static DWORD
  1775. _winapi_GetFileType_impl(PyObject *module, HANDLE handle)
  1776. /*[clinic end generated code: output=92b8466ac76ecc17 input=0058366bc40bbfbf]*/
  1777. {
  1778. DWORD result;
  1779. Py_BEGIN_ALLOW_THREADS
  1780. result = GetFileType(handle);
  1781. Py_END_ALLOW_THREADS
  1782. if (result == FILE_TYPE_UNKNOWN && GetLastError() != NO_ERROR) {
  1783. PyErr_SetFromWindowsErr(0);
  1784. return -1;
  1785. }
  1786. return result;
  1787. }
  1788. /*[clinic input]
  1789. _winapi._mimetypes_read_windows_registry
  1790. on_type_read: object
  1791. Optimized function for reading all known MIME types from the registry.
  1792. *on_type_read* is a callable taking *type* and *ext* arguments, as for
  1793. MimeTypes.add_type.
  1794. [clinic start generated code]*/
  1795. static PyObject *
  1796. _winapi__mimetypes_read_windows_registry_impl(PyObject *module,
  1797. PyObject *on_type_read)
  1798. /*[clinic end generated code: output=20829f00bebce55b input=cd357896d6501f68]*/
  1799. {
  1800. #define CCH_EXT 128
  1801. #define CB_TYPE 510
  1802. struct {
  1803. wchar_t ext[CCH_EXT];
  1804. wchar_t type[CB_TYPE / sizeof(wchar_t) + 1];
  1805. } entries[64];
  1806. int entry = 0;
  1807. HKEY hkcr = NULL;
  1808. LRESULT err;
  1809. Py_BEGIN_ALLOW_THREADS
  1810. err = RegOpenKeyExW(HKEY_CLASSES_ROOT, NULL, 0, KEY_READ, &hkcr);
  1811. for (DWORD i = 0; err == ERROR_SUCCESS || err == ERROR_MORE_DATA; ++i) {
  1812. LPWSTR ext = entries[entry].ext;
  1813. LPWSTR type = entries[entry].type;
  1814. DWORD cchExt = CCH_EXT;
  1815. DWORD cbType = CB_TYPE;
  1816. HKEY subkey;
  1817. DWORD regType;
  1818. err = RegEnumKeyExW(hkcr, i, ext, &cchExt, NULL, NULL, NULL, NULL);
  1819. if (err != ERROR_SUCCESS || (cchExt && ext[0] != L'.')) {
  1820. continue;
  1821. }
  1822. err = RegOpenKeyExW(hkcr, ext, 0, KEY_READ, &subkey);
  1823. if (err == ERROR_FILE_NOT_FOUND) {
  1824. err = ERROR_SUCCESS;
  1825. continue;
  1826. } else if (err != ERROR_SUCCESS) {
  1827. continue;
  1828. }
  1829. err = RegQueryValueExW(subkey, L"Content Type", NULL,
  1830. &regType, (LPBYTE)type, &cbType);
  1831. RegCloseKey(subkey);
  1832. if (err == ERROR_FILE_NOT_FOUND) {
  1833. err = ERROR_SUCCESS;
  1834. continue;
  1835. } else if (err != ERROR_SUCCESS) {
  1836. continue;
  1837. } else if (regType != REG_SZ || !cbType) {
  1838. continue;
  1839. }
  1840. type[cbType / sizeof(wchar_t)] = L'\0';
  1841. entry += 1;
  1842. /* Flush our cached entries if we are full */
  1843. if (entry == sizeof(entries) / sizeof(entries[0])) {
  1844. Py_BLOCK_THREADS
  1845. for (int j = 0; j < entry; ++j) {
  1846. PyObject *r = PyObject_CallFunction(
  1847. on_type_read, "uu", entries[j].type, entries[j].ext
  1848. );
  1849. if (!r) {
  1850. /* We blocked threads, so safe to return from here */
  1851. RegCloseKey(hkcr);
  1852. return NULL;
  1853. }
  1854. Py_DECREF(r);
  1855. }
  1856. Py_UNBLOCK_THREADS
  1857. entry = 0;
  1858. }
  1859. }
  1860. if (hkcr) {
  1861. RegCloseKey(hkcr);
  1862. }
  1863. Py_END_ALLOW_THREADS
  1864. if (err != ERROR_SUCCESS && err != ERROR_NO_MORE_ITEMS) {
  1865. PyErr_SetFromWindowsErr((int)err);
  1866. return NULL;
  1867. }
  1868. for (int j = 0; j < entry; ++j) {
  1869. PyObject *r = PyObject_CallFunction(
  1870. on_type_read, "uu", entries[j].type, entries[j].ext
  1871. );
  1872. if (!r) {
  1873. return NULL;
  1874. }
  1875. Py_DECREF(r);
  1876. }
  1877. Py_RETURN_NONE;
  1878. #undef CCH_EXT
  1879. #undef CB_TYPE
  1880. }
  1881. /*[clinic input]
  1882. _winapi.NeedCurrentDirectoryForExePath -> bool
  1883. exe_name: LPCWSTR
  1884. /
  1885. [clinic start generated code]*/
  1886. static int
  1887. _winapi_NeedCurrentDirectoryForExePath_impl(PyObject *module,
  1888. LPCWSTR exe_name)
  1889. /*[clinic end generated code: output=a65ec879502b58fc input=972aac88a1ec2f00]*/
  1890. {
  1891. BOOL result;
  1892. Py_BEGIN_ALLOW_THREADS
  1893. result = NeedCurrentDirectoryForExePathW(exe_name);
  1894. Py_END_ALLOW_THREADS
  1895. return result;
  1896. }
  1897. /*[clinic input]
  1898. _winapi.CopyFile2
  1899. existing_file_name: LPCWSTR
  1900. new_file_name: LPCWSTR
  1901. flags: DWORD
  1902. progress_routine: object = None
  1903. Copies a file from one name to a new name.
  1904. This is implemented using the CopyFile2 API, which preserves all stat
  1905. and metadata information apart from security attributes.
  1906. progress_routine is reserved for future use, but is currently not
  1907. implemented. Its value is ignored.
  1908. [clinic start generated code]*/
  1909. static PyObject *
  1910. _winapi_CopyFile2_impl(PyObject *module, LPCWSTR existing_file_name,
  1911. LPCWSTR new_file_name, DWORD flags,
  1912. PyObject *progress_routine)
  1913. /*[clinic end generated code: output=43d960d9df73d984 input=fb976b8d1492d130]*/
  1914. {
  1915. HRESULT hr;
  1916. COPYFILE2_EXTENDED_PARAMETERS params = { sizeof(COPYFILE2_EXTENDED_PARAMETERS) };
  1917. if (PySys_Audit("_winapi.CopyFile2", "uuI",
  1918. existing_file_name, new_file_name, flags) < 0) {
  1919. return NULL;
  1920. }
  1921. params.dwCopyFlags = flags;
  1922. /* For future implementation. We ignore the value for now so that
  1923. users only have to test for 'CopyFile2' existing and not whether
  1924. the additional parameter exists.
  1925. if (progress_routine != Py_None) {
  1926. params.pProgressRoutine = _winapi_CopyFile2ProgressRoutine;
  1927. params.pvCallbackContext = Py_NewRef(progress_routine);
  1928. }
  1929. */
  1930. Py_BEGIN_ALLOW_THREADS;
  1931. hr = CopyFile2(existing_file_name, new_file_name, &params);
  1932. Py_END_ALLOW_THREADS;
  1933. /* For future implementation.
  1934. if (progress_routine != Py_None) {
  1935. Py_DECREF(progress_routine);
  1936. }
  1937. */
  1938. if (FAILED(hr)) {
  1939. if ((hr & 0xFFFF0000) == 0x80070000) {
  1940. PyErr_SetFromWindowsErr(hr & 0xFFFF);
  1941. } else {
  1942. PyErr_SetFromWindowsErr(hr);
  1943. }
  1944. return NULL;
  1945. }
  1946. Py_RETURN_NONE;
  1947. }
  1948. static PyMethodDef winapi_functions[] = {
  1949. _WINAPI_CLOSEHANDLE_METHODDEF
  1950. _WINAPI_CONNECTNAMEDPIPE_METHODDEF
  1951. _WINAPI_CREATEFILE_METHODDEF
  1952. _WINAPI_CREATEFILEMAPPING_METHODDEF
  1953. _WINAPI_CREATENAMEDPIPE_METHODDEF
  1954. _WINAPI_CREATEPIPE_METHODDEF
  1955. _WINAPI_CREATEPROCESS_METHODDEF
  1956. _WINAPI_CREATEJUNCTION_METHODDEF
  1957. _WINAPI_DUPLICATEHANDLE_METHODDEF
  1958. _WINAPI_EXITPROCESS_METHODDEF
  1959. _WINAPI_GETCURRENTPROCESS_METHODDEF
  1960. _WINAPI_GETEXITCODEPROCESS_METHODDEF
  1961. _WINAPI_GETLASTERROR_METHODDEF
  1962. _WINAPI_GETMODULEFILENAME_METHODDEF
  1963. _WINAPI_GETSTDHANDLE_METHODDEF
  1964. _WINAPI_GETVERSION_METHODDEF
  1965. _WINAPI_MAPVIEWOFFILE_METHODDEF
  1966. _WINAPI_OPENFILEMAPPING_METHODDEF
  1967. _WINAPI_OPENPROCESS_METHODDEF
  1968. _WINAPI_PEEKNAMEDPIPE_METHODDEF
  1969. _WINAPI_LCMAPSTRINGEX_METHODDEF
  1970. _WINAPI_READFILE_METHODDEF
  1971. _WINAPI_SETNAMEDPIPEHANDLESTATE_METHODDEF
  1972. _WINAPI_TERMINATEPROCESS_METHODDEF
  1973. _WINAPI_UNMAPVIEWOFFILE_METHODDEF
  1974. _WINAPI_VIRTUALQUERYSIZE_METHODDEF
  1975. _WINAPI_WAITNAMEDPIPE_METHODDEF
  1976. _WINAPI_WAITFORMULTIPLEOBJECTS_METHODDEF
  1977. _WINAPI_WAITFORSINGLEOBJECT_METHODDEF
  1978. _WINAPI_WRITEFILE_METHODDEF
  1979. _WINAPI_GETACP_METHODDEF
  1980. _WINAPI_GETFILETYPE_METHODDEF
  1981. _WINAPI__MIMETYPES_READ_WINDOWS_REGISTRY_METHODDEF
  1982. _WINAPI_NEEDCURRENTDIRECTORYFOREXEPATH_METHODDEF
  1983. _WINAPI_COPYFILE2_METHODDEF
  1984. {NULL, NULL}
  1985. };
  1986. #define WINAPI_CONSTANT(fmt, con) \
  1987. do { \
  1988. PyObject *value = Py_BuildValue(fmt, con); \
  1989. if (value == NULL) { \
  1990. return -1; \
  1991. } \
  1992. if (PyDict_SetItemString(d, #con, value) < 0) { \
  1993. Py_DECREF(value); \
  1994. return -1; \
  1995. } \
  1996. Py_DECREF(value); \
  1997. } while (0)
  1998. static int winapi_exec(PyObject *m)
  1999. {
  2000. WinApiState *st = winapi_get_state(m);
  2001. st->overlapped_type = (PyTypeObject *)PyType_FromModuleAndSpec(m, &winapi_overlapped_type_spec, NULL);
  2002. if (st->overlapped_type == NULL) {
  2003. return -1;
  2004. }
  2005. if (PyModule_AddType(m, st->overlapped_type) < 0) {
  2006. return -1;
  2007. }
  2008. PyObject *d = PyModule_GetDict(m);
  2009. /* constants */
  2010. WINAPI_CONSTANT(F_DWORD, CREATE_NEW_CONSOLE);
  2011. WINAPI_CONSTANT(F_DWORD, CREATE_NEW_PROCESS_GROUP);
  2012. WINAPI_CONSTANT(F_DWORD, DUPLICATE_SAME_ACCESS);
  2013. WINAPI_CONSTANT(F_DWORD, DUPLICATE_CLOSE_SOURCE);
  2014. WINAPI_CONSTANT(F_DWORD, ERROR_ACCESS_DENIED);
  2015. WINAPI_CONSTANT(F_DWORD, ERROR_ALREADY_EXISTS);
  2016. WINAPI_CONSTANT(F_DWORD, ERROR_BROKEN_PIPE);
  2017. WINAPI_CONSTANT(F_DWORD, ERROR_IO_PENDING);
  2018. WINAPI_CONSTANT(F_DWORD, ERROR_MORE_DATA);
  2019. WINAPI_CONSTANT(F_DWORD, ERROR_NETNAME_DELETED);
  2020. WINAPI_CONSTANT(F_DWORD, ERROR_NO_SYSTEM_RESOURCES);
  2021. WINAPI_CONSTANT(F_DWORD, ERROR_MORE_DATA);
  2022. WINAPI_CONSTANT(F_DWORD, ERROR_NETNAME_DELETED);
  2023. WINAPI_CONSTANT(F_DWORD, ERROR_NO_DATA);
  2024. WINAPI_CONSTANT(F_DWORD, ERROR_NO_SYSTEM_RESOURCES);
  2025. WINAPI_CONSTANT(F_DWORD, ERROR_OPERATION_ABORTED);
  2026. WINAPI_CONSTANT(F_DWORD, ERROR_PIPE_BUSY);
  2027. WINAPI_CONSTANT(F_DWORD, ERROR_PIPE_CONNECTED);
  2028. WINAPI_CONSTANT(F_DWORD, ERROR_PRIVILEGE_NOT_HELD);
  2029. WINAPI_CONSTANT(F_DWORD, ERROR_SEM_TIMEOUT);
  2030. WINAPI_CONSTANT(F_DWORD, FILE_FLAG_FIRST_PIPE_INSTANCE);
  2031. WINAPI_CONSTANT(F_DWORD, FILE_FLAG_OVERLAPPED);
  2032. WINAPI_CONSTANT(F_DWORD, FILE_GENERIC_READ);
  2033. WINAPI_CONSTANT(F_DWORD, FILE_GENERIC_WRITE);
  2034. WINAPI_CONSTANT(F_DWORD, FILE_MAP_ALL_ACCESS);
  2035. WINAPI_CONSTANT(F_DWORD, FILE_MAP_COPY);
  2036. WINAPI_CONSTANT(F_DWORD, FILE_MAP_EXECUTE);
  2037. WINAPI_CONSTANT(F_DWORD, FILE_MAP_READ);
  2038. WINAPI_CONSTANT(F_DWORD, FILE_MAP_WRITE);
  2039. WINAPI_CONSTANT(F_DWORD, GENERIC_READ);
  2040. WINAPI_CONSTANT(F_DWORD, GENERIC_WRITE);
  2041. WINAPI_CONSTANT(F_DWORD, INFINITE);
  2042. WINAPI_CONSTANT(F_HANDLE, INVALID_HANDLE_VALUE);
  2043. WINAPI_CONSTANT(F_DWORD, MEM_COMMIT);
  2044. WINAPI_CONSTANT(F_DWORD, MEM_FREE);
  2045. WINAPI_CONSTANT(F_DWORD, MEM_IMAGE);
  2046. WINAPI_CONSTANT(F_DWORD, MEM_MAPPED);
  2047. WINAPI_CONSTANT(F_DWORD, MEM_PRIVATE);
  2048. WINAPI_CONSTANT(F_DWORD, MEM_RESERVE);
  2049. WINAPI_CONSTANT(F_DWORD, NMPWAIT_WAIT_FOREVER);
  2050. WINAPI_CONSTANT(F_DWORD, OPEN_EXISTING);
  2051. WINAPI_CONSTANT(F_DWORD, PAGE_EXECUTE);
  2052. WINAPI_CONSTANT(F_DWORD, PAGE_EXECUTE_READ);
  2053. WINAPI_CONSTANT(F_DWORD, PAGE_EXECUTE_READWRITE);
  2054. WINAPI_CONSTANT(F_DWORD, PAGE_EXECUTE_WRITECOPY);
  2055. WINAPI_CONSTANT(F_DWORD, PAGE_GUARD);
  2056. WINAPI_CONSTANT(F_DWORD, PAGE_NOACCESS);
  2057. WINAPI_CONSTANT(F_DWORD, PAGE_NOCACHE);
  2058. WINAPI_CONSTANT(F_DWORD, PAGE_READONLY);
  2059. WINAPI_CONSTANT(F_DWORD, PAGE_READWRITE);
  2060. WINAPI_CONSTANT(F_DWORD, PAGE_WRITECOMBINE);
  2061. WINAPI_CONSTANT(F_DWORD, PAGE_WRITECOPY);
  2062. WINAPI_CONSTANT(F_DWORD, PIPE_ACCESS_DUPLEX);
  2063. WINAPI_CONSTANT(F_DWORD, PIPE_ACCESS_INBOUND);
  2064. WINAPI_CONSTANT(F_DWORD, PIPE_READMODE_MESSAGE);
  2065. WINAPI_CONSTANT(F_DWORD, PIPE_TYPE_MESSAGE);
  2066. WINAPI_CONSTANT(F_DWORD, PIPE_UNLIMITED_INSTANCES);
  2067. WINAPI_CONSTANT(F_DWORD, PIPE_WAIT);
  2068. WINAPI_CONSTANT(F_DWORD, PROCESS_ALL_ACCESS);
  2069. WINAPI_CONSTANT(F_DWORD, SYNCHRONIZE);
  2070. WINAPI_CONSTANT(F_DWORD, PROCESS_DUP_HANDLE);
  2071. WINAPI_CONSTANT(F_DWORD, SEC_COMMIT);
  2072. WINAPI_CONSTANT(F_DWORD, SEC_IMAGE);
  2073. WINAPI_CONSTANT(F_DWORD, SEC_LARGE_PAGES);
  2074. WINAPI_CONSTANT(F_DWORD, SEC_NOCACHE);
  2075. WINAPI_CONSTANT(F_DWORD, SEC_RESERVE);
  2076. WINAPI_CONSTANT(F_DWORD, SEC_WRITECOMBINE);
  2077. WINAPI_CONSTANT(F_DWORD, STARTF_USESHOWWINDOW);
  2078. WINAPI_CONSTANT(F_DWORD, STARTF_USESTDHANDLES);
  2079. WINAPI_CONSTANT(F_DWORD, STD_INPUT_HANDLE);
  2080. WINAPI_CONSTANT(F_DWORD, STD_OUTPUT_HANDLE);
  2081. WINAPI_CONSTANT(F_DWORD, STD_ERROR_HANDLE);
  2082. WINAPI_CONSTANT(F_DWORD, STILL_ACTIVE);
  2083. WINAPI_CONSTANT(F_DWORD, SW_HIDE);
  2084. WINAPI_CONSTANT(F_DWORD, WAIT_OBJECT_0);
  2085. WINAPI_CONSTANT(F_DWORD, WAIT_ABANDONED_0);
  2086. WINAPI_CONSTANT(F_DWORD, WAIT_TIMEOUT);
  2087. WINAPI_CONSTANT(F_DWORD, ABOVE_NORMAL_PRIORITY_CLASS);
  2088. WINAPI_CONSTANT(F_DWORD, BELOW_NORMAL_PRIORITY_CLASS);
  2089. WINAPI_CONSTANT(F_DWORD, HIGH_PRIORITY_CLASS);
  2090. WINAPI_CONSTANT(F_DWORD, IDLE_PRIORITY_CLASS);
  2091. WINAPI_CONSTANT(F_DWORD, NORMAL_PRIORITY_CLASS);
  2092. WINAPI_CONSTANT(F_DWORD, REALTIME_PRIORITY_CLASS);
  2093. WINAPI_CONSTANT(F_DWORD, CREATE_NO_WINDOW);
  2094. WINAPI_CONSTANT(F_DWORD, DETACHED_PROCESS);
  2095. WINAPI_CONSTANT(F_DWORD, CREATE_DEFAULT_ERROR_MODE);
  2096. WINAPI_CONSTANT(F_DWORD, CREATE_BREAKAWAY_FROM_JOB);
  2097. WINAPI_CONSTANT(F_DWORD, FILE_TYPE_UNKNOWN);
  2098. WINAPI_CONSTANT(F_DWORD, FILE_TYPE_DISK);
  2099. WINAPI_CONSTANT(F_DWORD, FILE_TYPE_CHAR);
  2100. WINAPI_CONSTANT(F_DWORD, FILE_TYPE_PIPE);
  2101. WINAPI_CONSTANT(F_DWORD, FILE_TYPE_REMOTE);
  2102. WINAPI_CONSTANT("u", LOCALE_NAME_INVARIANT);
  2103. WINAPI_CONSTANT(F_DWORD, LOCALE_NAME_MAX_LENGTH);
  2104. WINAPI_CONSTANT("u", LOCALE_NAME_SYSTEM_DEFAULT);
  2105. WINAPI_CONSTANT("u", LOCALE_NAME_USER_DEFAULT);
  2106. WINAPI_CONSTANT(F_DWORD, LCMAP_FULLWIDTH);
  2107. WINAPI_CONSTANT(F_DWORD, LCMAP_HALFWIDTH);
  2108. WINAPI_CONSTANT(F_DWORD, LCMAP_HIRAGANA);
  2109. WINAPI_CONSTANT(F_DWORD, LCMAP_KATAKANA);
  2110. WINAPI_CONSTANT(F_DWORD, LCMAP_LINGUISTIC_CASING);
  2111. WINAPI_CONSTANT(F_DWORD, LCMAP_LOWERCASE);
  2112. WINAPI_CONSTANT(F_DWORD, LCMAP_SIMPLIFIED_CHINESE);
  2113. WINAPI_CONSTANT(F_DWORD, LCMAP_TITLECASE);
  2114. WINAPI_CONSTANT(F_DWORD, LCMAP_TRADITIONAL_CHINESE);
  2115. WINAPI_CONSTANT(F_DWORD, LCMAP_UPPERCASE);
  2116. WINAPI_CONSTANT(F_DWORD, COPY_FILE_ALLOW_DECRYPTED_DESTINATION);
  2117. WINAPI_CONSTANT(F_DWORD, COPY_FILE_COPY_SYMLINK);
  2118. WINAPI_CONSTANT(F_DWORD, COPY_FILE_FAIL_IF_EXISTS);
  2119. WINAPI_CONSTANT(F_DWORD, COPY_FILE_NO_BUFFERING);
  2120. WINAPI_CONSTANT(F_DWORD, COPY_FILE_NO_OFFLOAD);
  2121. WINAPI_CONSTANT(F_DWORD, COPY_FILE_OPEN_SOURCE_FOR_WRITE);
  2122. WINAPI_CONSTANT(F_DWORD, COPY_FILE_RESTARTABLE);
  2123. WINAPI_CONSTANT(F_DWORD, COPY_FILE_REQUEST_SECURITY_PRIVILEGES);
  2124. WINAPI_CONSTANT(F_DWORD, COPY_FILE_RESUME_FROM_PAUSE);
  2125. #ifndef COPY_FILE_REQUEST_COMPRESSED_TRAFFIC
  2126. // Only defined in newer WinSDKs
  2127. #define COPY_FILE_REQUEST_COMPRESSED_TRAFFIC 0x10000000
  2128. #endif
  2129. WINAPI_CONSTANT(F_DWORD, COPY_FILE_REQUEST_COMPRESSED_TRAFFIC);
  2130. WINAPI_CONSTANT(F_DWORD, COPYFILE2_CALLBACK_CHUNK_STARTED);
  2131. WINAPI_CONSTANT(F_DWORD, COPYFILE2_CALLBACK_CHUNK_FINISHED);
  2132. WINAPI_CONSTANT(F_DWORD, COPYFILE2_CALLBACK_STREAM_STARTED);
  2133. WINAPI_CONSTANT(F_DWORD, COPYFILE2_CALLBACK_STREAM_FINISHED);
  2134. WINAPI_CONSTANT(F_DWORD, COPYFILE2_CALLBACK_POLL_CONTINUE);
  2135. WINAPI_CONSTANT(F_DWORD, COPYFILE2_CALLBACK_ERROR);
  2136. WINAPI_CONSTANT(F_DWORD, COPYFILE2_PROGRESS_CONTINUE);
  2137. WINAPI_CONSTANT(F_DWORD, COPYFILE2_PROGRESS_CANCEL);
  2138. WINAPI_CONSTANT(F_DWORD, COPYFILE2_PROGRESS_STOP);
  2139. WINAPI_CONSTANT(F_DWORD, COPYFILE2_PROGRESS_QUIET);
  2140. WINAPI_CONSTANT(F_DWORD, COPYFILE2_PROGRESS_PAUSE);
  2141. WINAPI_CONSTANT("i", NULL);
  2142. return 0;
  2143. }
  2144. static PyModuleDef_Slot winapi_slots[] = {
  2145. {Py_mod_exec, winapi_exec},
  2146. {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  2147. {0, NULL}
  2148. };
  2149. static int
  2150. winapi_traverse(PyObject *module, visitproc visit, void *arg)
  2151. {
  2152. WinApiState *st = winapi_get_state(module);
  2153. Py_VISIT(st->overlapped_type);
  2154. return 0;
  2155. }
  2156. static int
  2157. winapi_clear(PyObject *module)
  2158. {
  2159. WinApiState *st = winapi_get_state(module);
  2160. Py_CLEAR(st->overlapped_type);
  2161. return 0;
  2162. }
  2163. static void
  2164. winapi_free(void *module)
  2165. {
  2166. winapi_clear((PyObject *)module);
  2167. }
  2168. static struct PyModuleDef winapi_module = {
  2169. PyModuleDef_HEAD_INIT,
  2170. .m_name = "_winapi",
  2171. .m_size = sizeof(WinApiState),
  2172. .m_methods = winapi_functions,
  2173. .m_slots = winapi_slots,
  2174. .m_traverse = winapi_traverse,
  2175. .m_clear = winapi_clear,
  2176. .m_free = winapi_free,
  2177. };
  2178. PyMODINIT_FUNC
  2179. PyInit__winapi(void)
  2180. {
  2181. return PyModuleDef_Init(&winapi_module);
  2182. }