- Notifications
You must be signed in to change notification settings - Fork 31.7k
/
Copy path_winapi.c
3240 lines (2739 loc) · 94 KB
/
_winapi.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Support routines from the Windows API
*
* This module was originally created by merging PC/_subprocess.c with
* Modules/_multiprocessing/win32_functions.c.
*
* Copyright (c) 2004 by Fredrik Lundh <fredrik@pythonware.com>
* Copyright (c) 2004 by Secret Labs AB, http://www.pythonware.com
* Copyright (c) 2004 by Peter Astrand <astrand@lysator.liu.se>
*
* By obtaining, using, and/or copying this software and/or its
* associated documentation, you agree that you have read, understood,
* and will comply with the following terms and conditions:
*
* Permission to use, copy, modify, and distribute this software and
* its associated documentation for any purpose and without fee is
* hereby granted, provided that the above copyright notice appears in
* all copies, and that both that copyright notice and this permission
* notice appear in supporting documentation, and that the name of the
* authors not be used in advertising or publicity pertaining to
* distribution of the software without specific, written prior
* permission.
*
* THE AUTHORS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
* INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
* CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
* OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
/* Licensed to PSF under a Contributor Agreement. */
/* See https://www.python.org/2.4/license for licensing details. */
#include"Python.h"
#include"pycore_moduleobject.h"// _PyModule_GetState()
#include"pycore_pylifecycle.h"// _Py_IsInterpreterFinalizing()
#include"pycore_pystate.h"// _PyInterpreterState_GET
#include"pycore_unicodeobject.h"// for Argument Clinic
#ifndefWINDOWS_LEAN_AND_MEAN
# defineWINDOWS_LEAN_AND_MEAN
#endif
#include<windows.h>
#include<winioctl.h>
#include<crtdbg.h>
#include"winreparse.h"
#if defined(MS_WIN32) && !defined(MS_WIN64)
#defineHANDLE_TO_PYNUM(handle) \
PyLong_FromUnsignedLong((unsigned long) handle)
#definePYNUM_TO_HANDLE(obj) ((HANDLE)PyLong_AsUnsignedLong(obj))
#defineF_POINTER "k"
#defineT_POINTER Py_T_ULONG
#else
#defineHANDLE_TO_PYNUM(handle) \
PyLong_FromUnsignedLongLong((unsigned long long) handle)
#definePYNUM_TO_HANDLE(obj) ((HANDLE)PyLong_AsUnsignedLongLong(obj))
#defineF_POINTER "K"
#defineT_POINTER Py_T_ULONGLONG
#endif
#defineF_HANDLE F_POINTER
#defineF_DWORD "k"
#defineT_HANDLE T_POINTER
// winbase.h limits the STARTF_* flags to the desktop API as of 10.0.19041.
#ifndefSTARTF_USESHOWWINDOW
#defineSTARTF_USESHOWWINDOW 0x00000001
#endif
#ifndefSTARTF_USESIZE
#defineSTARTF_USESIZE 0x00000002
#endif
#ifndefSTARTF_USEPOSITION
#defineSTARTF_USEPOSITION 0x00000004
#endif
#ifndefSTARTF_USECOUNTCHARS
#defineSTARTF_USECOUNTCHARS 0x00000008
#endif
#ifndefSTARTF_USEFILLATTRIBUTE
#defineSTARTF_USEFILLATTRIBUTE 0x00000010
#endif
#ifndefSTARTF_RUNFULLSCREEN
#defineSTARTF_RUNFULLSCREEN 0x00000020
#endif
#ifndefSTARTF_FORCEONFEEDBACK
#defineSTARTF_FORCEONFEEDBACK 0x00000040
#endif
#ifndefSTARTF_FORCEOFFFEEDBACK
#defineSTARTF_FORCEOFFFEEDBACK 0x00000080
#endif
#ifndefSTARTF_USESTDHANDLES
#defineSTARTF_USESTDHANDLES 0x00000100
#endif
#ifndefSTARTF_USEHOTKEY
#defineSTARTF_USEHOTKEY 0x00000200
#endif
#ifndefSTARTF_TITLEISLINKNAME
#defineSTARTF_TITLEISLINKNAME 0x00000800
#endif
#ifndefSTARTF_TITLEISAPPID
#defineSTARTF_TITLEISAPPID 0x00001000
#endif
#ifndefSTARTF_PREVENTPINNING
#defineSTARTF_PREVENTPINNING 0x00002000
#endif
#ifndefSTARTF_UNTRUSTEDSOURCE
#defineSTARTF_UNTRUSTEDSOURCE 0x00008000
#endif
typedefstruct {
PyTypeObject*overlapped_type;
} WinApiState;
staticinlineWinApiState*
winapi_get_state(PyObject*module)
{
void*state=_PyModule_GetState(module);
assert(state!=NULL);
return (WinApiState*)state;
}
/*
* A Python object wrapping an OVERLAPPED structure and other useful data
* for overlapped I/O
*/
typedefstruct {
PyObject_HEAD
OVERLAPPEDoverlapped;
/* For convenience, we store the file handle too */
HANDLEhandle;
/* Whether there's I/O in flight */
intpending;
/* Whether I/O completed successfully */
intcompleted;
/* Buffer used for reading (optional) */
PyObject*read_buffer;
/* Buffer used for writing (optional) */
Py_bufferwrite_buffer;
} OverlappedObject;
#defineOverlappedObject_CAST(op) ((OverlappedObject *)(op))
/*
Note: tp_clear (overlapped_clear) is not implemented because it
requires cancelling the IO operation if it's pending and the cancellation is
quite complex and can fail (see: overlapped_dealloc).
*/
staticint
overlapped_traverse(PyObject*op, visitprocvisit, void*arg)
{
OverlappedObject*self=OverlappedObject_CAST(op);
Py_VISIT(self->read_buffer);
Py_VISIT(self->write_buffer.obj);
Py_VISIT(Py_TYPE(self));
return0;
}
staticvoid
overlapped_dealloc(PyObject*op)
{
DWORDbytes;
interr=GetLastError();
OverlappedObject*self=OverlappedObject_CAST(op);
PyObject_GC_UnTrack(self);
if (self->pending) {
if (CancelIoEx(self->handle, &self->overlapped) &&
GetOverlappedResult(self->handle, &self->overlapped, &bytes, TRUE))
{
/* The operation is no longer pending -- nothing to do. */
}
elseif (_Py_IsInterpreterFinalizing(_PyInterpreterState_GET())) {
/* The operation is still pending -- give a warning. This
will probably only happen on Windows XP. */
PyErr_SetString(PyExc_PythonFinalizationError,
"I/O operations still in flight while destroying "
"Overlapped object, the process may crash");
PyErr_FormatUnraisable("Exception ignored while deallocating "
"overlapped operation %R", self);
}
else {
/* The operation is still pending, but the process is
probably about to exit, so we need not worry too much
about memory leaks. Leaking self prevents a potential
crash. This can happen when a daemon thread is cleaned
up at exit -- see #19565. We only expect to get here
on Windows XP. */
CloseHandle(self->overlapped.hEvent);
SetLastError(err);
return;
}
}
CloseHandle(self->overlapped.hEvent);
SetLastError(err);
if (self->write_buffer.obj)
PyBuffer_Release(&self->write_buffer);
Py_CLEAR(self->read_buffer);
PyTypeObject*tp=Py_TYPE(self);
tp->tp_free(self);
Py_DECREF(tp);
}
/*[clinic input]
module _winapi
class _winapi.Overlapped "OverlappedObject *" "&OverlappedType"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=c13d3f5fd1dabb84]*/
/*[python input]
def create_converter(type_, format_unit):
name = type_ + '_converter'
# registered upon creation by CConverter's metaclass
type(name, (CConverter,), {'type': type_, 'format_unit': format_unit})
# format unit differs between platforms for these
create_converter('HANDLE', '" F_HANDLE "')
create_converter('HMODULE', '" F_HANDLE "')
create_converter('LPSECURITY_ATTRIBUTES', '" F_POINTER "')
create_converter('LPCVOID', '" F_POINTER "')
create_converter('BOOL', 'i') # F_BOOL used previously (always 'i')
create_converter('DWORD', 'k') # F_DWORD is always "k" (which is much shorter)
create_converter('UINT', 'I') # F_UINT used previously (always 'I')
class LPCWSTR_converter(Py_UNICODE_converter):
type = 'LPCWSTR'
class HANDLE_return_converter(CReturnConverter):
type = 'HANDLE'
def render(self, function, data):
self.declare(data)
self.err_occurred_if("_return_value == INVALID_HANDLE_VALUE", data)
data.return_conversion.append(
'if (_return_value == NULL) {\n Py_RETURN_NONE;\n}\n')
data.return_conversion.append(
'return_value = HANDLE_TO_PYNUM(_return_value);\n')
class DWORD_return_converter(CReturnConverter):
type = 'DWORD'
def render(self, function, data):
self.declare(data)
self.err_occurred_if("_return_value == PY_DWORD_MAX", data)
data.return_conversion.append(
'return_value = PyLong_FromUnsignedLong(_return_value);\n')
class LPVOID_return_converter(CReturnConverter):
type = 'LPVOID'
def render(self, function, data):
self.declare(data)
self.err_occurred_if("_return_value == NULL", data)
data.return_conversion.append(
'return_value = HANDLE_TO_PYNUM(_return_value);\n')
[python start generated code]*/
/*[python end generated code: output=da39a3ee5e6b4b0d input=da0a4db751936ee7]*/
#include"clinic/_winapi.c.h"
/*[clinic input]
_winapi.Overlapped.GetOverlappedResult
wait: bool
/
[clinic start generated code]*/
staticPyObject*
_winapi_Overlapped_GetOverlappedResult_impl(OverlappedObject*self, intwait)
/*[clinic end generated code: output=bdd0c1ed6518cd03 input=194505ee8e0e3565]*/
{
BOOLres;
DWORDtransferred=0;
DWORDerr;
Py_BEGIN_ALLOW_THREADS
res=GetOverlappedResult(self->handle, &self->overlapped, &transferred,
wait!=0);
Py_END_ALLOW_THREADS
err=res ? ERROR_SUCCESS : GetLastError();
switch (err) {
caseERROR_SUCCESS:
caseERROR_MORE_DATA:
caseERROR_OPERATION_ABORTED:
self->completed=1;
self->pending=0;
break;
caseERROR_IO_INCOMPLETE:
break;
default:
self->pending=0;
returnPyErr_SetExcFromWindowsErr(PyExc_OSError, err);
}
if (self->completed&&self->read_buffer!=NULL) {
assert(PyBytes_CheckExact(self->read_buffer));
if (transferred!=PyBytes_GET_SIZE(self->read_buffer) &&
_PyBytes_Resize(&self->read_buffer, transferred))
returnNULL;
}
returnPy_BuildValue("II", (unsigned) transferred, (unsigned) err);
}
/*[clinic input]
_winapi.Overlapped.getbuffer
[clinic start generated code]*/
staticPyObject*
_winapi_Overlapped_getbuffer_impl(OverlappedObject*self)
/*[clinic end generated code: output=95a3eceefae0f748 input=347fcfd56b4ceabd]*/
{
PyObject*res;
if (!self->completed) {
PyErr_SetString(PyExc_ValueError,
"can't get read buffer before GetOverlappedResult() "
"signals the operation completed");
returnNULL;
}
res=self->read_buffer ? self->read_buffer : Py_None;
returnPy_NewRef(res);
}
/*[clinic input]
_winapi.Overlapped.cancel
[clinic start generated code]*/
staticPyObject*
_winapi_Overlapped_cancel_impl(OverlappedObject*self)
/*[clinic end generated code: output=fcb9ab5df4ebdae5 input=cbf3da142290039f]*/
{
BOOLres= TRUE;
if (self->pending) {
Py_BEGIN_ALLOW_THREADS
res=CancelIoEx(self->handle, &self->overlapped);
Py_END_ALLOW_THREADS
}
/* CancelIoEx returns ERROR_NOT_FOUND if the I/O completed in-between */
if (!res&&GetLastError() !=ERROR_NOT_FOUND)
returnPyErr_SetExcFromWindowsErr(PyExc_OSError, 0);
self->pending=0;
Py_RETURN_NONE;
}
staticPyMethodDefoverlapped_methods[] = {
_WINAPI_OVERLAPPED_GETOVERLAPPEDRESULT_METHODDEF
_WINAPI_OVERLAPPED_GETBUFFER_METHODDEF
_WINAPI_OVERLAPPED_CANCEL_METHODDEF
{NULL}
};
staticPyMemberDefoverlapped_members[] = {
{"event", T_HANDLE,
offsetof(OverlappedObject, overlapped) + offsetof(OVERLAPPED, hEvent),
Py_READONLY, "overlapped event handle"},
{NULL}
};
staticPyType_Slotwinapi_overlapped_type_slots[] = {
{Py_tp_traverse, overlapped_traverse},
{Py_tp_dealloc, overlapped_dealloc},
{Py_tp_doc, "OVERLAPPED structure wrapper"},
{Py_tp_methods, overlapped_methods},
{Py_tp_members, overlapped_members},
{0,0}
};
staticPyType_Specwinapi_overlapped_type_spec= {
.name="_winapi.Overlapped",
.basicsize=sizeof(OverlappedObject),
.flags= (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_DISALLOW_INSTANTIATION |
Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_IMMUTABLETYPE),
.slots=winapi_overlapped_type_slots,
};
staticOverlappedObject*
new_overlapped(PyObject*module, HANDLEhandle)
{
WinApiState*st=winapi_get_state(module);
OverlappedObject*self=PyObject_GC_New(OverlappedObject, st->overlapped_type);
if (!self)
returnNULL;
self->handle=handle;
self->read_buffer=NULL;
self->pending=0;
self->completed=0;
memset(&self->overlapped, 0, sizeof(OVERLAPPED));
memset(&self->write_buffer, 0, sizeof(Py_buffer));
/* Manual reset, initially non-signalled */
self->overlapped.hEvent=CreateEvent(NULL, TRUE, FALSE, NULL);
PyObject_GC_Track(self);
returnself;
}
/* -------------------------------------------------------------------- */
/* windows API functions */
/*[clinic input]
_winapi.CloseHandle
handle: HANDLE
/
Close handle.
[clinic start generated code]*/
staticPyObject*
_winapi_CloseHandle_impl(PyObject*module, HANDLEhandle)
/*[clinic end generated code: output=7ad37345f07bd782 input=7f0e4ac36e0352b8]*/
{
BOOLsuccess;
Py_BEGIN_ALLOW_THREADS
success=CloseHandle(handle);
Py_END_ALLOW_THREADS
if (!success)
returnPyErr_SetFromWindowsErr(0);
Py_RETURN_NONE;
}
/*[clinic input]
_winapi.ConnectNamedPipe
handle: HANDLE
overlapped as use_overlapped: bool = False
[clinic start generated code]*/
staticPyObject*
_winapi_ConnectNamedPipe_impl(PyObject*module, HANDLEhandle,
intuse_overlapped)
/*[clinic end generated code: output=335a0e7086800671 input=a80e56e8bd370e31]*/
{
BOOLsuccess;
OverlappedObject*overlapped=NULL;
if (use_overlapped) {
overlapped=new_overlapped(module, handle);
if (!overlapped)
returnNULL;
}
Py_BEGIN_ALLOW_THREADS
success=ConnectNamedPipe(handle,
overlapped ? &overlapped->overlapped : NULL);
Py_END_ALLOW_THREADS
if (overlapped) {
interr=GetLastError();
/* Overlapped ConnectNamedPipe never returns a success code */
assert(success==0);
if (err==ERROR_IO_PENDING)
overlapped->pending=1;
elseif (err==ERROR_PIPE_CONNECTED)
SetEvent(overlapped->overlapped.hEvent);
else {
Py_DECREF(overlapped);
returnPyErr_SetFromWindowsErr(err);
}
return (PyObject*) overlapped;
}
if (!success)
returnPyErr_SetFromWindowsErr(0);
Py_RETURN_NONE;
}
/*[clinic input]
_winapi.CreateEventW -> HANDLE
security_attributes: LPSECURITY_ATTRIBUTES
manual_reset: BOOL
initial_state: BOOL
name: LPCWSTR(accept={str, NoneType})
[clinic start generated code]*/
staticHANDLE
_winapi_CreateEventW_impl(PyObject*module,
LPSECURITY_ATTRIBUTESsecurity_attributes,
BOOLmanual_reset, BOOLinitial_state,
LPCWSTRname)
/*[clinic end generated code: output=2d4c7d5852ecb298 input=4187cee28ac763f8]*/
{
HANDLEhandle;
if (PySys_Audit("_winapi.CreateEventW", "bbu", manual_reset, initial_state, name) <0) {
returnINVALID_HANDLE_VALUE;
}
Py_BEGIN_ALLOW_THREADS
handle=CreateEventW(security_attributes, manual_reset, initial_state, name);
Py_END_ALLOW_THREADS
if (handle==INVALID_HANDLE_VALUE) {
PyErr_SetFromWindowsErr(0);
}
returnhandle;
}
/*[clinic input]
_winapi.CreateFile -> HANDLE
file_name: LPCWSTR
desired_access: DWORD
share_mode: DWORD
security_attributes: LPSECURITY_ATTRIBUTES
creation_disposition: DWORD
flags_and_attributes: DWORD
template_file: HANDLE
/
[clinic start generated code]*/
staticHANDLE
_winapi_CreateFile_impl(PyObject*module, LPCWSTRfile_name,
DWORDdesired_access, DWORDshare_mode,
LPSECURITY_ATTRIBUTESsecurity_attributes,
DWORDcreation_disposition,
DWORDflags_and_attributes, HANDLEtemplate_file)
/*[clinic end generated code: output=818c811e5e04d550 input=1fa870ed1c2e3d69]*/
{
HANDLEhandle;
if (PySys_Audit("_winapi.CreateFile", "ukkkk",
file_name, desired_access, share_mode,
creation_disposition, flags_and_attributes) <0) {
returnINVALID_HANDLE_VALUE;
}
Py_BEGIN_ALLOW_THREADS
handle=CreateFileW(file_name, desired_access,
share_mode, security_attributes,
creation_disposition,
flags_and_attributes, template_file);
Py_END_ALLOW_THREADS
if (handle==INVALID_HANDLE_VALUE) {
PyErr_SetFromWindowsErr(0);
}
returnhandle;
}
/*[clinic input]
_winapi.CreateFileMapping -> HANDLE
file_handle: HANDLE
security_attributes: LPSECURITY_ATTRIBUTES
protect: DWORD
max_size_high: DWORD
max_size_low: DWORD
name: LPCWSTR
/
[clinic start generated code]*/
staticHANDLE
_winapi_CreateFileMapping_impl(PyObject*module, HANDLEfile_handle,
LPSECURITY_ATTRIBUTESsecurity_attributes,
DWORDprotect, DWORDmax_size_high,
DWORDmax_size_low, LPCWSTRname)
/*[clinic end generated code: output=6c0a4d5cf7f6fcc6 input=3dc5cf762a74dee8]*/
{
HANDLEhandle;
Py_BEGIN_ALLOW_THREADS
handle=CreateFileMappingW(file_handle, security_attributes,
protect, max_size_high, max_size_low,
name);
Py_END_ALLOW_THREADS
if (handle== NULL) {
PyObject*temp=PyUnicode_FromWideChar(name, -1);
PyErr_SetExcFromWindowsErrWithFilenameObject(PyExc_OSError, 0, temp);
Py_XDECREF(temp);
handle=INVALID_HANDLE_VALUE;
}
returnhandle;
}
/*[clinic input]
_winapi.CreateJunction
src_path: LPCWSTR
dst_path: LPCWSTR
/
[clinic start generated code]*/
staticPyObject*
_winapi_CreateJunction_impl(PyObject*module, LPCWSTRsrc_path,
LPCWSTRdst_path)
/*[clinic end generated code: output=44b3f5e9bbcc4271 input=963d29b44b9384a7]*/
{
/* Privilege adjustment */
HANDLEtoken=NULL;
struct {
TOKEN_PRIVILEGESbase;
/* overallocate by a few array elements */
LUID_AND_ATTRIBUTESprivs[4];
} tp, previousTp;
DWORDpreviousTpSize=0;
/* Reparse data buffer */
constUSHORTprefix_len=4;
USHORTprint_len=0;
USHORTrdb_size=0;
_Py_PREPARSE_DATA_BUFFERrdb=NULL;
/* Junction point creation */
HANDLEjunction=NULL;
DWORDret=0;
if (src_path==NULL||dst_path==NULL)
returnPyErr_SetFromWindowsErr(ERROR_INVALID_PARAMETER);
if (wcsncmp(src_path, L"\\??\\", prefix_len) ==0)
returnPyErr_SetFromWindowsErr(ERROR_INVALID_PARAMETER);
if (PySys_Audit("_winapi.CreateJunction", "uu", src_path, dst_path) <0) {
returnNULL;
}
/* Adjust privileges to allow rewriting directory entry as a
junction point. */
if (!OpenProcessToken(GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &token)) {
goto cleanup;
}
if (!LookupPrivilegeValue(NULL, SE_RESTORE_NAME, &tp.base.Privileges[0].Luid)) {
goto cleanup;
}
tp.base.PrivilegeCount=1;
tp.base.Privileges[0].Attributes=SE_PRIVILEGE_ENABLED;
if (!AdjustTokenPrivileges(token, FALSE, &tp.base, sizeof(previousTp),
&previousTp.base, &previousTpSize)) {
goto cleanup;
}
if (GetFileAttributesW(src_path) ==INVALID_FILE_ATTRIBUTES)
goto cleanup;
/* Store the absolute link target path length in print_len. */
print_len= (USHORT)GetFullPathNameW(src_path, 0, NULL, NULL);
if (print_len==0)
goto cleanup;
/* NUL terminator should not be part of print_len. */
--print_len;
/* REPARSE_DATA_BUFFER usage is heavily under-documented, especially for
junction points. Here's what I've learned along the way:
- A junction point has two components: a print name and a substitute
name. They both describe the link target, but the substitute name is
the physical target and the print name is shown in directory listings.
- The print name must be a native name, prefixed with "\??\".
- Both names are stored after each other in the same buffer (the
PathBuffer) and both must be NUL-terminated.
- There are four members defining their respective offset and length
inside PathBuffer: SubstituteNameOffset, SubstituteNameLength,
PrintNameOffset and PrintNameLength.
- The total size we need to allocate for the REPARSE_DATA_BUFFER, thus,
is the sum of:
- the fixed header size (REPARSE_DATA_BUFFER_HEADER_SIZE)
- the size of the MountPointReparseBuffer member without the PathBuffer
- the size of the prefix ("\??\") in bytes
- the size of the print name in bytes
- the size of the substitute name in bytes
- the size of two NUL terminators in bytes */
rdb_size=_Py_REPARSE_DATA_BUFFER_HEADER_SIZE+
sizeof(rdb->MountPointReparseBuffer) -
sizeof(rdb->MountPointReparseBuffer.PathBuffer) +
/* Two +1's for NUL terminators. */
(prefix_len+print_len+1+print_len+1) *sizeof(WCHAR);
rdb= (_Py_PREPARSE_DATA_BUFFER)PyMem_RawCalloc(1, rdb_size);
if (rdb==NULL)
goto cleanup;
rdb->ReparseTag=IO_REPARSE_TAG_MOUNT_POINT;
rdb->ReparseDataLength=rdb_size-_Py_REPARSE_DATA_BUFFER_HEADER_SIZE;
rdb->MountPointReparseBuffer.SubstituteNameOffset=0;
rdb->MountPointReparseBuffer.SubstituteNameLength=
(prefix_len+print_len) *sizeof(WCHAR);
rdb->MountPointReparseBuffer.PrintNameOffset=
rdb->MountPointReparseBuffer.SubstituteNameLength+sizeof(WCHAR);
rdb->MountPointReparseBuffer.PrintNameLength=print_len*sizeof(WCHAR);
/* Store the full native path of link target at the substitute name
offset (0). */
wcscpy(rdb->MountPointReparseBuffer.PathBuffer, L"\\??\\");
if (GetFullPathNameW(src_path, print_len+1,
rdb->MountPointReparseBuffer.PathBuffer+prefix_len,
NULL) ==0)
goto cleanup;
/* Copy everything but the native prefix to the print name offset. */
wcscpy(rdb->MountPointReparseBuffer.PathBuffer+
prefix_len+print_len+1,
rdb->MountPointReparseBuffer.PathBuffer+prefix_len);
/* Create a directory for the junction point. */
if (!CreateDirectoryW(dst_path, NULL))
goto cleanup;
junction=CreateFileW(dst_path, GENERIC_READ | GENERIC_WRITE, 0, NULL,
OPEN_EXISTING,
FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, NULL);
if (junction==INVALID_HANDLE_VALUE)
goto cleanup;
/* Make the directory entry a junction point. */
if (!DeviceIoControl(junction, FSCTL_SET_REPARSE_POINT, rdb, rdb_size,
NULL, 0, &ret, NULL))
goto cleanup;
cleanup:
ret=GetLastError();
if (previousTpSize) {
AdjustTokenPrivileges(token, FALSE, &previousTp.base, previousTpSize,
NULL, NULL);
}
if (token!=NULL)
CloseHandle(token);
if (junction!=NULL)
CloseHandle(junction);
PyMem_RawFree(rdb);
if (ret!=0)
returnPyErr_SetFromWindowsErr(ret);
Py_RETURN_NONE;
}
/*[clinic input]
_winapi.CreateMutexW -> HANDLE
security_attributes: LPSECURITY_ATTRIBUTES
initial_owner: BOOL
name: LPCWSTR(accept={str, NoneType})
[clinic start generated code]*/
staticHANDLE
_winapi_CreateMutexW_impl(PyObject*module,
LPSECURITY_ATTRIBUTESsecurity_attributes,
BOOLinitial_owner, LPCWSTRname)
/*[clinic end generated code: output=31b9ee8fc37e49a5 input=7d54b921e723254a]*/
{
HANDLEhandle;
if (PySys_Audit("_winapi.CreateMutexW", "bu", initial_owner, name) <0) {
returnINVALID_HANDLE_VALUE;
}
Py_BEGIN_ALLOW_THREADS
handle=CreateMutexW(security_attributes, initial_owner, name);
Py_END_ALLOW_THREADS
if (handle==INVALID_HANDLE_VALUE) {
PyErr_SetFromWindowsErr(0);
}
returnhandle;
}
/*[clinic input]
_winapi.CreateNamedPipe -> HANDLE
name: LPCWSTR
open_mode: DWORD
pipe_mode: DWORD
max_instances: DWORD
out_buffer_size: DWORD
in_buffer_size: DWORD
default_timeout: DWORD
security_attributes: LPSECURITY_ATTRIBUTES
/
[clinic start generated code]*/
staticHANDLE
_winapi_CreateNamedPipe_impl(PyObject*module, LPCWSTRname, DWORDopen_mode,
DWORDpipe_mode, DWORDmax_instances,
DWORDout_buffer_size, DWORDin_buffer_size,
DWORDdefault_timeout,
LPSECURITY_ATTRIBUTESsecurity_attributes)
/*[clinic end generated code: output=7d6fde93227680ba input=5bd4e4a55639ee02]*/
{
HANDLEhandle;
if (PySys_Audit("_winapi.CreateNamedPipe", "ukk",
name, open_mode, pipe_mode) <0) {
returnINVALID_HANDLE_VALUE;
}
Py_BEGIN_ALLOW_THREADS
handle=CreateNamedPipeW(name, open_mode, pipe_mode,
max_instances, out_buffer_size,
in_buffer_size, default_timeout,
security_attributes);
Py_END_ALLOW_THREADS
if (handle==INVALID_HANDLE_VALUE)
PyErr_SetFromWindowsErr(0);
returnhandle;
}
/*[clinic input]
_winapi.CreatePipe
pipe_attrs: object
Ignored internally, can be None.
size: DWORD
/
Create an anonymous pipe.
Returns a 2-tuple of handles, to the read and write ends of the pipe.
[clinic start generated code]*/
staticPyObject*
_winapi_CreatePipe_impl(PyObject*module, PyObject*pipe_attrs, DWORDsize)
/*[clinic end generated code: output=1c4411d8699f0925 input=c4f2cfa56ef68d90]*/
{
HANDLEread_pipe;
HANDLEwrite_pipe;
BOOLresult;
if (PySys_Audit("_winapi.CreatePipe", NULL) <0) {
returnNULL;
}
Py_BEGIN_ALLOW_THREADS
result=CreatePipe(&read_pipe, &write_pipe, NULL, size);
Py_END_ALLOW_THREADS
if (! result)
returnPyErr_SetFromWindowsErr(GetLastError());
returnPy_BuildValue(
"NN", HANDLE_TO_PYNUM(read_pipe), HANDLE_TO_PYNUM(write_pipe));
}
/* helpers for createprocess */
staticunsigned long
getulong(PyObject*obj, constchar*name)
{
PyObject*value;
unsigned longret;
value=PyObject_GetAttrString(obj, name);
if (! value) {
PyErr_Clear(); /* FIXME: propagate error? */
return0;
}
ret=PyLong_AsUnsignedLong(value);
Py_DECREF(value);
returnret;
}
staticHANDLE
gethandle(PyObject*obj, constchar*name)
{
PyObject*value;
HANDLEret;
value=PyObject_GetAttrString(obj, name);
if (! value) {
PyErr_Clear(); /* FIXME: propagate error? */
returnNULL;
}
if (value==Py_None)
ret=NULL;
else
ret=PYNUM_TO_HANDLE(value);
Py_DECREF(value);
returnret;
}
staticPyObject*
sortenvironmentkey(PyObject*module, PyObject*item)
{
return_winapi_LCMapStringEx_impl(NULL, LOCALE_NAME_INVARIANT,
LCMAP_UPPERCASE, item);
}
staticPyMethodDefsortenvironmentkey_def= {
"sortenvironmentkey", _PyCFunction_CAST(sortenvironmentkey), METH_O, "",
};
staticint
sort_environment_keys(PyObject*keys)
{
PyObject*keyfunc=PyCFunction_New(&sortenvironmentkey_def, NULL);
if (keyfunc==NULL) {
return-1;
}
PyObject*kwnames=Py_BuildValue("(s)", "key");
if (kwnames==NULL) {
Py_DECREF(keyfunc);
return-1;
}
PyObject*args[] = { keys, keyfunc };
PyObject*ret=PyObject_VectorcallMethod(&_Py_ID(sort), args, 1, kwnames);
Py_DECREF(keyfunc);
Py_DECREF(kwnames);
if (ret==NULL) {
return-1;
}
Py_DECREF(ret);
return0;
}
staticint
compare_string_ordinal(PyObject*str1, PyObject*str2, int*result)
{
wchar_t*s1=PyUnicode_AsWideCharString(str1, NULL);
if (s1==NULL) {
return-1;
}
wchar_t*s2=PyUnicode_AsWideCharString(str2, NULL);
if (s2==NULL) {
PyMem_Free(s1);
return-1;
}
*result=CompareStringOrdinal(s1, -1, s2, -1, TRUE);
PyMem_Free(s1);
PyMem_Free(s2);
return0;
}
staticPyObject*
dedup_environment_keys(PyObject*keys)
{
PyObject*result=PyList_New(0);
if (result==NULL) {
returnNULL;
}
// Iterate over the pre-ordered keys, check whether the current key is equal
// to the next key (ignoring case), if different, insert the current value
// into the result list. If they are equal, do nothing because we always
// want to keep the last inserted one.
for (Py_ssize_ti=0; i<PyList_GET_SIZE(keys); i++) {
PyObject*key=PyList_GET_ITEM(keys, i);
// The last key will always be kept.
if (i+1==PyList_GET_SIZE(keys)) {
if (PyList_Append(result, key) <0) {
Py_DECREF(result);
returnNULL;
}
continue;
}
PyObject*next_key=PyList_GET_ITEM(keys, i+1);
intcompare_result;
if (compare_string_ordinal(key, next_key, &compare_result) <0) {
Py_DECREF(result);
returnNULL;
}
if (compare_result==CSTR_EQUAL) {
continue;
}
if (PyList_Append(result, key) <0) {
Py_DECREF(result);
returnNULL;
}
}
returnresult;
}
staticPyObject*
normalize_environment(PyObject*environment)
{
PyObject*keys=PyMapping_Keys(environment);
if (keys==NULL) {
returnNULL;
}
if (sort_environment_keys(keys) <0) {
Py_DECREF(keys);
returnNULL;
}