-
Notifications
You must be signed in to change notification settings - Fork 675
/
Copy pathPyDebugAttach.cpp
1706 lines (1453 loc) · 68.5 KB
/
PyDebugAttach.cpp
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
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
// PyDebugAttach.cpp : Defines the exported functions for the DLL application.
//
#include "stdafx.h"
#include "PyDebugAttach.h"
#include "..\VsPyProf\python.h"
#include <algorithm>
// _Always_ is not defined for all versions, so make it a no-op if missing.
#ifndef _Always_
#define _Always_(x) x
#endif
using namespace std;
typedef int (Py_IsInitialized)();
typedef void (PyEval_Lock)(); // Acquire/Release lock
typedef void (PyThreadState_API)(PyThreadState *); // Acquire/Release lock
typedef PyInterpreterState* (PyInterpreterState_Head)();
typedef PyThreadState* (PyInterpreterState_ThreadHead)(PyInterpreterState* interp);
typedef PyThreadState* (PyThreadState_Next)(PyThreadState *tstate);
typedef PyThreadState* (PyThreadState_Swap)(PyThreadState *tstate);
typedef PyThreadState* (_PyThreadState_UncheckedGet)();
typedef PyObject* (PyDict_New)();
typedef PyObject* (PyModule_New)(const char *name);
typedef PyObject* (PyModule_GetDict)(PyObject *module);
typedef PyObject* (Py_CompileString)(const char *str, const char *filename, int start);
typedef PyObject* (PyEval_EvalCode)(PyObject *co, PyObject *globals, PyObject *locals);
typedef PyObject* (PyDict_GetItemString)(PyObject *p, const char *key);
typedef PyObject* (PyObject_CallFunctionObjArgs)(PyObject *callable, ...); // call w/ varargs, last arg should be NULL
typedef PyObject* (PyEval_GetBuiltins)();
typedef int (PyDict_SetItemString)(PyObject *dp, const char *key, PyObject *item);
typedef int (PyEval_ThreadsInitialized)();
typedef void (Py_AddPendingCall)(int (*func)(void *), void*);
typedef PyObject* (PyInt_FromLong)(long);
typedef PyObject* (PyString_FromString)(const char* s);
typedef void PyEval_SetTrace(Py_tracefunc func, PyObject *obj);
typedef void (PyErr_Restore)(PyObject *type, PyObject *value, PyObject *traceback);
typedef void (PyErr_Fetch)(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback);
typedef PyObject* (PyErr_Occurred)();
typedef PyObject* (PyErr_Print)();
typedef PyObject* (PyImport_ImportModule) (const char *name);
typedef PyObject* (PyObject_GetAttrString)(PyObject *o, const char *attr_name);
typedef PyObject* (PyObject_SetAttrString)(PyObject *o, const char *attr_name, PyObject* value);
typedef PyObject* (PyBool_FromLong)(long v);
typedef enum { PyGILState_LOCKED, PyGILState_UNLOCKED } PyGILState_STATE;
typedef PyGILState_STATE(PyGILState_Ensure)();
typedef void (PyGILState_Release)(PyGILState_STATE);
typedef unsigned long (_PyEval_GetSwitchInterval)(void);
typedef void (_PyEval_SetSwitchInterval)(unsigned long microseconds);
typedef void* (PyThread_get_key_value)(int);
typedef int (PyThread_set_key_value)(int, void*);
typedef void (PyThread_delete_key_value)(int);
typedef PyGILState_STATE PyGILState_EnsureFunc(void);
typedef void PyGILState_ReleaseFunc(PyGILState_STATE);
typedef PyObject* PyInt_FromSize_t(size_t ival);
typedef PyThreadState *PyThreadState_NewFunc(PyInterpreterState *interp);
typedef PyObject* PyObject_Repr(PyObject*);
typedef size_t PyUnicode_AsWideChar(PyObject *unicode, wchar_t *w, size_t size);
class PyObjectHolder;
PyObject* GetPyObjectPointerNoDebugInfo(bool isDebug, PyObject* object);
void DecRef(PyObject* object, bool isDebug);
void IncRef(PyObject* object, bool isDebug);
#define MAX_INTERPRETERS 10
// Helper class so we can use RAII for freeing python objects when they go out of scope
class PyObjectHolder {
private:
PyObject* _object;
public:
bool _isDebug;
PyObjectHolder(bool isDebug) {
_object = nullptr;
_isDebug = isDebug;
}
PyObjectHolder(bool isDebug, PyObject *object) {
_object = object;
_isDebug = isDebug;
};
PyObjectHolder(bool isDebug, PyObject *object, bool addRef) {
_object = object;
_isDebug = isDebug;
if (_object != nullptr && addRef) {
GetPyObjectPointerNoDebugInfo(_isDebug, _object)->ob_refcnt++;
}
};
PyObject* ToPython() {
return _object;
}
~PyObjectHolder() {
DecRef(_object, _isDebug);
}
PyObject* operator* () {
return GetPyObjectPointerNoDebugInfo(_isDebug, _object);
}
};
class InterpreterInfo {
public:
InterpreterInfo(HMODULE module, bool debug) :
Interpreter(module),
CurrentThread(nullptr),
CurrentThreadGetter(nullptr),
NewThreadFunction(nullptr),
PyGILState_Ensure(nullptr),
Version(PythonVersion_Unknown),
Call(nullptr),
IsDebug(debug),
SetTrace(nullptr),
PyThreadState_New(nullptr),
ThreadState_Swap(nullptr) {
}
~InterpreterInfo() {
if (NewThreadFunction != nullptr) {
delete NewThreadFunction;
}
}
PyObjectHolder* NewThreadFunction;
PyThreadState** CurrentThread;
_PyThreadState_UncheckedGet *CurrentThreadGetter;
HMODULE Interpreter;
PyGILState_EnsureFunc* PyGILState_Ensure;
PyEval_SetTrace* SetTrace;
PyThreadState_NewFunc* PyThreadState_New;
PyThreadState_Swap* ThreadState_Swap;
PythonVersion GetVersion() {
if (Version == PythonVersion_Unknown) {
Version = ::GetPythonVersion(Interpreter);
}
return Version;
}
PyObject_CallFunctionObjArgs* GetCall() {
if (Call == nullptr) {
Call = (PyObject_CallFunctionObjArgs*)GetProcAddress(Interpreter, "PyObject_CallFunctionObjArgs");
}
return Call;
}
bool EnsureSetTrace() {
if (SetTrace == nullptr) {
auto setTrace = (PyEval_SetTrace*)(void*)GetProcAddress(Interpreter, "PyEval_SetTrace");
SetTrace = setTrace;
}
return SetTrace != nullptr;
}
bool EnsureThreadStateSwap() {
if (ThreadState_Swap == nullptr) {
auto swap = (PyThreadState_Swap*)(void*)GetProcAddress(Interpreter, "PyThreadState_Swap");
ThreadState_Swap = swap;
}
return ThreadState_Swap != nullptr;
}
bool EnsureCurrentThread() {
if (CurrentThread == nullptr && CurrentThreadGetter == nullptr) {
CurrentThreadGetter = (_PyThreadState_UncheckedGet*)GetProcAddress(Interpreter, "_PyThreadState_UncheckedGet");
CurrentThread = (PyThreadState**)(void*)GetProcAddress(Interpreter, "_PyThreadState_Current");
}
return CurrentThread != nullptr || CurrentThreadGetter != nullptr;
}
PyThreadState *GetCurrentThread() {
return CurrentThreadGetter ? CurrentThreadGetter() : *CurrentThread;
}
private:
PythonVersion Version;
PyObject_CallFunctionObjArgs* Call;
bool IsDebug;
};
DWORD _interpreterCount = 0;
InterpreterInfo* _interpreterInfo[MAX_INTERPRETERS];
void PatchIAT(PIMAGE_DOS_HEADER dosHeader, PVOID replacingFunc, LPSTR exportingDll, LPVOID newFunction) {
if (dosHeader->e_magic != IMAGE_DOS_SIGNATURE) {
return;
}
auto ntHeader = (IMAGE_NT_HEADERS*)(((BYTE*)dosHeader) + dosHeader->e_lfanew);
if (ntHeader->Signature != IMAGE_NT_SIGNATURE) {
return;
}
auto importAddr = ntHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress;
if (importAddr == 0) {
return;
}
auto import = (PIMAGE_IMPORT_DESCRIPTOR)(importAddr + ((BYTE*)dosHeader));
while (import->Name) {
char* name = (char*)(import->Name + ((BYTE*)dosHeader));
if (_stricmp(name, exportingDll) == 0) {
auto thunkData = (PIMAGE_THUNK_DATA)((import->FirstThunk) + ((BYTE*)dosHeader));
while (thunkData->u1.Function) {
PVOID funcAddr = (char*)(thunkData->u1.Function);
if (funcAddr == replacingFunc) {
DWORD flOldProtect;
if (VirtualProtect(&thunkData->u1, sizeof(SIZE_T), PAGE_READWRITE, &flOldProtect)) {
thunkData->u1.Function = (SIZE_T)newFunction;
VirtualProtect(&thunkData->u1, sizeof(SIZE_T), flOldProtect, &flOldProtect);
}
}
thunkData++;
}
}
import++;
}
}
typedef BOOL WINAPI EnumProcessModulesFunc(
__in HANDLE hProcess,
__out HMODULE *lphModule,
__in DWORD cb,
__out LPDWORD lpcbNeeded
);
typedef __kernel_entry NTSTATUS NTAPI
NtQueryInformationProcessFunc(
IN HANDLE ProcessHandle,
IN PROCESSINFOCLASS ProcessInformationClass,
OUT PVOID ProcessInformation,
IN ULONG ProcessInformationLength,
OUT PULONG ReturnLength OPTIONAL
);
// This function will work with Win7 and later versions of the OS and is safe to call under
// the loader lock (all APIs used are in kernel32).
BOOL PatchFunction(LPSTR exportingDll, PVOID replacingFunc, LPVOID newFunction) {
HANDLE hProcess = GetCurrentProcess();
DWORD modSize = sizeof(HMODULE) * 1024;
HMODULE* hMods = (HMODULE*)_malloca(modSize);
DWORD modsNeeded = 0;
if (hMods == nullptr) {
modsNeeded = 0;
return FALSE;
}
#pragma warning(push)
#pragma warning(disable:6263) // Using _alloca in a loop: this can quickly overflow stack. Note that this is _malloca, not _alloca, and will allocate on heap if needed.
while (!EnumProcessModules(hProcess, hMods, modSize, &modsNeeded)) {
// try again w/ more space...
_freea(hMods);
hMods = (HMODULE*)_malloca(modsNeeded);
if (hMods == nullptr) {
modsNeeded = 0;
break;
}
modSize = modsNeeded;
}
#pragma warning(pop)
for (DWORD tmp = 0; tmp < modsNeeded / sizeof(HMODULE); tmp++) {
PIMAGE_DOS_HEADER dosHeader = (PIMAGE_DOS_HEADER)hMods[tmp];
PatchIAT(dosHeader, replacingFunc, exportingDll, newFunction);
}
if (hMods != nullptr) {
_freea(hMods);
}
return TRUE;
}
wstring GetCurrentModuleFilename() {
HMODULE hModule = NULL;
if (GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCTSTR)GetCurrentModuleFilename, &hModule) != 0) {
wchar_t filename[MAX_PATH];
GetModuleFileName(hModule, filename, MAX_PATH);
return filename;
}
return wstring();
}
struct AttachInfo {
PyEval_Lock* InitThreads;
HANDLE Event;
};
HANDLE g_initedEvent;
int AttachCallback(void *initThreads) {
// initialize us for threading, this will acquire the GIL if not already created, and is a nop if the GIL is created.
// This leaves us in the proper state when we return back to the runtime whether the GIL was created or not before
// we were called.
((PyEval_Lock*)initThreads)();
SetEvent(g_initedEvent);
return 0;
}
bool ReadCodeFromFile(wchar_t* filePath, string& fileContents) {
ifstream filestr;
filestr.open(filePath, ios::binary);
if (filestr.fail()) {
return false;
}
copy_if(istreambuf_iterator<char>(filestr), {}, back_inserter(fileContents), [](auto ch) { return ch != '\r'; });
return true;
}
// create a custom heap for our unordered map. This is necessary because if we suspend a thread while in a heap function
// then we could deadlock here. We need to be VERY careful about what we do while the threads are suspended.
static HANDLE g_heap = 0;
template<typename T>
class PrivateHeapAllocator {
public:
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef T value_type;
template<class U>
struct rebind {
typedef PrivateHeapAllocator<U> other;
};
explicit PrivateHeapAllocator() {}
PrivateHeapAllocator(PrivateHeapAllocator const&) {}
~PrivateHeapAllocator() {}
template<typename U>
PrivateHeapAllocator(PrivateHeapAllocator<U> const&) {}
pointer allocate(size_type size, allocator<void>::const_pointer hint = 0) {
UNREFERENCED_PARAMETER(hint);
g_heap = (g_heap == nullptr) ? HeapCreate(0, 0, 0) : g_heap;
if (g_heap != nullptr)
{
auto mem = HeapAlloc(g_heap, 0, size * sizeof(T));
return static_cast<pointer>(mem);
}
return nullptr;
}
void deallocate(pointer p, size_type n) {
UNREFERENCED_PARAMETER(n);
HeapFree(g_heap, 0, p);
}
size_type max_size() const {
return (std::numeric_limits<size_type>::max)() / sizeof(T);
}
void construct(pointer p, const T& t) {
new(p) T(t);
}
void destroy(pointer p) {
p->~T();
}
};
typedef unordered_map<DWORD, HANDLE, std::hash<DWORD>, std::equal_to<DWORD>, PrivateHeapAllocator<pair<DWORD, HANDLE>>> ThreadMap;
void ResumeThreads(ThreadMap &suspendedThreads) {
for (auto start = suspendedThreads.begin(); start != suspendedThreads.end(); start++) {
ResumeThread((*start).second);
CloseHandle((*start).second);
}
suspendedThreads.clear();
}
// Suspends all threads ensuring that they are not currently in a call to Py_AddPendingCall.
void SuspendThreads(ThreadMap &suspendedThreads, Py_AddPendingCall* addPendingCall, PyEval_ThreadsInitialized* threadsInited) {
DWORD curThreadId = GetCurrentThreadId();
DWORD curProcess = GetCurrentProcessId();
// suspend all the threads in the process so we can do things safely...
bool suspended;
do {
suspended = false;
HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if (h != INVALID_HANDLE_VALUE) {
THREADENTRY32 te;
memset(&te, 0, sizeof(te));
te.dwSize = sizeof(te);
if (Thread32First(h, &te)) {
do {
if (te.dwSize >= FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID) + sizeof(te.th32OwnerProcessID) && te.th32OwnerProcessID == curProcess) {
if (te.th32ThreadID != curThreadId && suspendedThreads.find(te.th32ThreadID) == suspendedThreads.end()) {
HANDLE hThreadToSuspend = OpenThread(THREAD_ALL_ACCESS, FALSE, te.th32ThreadID);
if (hThreadToSuspend != nullptr) {
SuspendThread(hThreadToSuspend);
bool addingPendingCall = false;
CONTEXT context;
memset(&context, 0x00, sizeof(CONTEXT));
context.ContextFlags = CONTEXT_ALL;
GetThreadContext(hThreadToSuspend, &context);
#if defined(_X86_)
if(context.Eip >= *((DWORD*)addPendingCall) && context.Eip <= (*((DWORD*)addPendingCall)) + 0x100) {
addingPendingCall = true;
}
#elif defined(_AMD64_)
if (context.Rip >= *((DWORD64*)addPendingCall) && context.Rip <= *((DWORD64*)addPendingCall + 0x100)) {
addingPendingCall = true;
}
#endif
if (addingPendingCall) {
// we appear to be adding a pending call via this thread - wait for this to finish so we can add our own pending call...
ResumeThread(hThreadToSuspend);
SwitchToThread(); // yield to the resumed thread if it's on our CPU...
CloseHandle(hThreadToSuspend);
hThreadToSuspend = nullptr;
} else {
suspendedThreads[te.th32ThreadID] = hThreadToSuspend;
}
suspended = true;
}
}
}
te.dwSize = sizeof(te);
} while (Thread32Next(h, &te) && !threadsInited());
}
CloseHandle(h);
}
} while (suspended && !threadsInited());
}
PyObject* GetPyObjectPointerNoDebugInfo(bool isDebug, PyObject* object) {
if (object != nullptr && isDebug) {
// debug builds have 2 extra pointers at the front that we don't care about
return (PyObject*)((size_t*)object + 2);
}
return object;
}
void DecRef(PyObject* object, bool isDebug) {
auto noDebug = GetPyObjectPointerNoDebugInfo(isDebug, object);
if (noDebug != nullptr && --noDebug->ob_refcnt == 0) {
((PyTypeObject*)GetPyObjectPointerNoDebugInfo(isDebug, noDebug->ob_type))->tp_dealloc(object);
}
}
void IncRef(PyObject* object) {
object->ob_refcnt++;
}
#pragma warning(push)
#pragma warning(disable:4324) // 'MemoryBuffer': structure was padded due to alignment specifier
// Structure for our shared memory communication, aligned to be identical on 64-bit and 32-bit
struct MemoryBuffer {
int32_t PortNumber; // offset 0-4
unsigned : 4; // offset 4-8 (padding)
__declspec(align(8)) HANDLE AttachStartingEvent; // offset 8-16
__declspec(align(8)) HANDLE AttachDoneEvent; // offset 16-24
__declspec(align(8)) int32_t ErrorNumber; // offset 24-28
int32_t VersionNumber; // offset 28-32
char DebugId[64]; // null terminated string
char DebugOptions[1]; // null terminated string (VLA)
};
#pragma warning(pop)
class ConnectionInfo {
public:
HANDLE FileMapping;
MemoryBuffer *Buffer;
bool Succeeded;
ConnectionInfo() :
Succeeded(false), Buffer(nullptr), FileMapping(nullptr) {
}
ConnectionInfo(MemoryBuffer *memoryBuffer, HANDLE fileMapping) :
Succeeded(true), Buffer(memoryBuffer), FileMapping(fileMapping) {
}
// Reports an error while we're initially setting up the attach. These errors can all be
// reported quickly and are reported across the shared memory buffer.
void ReportError(int errorNum) {
Buffer->ErrorNumber = errorNum;
}
// Reports an error after we've started the attach via our socket. These are errors which
// may take a while to get to because the GIL is held and we cannot continue with the attach.
// Because the UI for attach is gone by the time we report this error it gets reported
// in the debug output pane.
// These errors should also be extremely rare - for example a broken PTVS install, or a broken
// Python interpreter. We'd much rather give the user a message box error earlier than the
// error logged in the output window which they might miss.
void ReportErrorAfterAttachDone(DWORD errorNum) {
WSADATA data;
if (!WSAStartup(MAKEWORD(2, 0), &data)) {
auto sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock != INVALID_SOCKET) {
sockaddr_in serveraddr = {0};
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
serveraddr.sin_port = htons(static_cast<u_short>(Buffer->PortNumber));
// connect to our DebugConnectionListener and report the error.
if (connect(sock, (sockaddr*)&serveraddr, sizeof(sockaddr_in)) == 0) {
// send our debug ID as an ASCII string.
send(sock, "A", 1, 0);
int len = (int)strlen(Buffer->DebugId);
unsigned long long lenBE64 = _byteswap_uint64(len);
send(sock, (const char*)&lenBE64, sizeof(lenBE64), 0);
send(sock, Buffer->DebugId, (int)len, 0);
// send our error number
unsigned long long errorNumBE64 = _byteswap_uint64(errorNum);
send(sock, (const char*)&errorNumBE64, sizeof(errorNumBE64), 0);
}
}
}
}
void SetVersion(PythonVersion version) {
Buffer->VersionNumber = version;
}
~ConnectionInfo() {
if (Succeeded) {
CloseHandle(Buffer->AttachStartingEvent);
auto attachDoneEvent = Buffer->AttachDoneEvent;
UnmapViewOfFile(Buffer);
CloseHandle(FileMapping);
// we may set this multiple times, but that doesn't matter...
SetEvent(attachDoneEvent);
CloseHandle(attachDoneEvent);
}
}
};
ConnectionInfo GetConnectionInfo() {
HANDLE hMapFile;
char* pBuf;
wchar_t fullMappingName[1024];
_snwprintf_s(fullMappingName, sizeof(fullMappingName) / sizeof(fullMappingName[0]), L"PythonDebuggerMemory%d", (int)GetCurrentProcessId());
hMapFile = OpenFileMapping(
FILE_MAP_ALL_ACCESS, // read/write access
FALSE, // do not inherit the name
fullMappingName); // name of mapping object
if (hMapFile == NULL) {
return ConnectionInfo();
}
pBuf = (char*)MapViewOfFile(hMapFile, // handle to map object
FILE_MAP_ALL_ACCESS, // read/write permission
0,
0,
1024);
if (pBuf == NULL) {
CloseHandle(hMapFile);
return ConnectionInfo();
}
return ConnectionInfo((MemoryBuffer*)pBuf, hMapFile);
}
// Error messages - must be kept in sync with ConnErrorMessages.cs
enum ConnErrorMessages {
ConnError_None,
ConnError_InterpreterNotInitialized,
ConnError_UnknownVersion,
ConnError_LoadDebuggerFailed,
ConnError_LoadDebuggerBadDebugger,
ConnError_PythonNotFound,
ConnError_TimeOut,
ConnError_CannotOpenProcess,
ConnError_OutOfMemory,
ConnError_CannotInjectThread,
ConnError_SysNotFound,
ConnError_SysSetTraceNotFound,
ConnError_SysGetTraceNotFound,
ConnError_PyDebugAttachNotFound,
ConnError_RemoteNetworkError,
ConnError_RemoteSslError,
ConnError_RemoteUnsupportedServer,
ConnError_RemoteSecretMismatch,
ConnError_RemoteAttachRejected,
ConnError_RemoteInvalidUri,
ConnError_RemoteUnsupportedTransport,
ConnError_UnsupportedVersion
};
// Ensures handles are closed when they go out of scope
class HandleHolder {
HANDLE _handle;
public:
HandleHolder(HANDLE handle) : _handle(handle) {
}
~HandleHolder() {
CloseHandle(_handle);
}
};
DWORD GetPythonThreadId(PythonVersion version, PyThreadState* curThread) {
DWORD threadId = 0;
if (PyThreadState_25_27::IsFor(version)) {
threadId = (DWORD)((PyThreadState_25_27*)curThread)->thread_id;
} else if (PyThreadState_30_33::IsFor(version)) {
threadId = (DWORD)((PyThreadState_30_33*)curThread)->thread_id;
} else if (PyThreadState_34_36::IsFor(version)) {
threadId = (DWORD)((PyThreadState_34_36*)curThread)->thread_id;
} else if (PyThreadState_37_39::IsFor(version)) {
threadId = (DWORD)((PyThreadState_37_39*)curThread)->thread_id;
} else if (PyThreadState_310::IsFor(version)) {
threadId = (DWORD)((PyThreadState_310*)curThread)->thread_id;
}
return threadId;
}
// holder to ensure we release the GIL even in error conditions
class GilHolder {
PyGILState_STATE _gilState;
PyGILState_Release* _release;
public:
GilHolder(PyGILState_Ensure* acquire, PyGILState_Release* release) {
_gilState = acquire();
_release = release;
}
~GilHolder() {
_release(_gilState);
}
};
bool LoadAndEvaluateCode(
wchar_t* filePath, const char* fileName, ConnectionInfo& connInfo, bool isDebug, PyObject* globalsDict,
Py_CompileString* pyCompileString, PyDict_SetItemString* dictSetItem,
PyEval_EvalCode* pyEvalCode, PyString_FromString* strFromString, PyEval_GetBuiltins* getBuiltins,
PyErr_Print pyErrPrint
) {
string fileContents;
if (!ReadCodeFromFile(filePath, fileContents))
{
connInfo.ReportErrorAfterAttachDone(ConnError_LoadDebuggerFailed);
return false;
}
auto debuggerCode = fileContents.data();
auto code = PyObjectHolder(isDebug, pyCompileString(debuggerCode, fileName, 257 /*Py_file_input*/));
if (*code == nullptr) {
connInfo.ReportErrorAfterAttachDone(ConnError_LoadDebuggerFailed);
return false;
}
dictSetItem(globalsDict, "__builtins__", getBuiltins());
auto size = WideCharToMultiByte(CP_UTF8, 0, filePath, (DWORD)wcslen(filePath), NULL, 0, NULL, NULL);
char* filenameBuffer = new char[size + 1];
if (WideCharToMultiByte(CP_UTF8, 0, filePath, (DWORD)wcslen(filePath), filenameBuffer, size, NULL, NULL) != 0) {
filenameBuffer[size] = 0;
dictSetItem(globalsDict, "__file__", strFromString(filenameBuffer));
}
auto evalResult = PyObjectHolder(isDebug, pyEvalCode(code.ToPython(), globalsDict, globalsDict));
#if !NDEBUG
if (*evalResult == nullptr) {
pyErrPrint();
}
#else
UNREFERENCED_PARAMETER(pyErrPrint);
#endif
return true;
}
bool DoAttach(HMODULE module, ConnectionInfo& connInfo, bool isDebug) {
// Python DLL?
auto isInit = (Py_IsInitialized*)GetProcAddress(module, "Py_IsInitialized");
if (isInit != nullptr && isInit()) {
DWORD interpreterId = INFINITE;
for (DWORD curInterp = 0; curInterp < MAX_INTERPRETERS; curInterp++) {
if (_interpreterInfo[curInterp] != nullptr &&
_interpreterInfo[curInterp]->Interpreter == module) {
interpreterId = curInterp;
break;
}
}
if (interpreterId == INFINITE) {
connInfo.ReportError(ConnError_UnknownVersion);
return FALSE;
}
auto version = GetPythonVersion(module);
// found initialized Python runtime, gather and check the APIs we need for a successful attach...
auto addPendingCall = (Py_AddPendingCall*)GetProcAddress(module, "Py_AddPendingCall");
auto interpHead = (PyInterpreterState_Head*)GetProcAddress(module, "PyInterpreterState_Head");
auto gilEnsure = (PyGILState_Ensure*)GetProcAddress(module, "PyGILState_Ensure");
auto gilRelease = (PyGILState_Release*)GetProcAddress(module, "PyGILState_Release");
auto threadHead = (PyInterpreterState_ThreadHead*)GetProcAddress(module, "PyInterpreterState_ThreadHead");
auto initThreads = (PyEval_Lock*)GetProcAddress(module, "PyEval_InitThreads");
auto releaseLock = (PyEval_Lock*)GetProcAddress(module, "PyEval_ReleaseLock");
auto threadsInited = (PyEval_ThreadsInitialized*)GetProcAddress(module, "PyEval_ThreadsInitialized");
auto threadNext = (PyThreadState_Next*)GetProcAddress(module, "PyThreadState_Next");
auto threadSwap = (PyThreadState_Swap*)GetProcAddress(module, "PyThreadState_Swap");
auto pyDictNew = (PyDict_New*)GetProcAddress(module, "PyDict_New");
auto pyCompileString = (Py_CompileString*)GetProcAddress(module, "Py_CompileString");
auto pyEvalCode = (PyEval_EvalCode*)GetProcAddress(module, "PyEval_EvalCode");
auto getDictItem = (PyDict_GetItemString*)GetProcAddress(module, "PyDict_GetItemString");
auto call = (PyObject_CallFunctionObjArgs*)GetProcAddress(module, "PyObject_CallFunctionObjArgs");
auto getBuiltins = (PyEval_GetBuiltins*)GetProcAddress(module, "PyEval_GetBuiltins");
auto dictSetItem = (PyDict_SetItemString*)GetProcAddress(module, "PyDict_SetItemString");
PyInt_FromLong* intFromLong;
PyString_FromString* strFromString;
PyInt_FromSize_t* intFromSizeT;
if (version >= PythonVersion_30) {
intFromLong = (PyInt_FromLong*)GetProcAddress(module, "PyLong_FromLong");
intFromSizeT = (PyInt_FromSize_t*)GetProcAddress(module, "PyLong_FromSize_t");
if (version >= PythonVersion_33) {
strFromString = (PyString_FromString*)GetProcAddress(module, "PyUnicode_FromString");
} else {
strFromString = (PyString_FromString*)GetProcAddress(module, "PyUnicodeUCS2_FromString");
}
} else {
intFromLong = (PyInt_FromLong*)GetProcAddress(module, "PyInt_FromLong");
strFromString = (PyString_FromString*)GetProcAddress(module, "PyString_FromString");
intFromSizeT = (PyInt_FromSize_t*)GetProcAddress(module, "PyInt_FromSize_t");
}
auto errOccurred = (PyErr_Occurred*)GetProcAddress(module, "PyErr_Occurred");
auto pyErrFetch = (PyErr_Fetch*)GetProcAddress(module, "PyErr_Fetch");
auto pyErrRestore = (PyErr_Restore*)GetProcAddress(module, "PyErr_Restore");
auto pyErrPrint = (PyErr_Print*)GetProcAddress(module, "PyErr_Print");
auto pyImportMod = (PyImport_ImportModule*) GetProcAddress(module, "PyImport_ImportModule");
auto pyGetAttr = (PyObject_GetAttrString*)GetProcAddress(module, "PyObject_GetAttrString");
auto pySetAttr = (PyObject_SetAttrString*)GetProcAddress(module, "PyObject_SetAttrString");
auto pyNone = (PyObject*)GetProcAddress(module, "_Py_NoneStruct");
auto boolFromLong = (PyBool_FromLong*)GetProcAddress(module, "PyBool_FromLong");
auto getThreadTls = (PyThread_get_key_value*)GetProcAddress(module, "PyThread_get_key_value");
auto setThreadTls = (PyThread_set_key_value*)GetProcAddress(module, "PyThread_set_key_value");
auto delThreadTls = (PyThread_delete_key_value*)GetProcAddress(module, "PyThread_delete_key_value");
auto PyCFrame_Type = (PyTypeObject*)GetProcAddress(module, "PyCFrame_Type");
auto pyObjectRepr = (PyObject_Repr*)GetProcAddress(module, "PyObject_Repr");
auto pyUnicodeAsWideChar = (PyUnicode_AsWideChar*)GetProcAddress(module,
version < PythonVersion_33 ? "PyUnicodeUCS2_AsWideChar" : "PyUnicode_AsWideChar");
// Either _PyThreadState_Current or _PyThreadState_UncheckedGet are required
auto curPythonThread = (PyThreadState**)(void*)GetProcAddress(module, "_PyThreadState_Current");
auto getPythonThread = (_PyThreadState_UncheckedGet*)GetProcAddress(module, "_PyThreadState_UncheckedGet");
// Either _Py_CheckInterval or _PyEval_[GS]etSwitchInterval are useful, but not required
auto intervalCheck = (int*)GetProcAddress(module, "_Py_CheckInterval");
auto getSwitchInterval = (_PyEval_GetSwitchInterval*)GetProcAddress(module, "_PyEval_GetSwitchInterval");
auto setSwitchInterval = (_PyEval_SetSwitchInterval*)GetProcAddress(module, "_PyEval_SetSwitchInterval");
if (addPendingCall == nullptr || interpHead == nullptr || gilEnsure == nullptr || gilRelease == nullptr || threadHead == nullptr ||
initThreads == nullptr || releaseLock == nullptr || threadsInited == nullptr || threadNext == nullptr || threadSwap == nullptr ||
pyDictNew == nullptr || pyCompileString == nullptr || pyEvalCode == nullptr || getDictItem == nullptr || call == nullptr ||
getBuiltins == nullptr || dictSetItem == nullptr || intFromLong == nullptr || pyErrRestore == nullptr || pyErrFetch == nullptr ||
errOccurred == nullptr || pyImportMod == nullptr || pyGetAttr == nullptr || pyNone == nullptr || pySetAttr == nullptr || boolFromLong == nullptr ||
getThreadTls == nullptr || setThreadTls == nullptr || delThreadTls == nullptr || pyObjectRepr == nullptr || pyUnicodeAsWideChar == nullptr ||
(curPythonThread == nullptr && getPythonThread == nullptr)) {
// we're missing some APIs, we cannot attach.
connInfo.ReportError(ConnError_PythonNotFound);
return false;
}
auto head = interpHead();
if (head == nullptr) {
// this interpreter is loaded but not initialized.
connInfo.ReportError(ConnError_InterpreterNotInitialized);
return false;
}
bool threadSafeAddPendingCall = false;
// check that we're a supported version
if (version == PythonVersion_Unknown) {
connInfo.ReportError(ConnError_UnknownVersion);
return false;
} else if (version < PythonVersion_26) {
connInfo.ReportError(ConnError_UnsupportedVersion);
return false;
} else if (version >= PythonVersion_27 && version != PythonVersion_30) {
threadSafeAddPendingCall = true;
}
connInfo.SetVersion(version);
// we know everything we need for VS to continue the attach.
connInfo.ReportError(ConnError_None);
SetEvent(connInfo.Buffer->AttachStartingEvent);
if (!threadsInited()) {
int saveIntervalCheck;
unsigned long saveLongIntervalCheck;
if (intervalCheck != nullptr) {
// not available on 3.2
saveIntervalCheck = *intervalCheck;
*intervalCheck = -1; // lower the interval check so pending calls are processed faster
saveLongIntervalCheck = 0; // prevent compiler warning
} else if (getSwitchInterval != nullptr && setSwitchInterval != nullptr) {
saveLongIntervalCheck = getSwitchInterval();
setSwitchInterval(0);
saveIntervalCheck = 0; // prevent compiler warning
}
else {
saveIntervalCheck = 0; // prevent compiler warning
saveLongIntervalCheck = 0; // prevent compiler warning
}
//
// Multiple thread support has not been initialized in the interpreter. We need multi threading support
// to block any actively running threads and setup the debugger attach state.
//
// We need to initialize multiple threading support but we need to do so safely. One option is to call
// Py_AddPendingCall and have our callback then initialize multi threading. This is completely safe on 2.7
// and up. Unfortunately that doesn't work if we're not actively running code on the main thread (blocked on a lock
// or reading input). It's also not thread safe pre-2.7 so we need to make sure it's safe to call on down-level
// interpreters.
//
// Another option is to make sure no code is running - if there is no active thread then we can safely call
// PyEval_InitThreads and we're in business. But to know this is safe we need to first suspend all the other
// threads in the process and then inspect if any code is running.
//
// Finally if code is running after we've suspended the threads then we can go ahead and do Py_AddPendingCall
// on down-level interpreters as long as we're sure no one else is making a call to Py_AddPendingCall at the same
// time.
//
// Therefore our strategy becomes: Make the Py_AddPendingCall on interpreters where it's thread safe. Then suspend
// all threads - if a threads IP is in Py_AddPendingCall resume and try again. Once we've got all of the threads
// stopped and not in Py_AddPendingCall (which calls no functions its self, you can see this and it's size in the
// debugger) then see if we have a current thread. If not go ahead and initialize multiple threading (it's now safe,
// no Python code is running). Otherwise add the pending call and repeat. If at any point during this process
// threading becomes initialized (due to our pending call or the Python code creating a new thread) then we're done
// and we just resume all of the presently suspended threads.
ThreadMap suspendedThreads;
g_initedEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
HandleHolder holder(g_initedEvent);
bool addedPendingCall = false;
if (addPendingCall != nullptr && threadSafeAddPendingCall) {
// we're on a thread safe Python version, go ahead and pend our call to initialize threading.
addPendingCall(&AttachCallback, initThreads);
addedPendingCall = true;
}
#define TICKS_DIFF(prev, cur) ((cur) >= (prev)) ? ((cur)-(prev)) : ((0xFFFFFFFF-(prev))+(cur))
const DWORD ticksPerSecond = 1000;
ULONGLONG startTickCount = GetTickCount64();
do {
SuspendThreads(suspendedThreads, addPendingCall, threadsInited);
if (!threadsInited()) {
auto curPyThread = getPythonThread ? getPythonThread() : *curPythonThread;
if (curPyThread == nullptr) {
// no threads are currently running, it is safe to initialize multi threading.
PyGILState_STATE gilState;
if (version >= PythonVersion_34) {
// in 3.4 due to http://bugs.python.org/issue20891,
// we need to create our thread state manually
// before we can call PyGILState_Ensure() before we
// can call PyEval_InitThreads().
// Don't require this function unless we need it.
auto threadNew = (PyThreadState_NewFunc*)GetProcAddress(module, "PyThreadState_New");
if (threadNew != nullptr) {
threadNew(head);
}
}
if (version >= PythonVersion_32) {
// in 3.2 due to the new GIL and later we can't call Py_InitThreads
// without a thread being initialized.
// So we use PyGilState_Ensure here to first
// initialize the current thread, and then we use
// Py_InitThreads to bring up multi-threading.
// Some context here: http://bugs.python.org/issue11329
// http://pytools.codeplex.com/workitem/834
gilState = gilEnsure();
}
else {
gilState = PyGILState_LOCKED; // prevent compiler warning
}
initThreads();
if (version >= PythonVersion_32) {
// we will release the GIL here
gilRelease(gilState);
} else {
releaseLock();
}
} else if (!addedPendingCall) {
// someone holds the GIL but no one is actively adding any pending calls. We can pend our call
// and initialize threads.
addPendingCall(&AttachCallback, initThreads);
addedPendingCall = true;
}
}
ResumeThreads(suspendedThreads);
} while (!threadsInited() &&
(TICKS_DIFF(startTickCount, GetTickCount64())) < (ticksPerSecond * 20) &&
!addedPendingCall);
if (!threadsInited()) {
if (addedPendingCall) {
// we've added our call to initialize multi-threading, we can now wait
// until Python code actually starts running.
SetEvent(connInfo.Buffer->AttachDoneEvent);
::WaitForSingleObject(g_initedEvent, INFINITE);
} else {
connInfo.ReportError(ConnError_TimeOut);
return false;
}
} else {
SetEvent(connInfo.Buffer->AttachDoneEvent);
}
if (intervalCheck != nullptr) {
*intervalCheck = saveIntervalCheck;
} else if (setSwitchInterval != nullptr) {
setSwitchInterval(saveLongIntervalCheck);
}
} else {
SetEvent(connInfo.Buffer->AttachDoneEvent);
}
if (g_heap != nullptr) {
HeapDestroy(g_heap);
g_heap = nullptr;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// go ahead and bring in the debugger module and initialize all threads in the process...
GilHolder gilLock(gilEnsure, gilRelease); // acquire and hold the GIL until done...
auto pyTrue = boolFromLong(1);
auto pyFalse = boolFromLong(0);
auto filename = GetCurrentModuleFilename();
if (filename.length() == 0) {
return nullptr;
}
wchar_t drive[_MAX_DRIVE], dir[_MAX_DIR], file[_MAX_FNAME], ext[_MAX_EXT];
_wsplitpath_s(filename.c_str(), drive, _MAX_DRIVE, dir, _MAX_DIR, file, _MAX_FNAME, ext, _MAX_EXT);