-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathprocess.cpp
More file actions
1550 lines (1319 loc) Β· 58.2 KB
/
process.cpp
File metadata and controls
1550 lines (1319 loc) Β· 58.2 KB
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
#include <algorithm>
#include <cstring>
#include <dirent.h>
#include <filesystem>
#include <memory>
#include <iostream>
#include <stdexcept>
#include <string>
#include <sys/ptrace.h>
#include <sys/wait.h>
#include <utility>
#include <vector>
#include "corefile.h"
#include "logging.h"
#include "maps_parser.h"
#include "mem.h"
#include "native_frame.h"
#include "process.h"
#include "pycode.h"
#include "pycompat.h"
#include "pyframe.h"
#include "pythread.h"
#include "pytypes.h"
#include "version.h"
#include "version_detector.h"
namespace {
static const std::string PERM_MESSAGE = "Operation not permitted";
class DirectoryReader
{
public:
explicit DirectoryReader(const std::string& path)
: dir_(opendir(path.c_str()))
{
if (!dir_) {
throw std::runtime_error("Could not read the contents of " + path);
}
};
~DirectoryReader()
{
closedir(dir_);
};
std::vector<std::string> files() const
{
std::vector<std::string> files;
struct dirent* ent;
while ((ent = readdir(dir_)) != nullptr) {
if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, "..")) {
continue;
}
files.emplace_back(ent->d_name);
}
return files;
}
private:
DIR* dir_;
};
} // namespace
namespace pystack {
namespace fs = std::filesystem;
namespace {
// Helper to extract the main interpreter map from ProcessMemoryMapInfo
std::optional<VirtualMap>
getMainMap(const ProcessMemoryMapInfo& map_info)
{
return map_info.libpython ? *map_info.libpython : map_info.python;
}
} // namespace
namespace { // unnamed
struct ParsedPyVersion
{
int major;
int minor;
int patch;
const char* release_level;
int serial;
};
std::ostream&
operator<<(std::ostream& out, const ParsedPyVersion& version)
{
// Use a temporary stringstream in case `out` is using hex or showbase
std::ostringstream oss;
oss << version.major << "." << version.minor << "." << version.patch;
if (version.release_level[0]) {
oss << version.release_level << version.serial;
}
out << oss.str();
return out;
}
bool
parsePyVersionHex(uint64_t version, ParsedPyVersion& parsed)
{
int major = (version >> 24) & 0xFF;
int minor = (version >> 16) & 0xFF;
int patch = (version >> 8) & 0xFF;
int level = (version >> 4) & 0x0F;
int count = (version >> 0) & 0x0F;
const char* level_str = "(unknown release level)";
if (level == 0xA) {
level_str = "a";
} else if (level == 0xB) {
level_str = "b";
} else if (level == 0xC) {
level_str = "rc";
} else if (level == 0xF) {
level_str = "";
}
if (major < 2 || major > 3 || level_str == nullptr || (level == 0xF && count != 0)) {
return false; // Doesn't look valid.
}
parsed = ParsedPyVersion{major, minor, patch, level_str, count};
return true;
}
} // unnamed namespace
static std::vector<int>
getProcessTids(pid_t pid)
{
std::string filepath = "/proc/" + std::to_string(pid) + "/task";
::DirectoryReader reader(filepath);
std::vector<std::string> files = reader.files();
std::vector<int> tids;
std::transform(
files.cbegin(),
files.cend(),
std::back_inserter(tids),
[](const std::string& file) -> int { return std::stoi(file); });
return tids;
}
ProcessTracer::ProcessTracer(pid_t pid)
{
std::unordered_map<int, int> error_by_tid;
bool found_new_tid = true;
while (found_new_tid) {
found_new_tid = false;
auto tids = getProcessTids(pid);
for (auto& tid : tids) {
if (d_tids.count(tid)) {
continue; // already stopped
}
auto err_it = error_by_tid.find(tid);
if (err_it != error_by_tid.end()) {
// We got an error for this TID on the last iteration.
// Since we found the TID again this iteration, it still
// belongs to us and should have been stoppable.
detachFromProcess();
int error = err_it->second;
if (error == EPERM) {
throw std::runtime_error(PERM_MESSAGE);
}
throw std::system_error(error, std::generic_category());
}
found_new_tid = true;
LOG(INFO) << "Trying to stop thread " << tid;
long ret = ptrace(PTRACE_ATTACH, tid, nullptr, nullptr);
if (ret < 0) {
int error = errno;
LOG(WARNING) << "Failed to attach to thread " << tid << ": " << strerror(error);
error_by_tid.emplace(tid, error);
continue;
}
// Add each tid as we attach: these are the tids we detach from.
d_tids.insert(tid);
LOG(INFO) << "Waiting for thread " << tid << " to be stopped";
ret = waitpid(tid, nullptr, WUNTRACED);
if (ret < 0) {
// In some old kernels is not possible to use WUNTRACED with
// threads (only the main thread will return a non zero value).
if (tid == pid || errno != ECHILD) {
detachFromProcess();
}
}
LOG(INFO) << "Thread " << tid << " stopped";
}
}
LOG(INFO) << "All " << d_tids.size() << " threads stopped";
}
void
ProcessTracer::detachFromProcess()
{
for (auto& tid : d_tids) {
LOG(INFO) << "Detaching from thread " << tid;
ptrace(PTRACE_DETACH, tid, nullptr, nullptr);
}
}
ProcessTracer::~ProcessTracer()
{
detachFromProcess();
}
std::vector<int>
ProcessTracer::getTids() const
{
return {d_tids.begin(), d_tids.end()};
}
AbstractProcessManager::AbstractProcessManager(
pid_t pid,
std::vector<VirtualMap>&& memory_maps,
std::optional<VirtualMap> main_map,
std::optional<VirtualMap> bss,
std::optional<VirtualMap> heap)
: d_pid(pid)
, d_main_map(std::move(main_map))
, d_bss(std::move(bss))
, d_heap(std::move(heap))
, d_memory_maps(std::move(memory_maps))
, d_manager(nullptr)
, d_unwinder(nullptr)
, d_analyzer(nullptr)
{
if (!d_main_map) {
throw std::runtime_error("The main interpreter map could not be located");
}
}
const std::vector<VirtualMap>&
AbstractProcessManager::MemoryMaps() const
{
return d_memory_maps;
}
std::pair<int, int>
AbstractProcessManager::Version() const
{
return std::make_pair(d_major, d_minor);
}
bool
AbstractProcessManager::isValidDictionaryObject(remote_addr_t addr) const
{
if (addr == (remote_addr_t) nullptr) {
return false;
}
if (!isAddressValid(addr)) {
return false;
}
try {
Object pyobj(shared_from_this(), addr);
return pyobj.objectType() == Object::ObjectType::DICT;
} catch (RemoteMemCopyError& ex) {
return false;
}
}
bool
AbstractProcessManager::isValidInterpreterState(remote_addr_t addr) const
{
/* The main idea here is that the PyInterpreterState has a pointer to the
current thread state:
typedef struct _is
{
struct PyThreadState *next;
struct PyThreadState *tstate_head;
} PyInterpreterState;
and the PyThreadState has a pointer back to the PyInterpreterState:
typedef struct PyThreadState
{
struct PyThreadState *next;
PyInterpreterState *interp;
...
}
Using this information we can proceed as follows:
- Interpret the memory region at the current position as PyInterpreterState.
- Look at the address that the *tstate_head* member looks to, if the address
does not look like garbage, copy the memory that the address points to from
the remote process.
- Reinterpret the memory we just copied as a PyThreadState and look at the
address the *interp* member points to. This must point back to the address we
started with, this is, the address of we are assuming that corresponds to a
PyInterpreterState.
- As a last security check: try to construct a single frame and the
associated code object from the executing thread and check that the results
make sense. We need to do this because, although very rare, there may be some
random memory regions that have the previous properties but they are still
garbage.
If any of the previous steps fail, we continue with the next memory chunk
until we find the PyInterpreterState or we run out of chunks.
*/
if (!isAddressValid(addr)) {
return false;
}
Structure<py_is_v> is(shared_from_this(), addr);
// The check for valid addresses may fail if the address falls in the stack
// space (there are "holes" in the address map space so just checking for
// min_addr < addr < max_addr does not guarantee a valid address) so we need
// to catch InvalidRemoteAddress exceptions.
try {
is.copyFromRemote();
} catch (RemoteMemCopyError& ex) {
return false;
}
auto current_thread_addr = is.getField(&py_is_v::o_tstate_head);
if (!isAddressValid(current_thread_addr)) {
return false;
}
Structure<py_thread_v> current_thread(shared_from_this(), current_thread_addr);
try {
current_thread.copyFromRemote();
} catch (RemoteMemCopyError& ex) {
return false;
}
if (current_thread.getField(&py_thread_v::o_interp) != addr) {
return false;
}
LOG(DEBUG) << std::hex << std::showbase << "Possible PyInterpreterState candidate at address "
<< addr << " with tstate_head value of " << current_thread_addr;
// Validate dictionaries in the interpreter state
std::unordered_map<std::string, remote_addr_t> dictionaries(
{{"modules", is.getField(&py_is_v::o_modules)},
{"sysdict", is.getField(&py_is_v::o_sysdict)},
{"builtins", is.getField(&py_is_v::o_builtins)}});
for (const auto& [dictname, addr] : dictionaries) {
if (!isValidDictionaryObject(addr)) {
LOG(DEBUG) << "The '" << dictname << "' dictionary object is not valid";
return false;
}
LOG(DEBUG) << "The '" << dictname << "' dictionary object is valid";
}
LOG(DEBUG) << std::hex << std::showbase << "Possible PyInterpreterState candidate at address "
<< addr << " is valid";
return true;
}
remote_addr_t
AbstractProcessManager::findInterpreterStateFromPointer(remote_addr_t pointer) const
{
LOG(DEBUG) << "Trying to determine PyInterpreterState directly from address " << std::hex
<< std::showbase << pointer;
remote_addr_t interp_state;
copyObjectFromProcess(pointer, &interp_state);
if (!isValidInterpreterState(interp_state)) {
LOG(INFO) << "Failed to determine PyInterpreterState directly from address " << std::hex
<< std::showbase << pointer;
return (remote_addr_t)NULL;
}
return interp_state;
}
remote_addr_t
AbstractProcessManager::findInterpreterStateFromPyRuntime(remote_addr_t runtime_addr) const
{
LOG(INFO) << "Searching for PyInterpreterState based on PyRuntime address " << std::hex
<< std::showbase << runtime_addr;
Structure<py_runtime_v> py_runtime(shared_from_this(), runtime_addr);
remote_addr_t interp_state = py_runtime.getField(&py_runtime_v::o_interp_head);
if (!isValidInterpreterState(interp_state)) {
LOG(INFO) << "Failing to resolve PyInterpreterState based on PyRuntime address " << std::hex
<< std::showbase << runtime_addr;
return (remote_addr_t)NULL;
}
LOG(DEBUG) << "Interpreter head reference from symbol dereference successfully";
return interp_state;
}
remote_addr_t
AbstractProcessManager::scanMemoryAreaForInterpreterState(const VirtualMap& map) const
{
void* result = nullptr;
size_t size = map.Size();
std::vector<char> memory_buffer(size);
remote_addr_t base = map.Start();
copyMemoryFromProcess(base, size, memory_buffer.data());
void* upper_bound = (void*)(memory_buffer.data() + size);
LOG(INFO) << std::showbase << std::hex
<< "Searching for PyInterpreterState in memory area spanning from " << map.Start()
<< " to " << map.End();
for (void** raddr = (void**)memory_buffer.data(); (void*)raddr < upper_bound; raddr++) {
if (!isValidInterpreterState((remote_addr_t)*raddr)) {
continue;
}
LOG(DEBUG) << std::hex << std::showbase
<< "Possible interpreter state referenced by memory segment "
<< reinterpret_cast<void*>((char*)raddr - (char*)memory_buffer.data() + (char*)base)
<< " (offset " << reinterpret_cast<void*>((char*)raddr - (char*)memory_buffer.data())
<< " ) -> addr " << static_cast<void*>((char*)raddr);
result = *raddr;
break;
}
if (result == nullptr) {
LOG(INFO) << std::showbase << std::hex
<< "Could not find a valid PyInterpreterState in memory area spanning from "
<< map.Start() << " to " << map.End();
}
return (remote_addr_t)result;
}
remote_addr_t
AbstractProcessManager::scanMemoryAreaForDebugOffsets(const VirtualMap& map) const
{
size_t size = map.Size();
std::vector<char> memory_buffer(size);
remote_addr_t base = map.Start();
copyMemoryFromProcess(base, size, memory_buffer.data());
LOG(INFO) << std::showbase << std::hex << "Searching for debug offsets in memory area spanning from "
<< map.Start() << " to " << map.End();
uint64_t* lower_bound = (uint64_t*)&memory_buffer.data()[0];
uint64_t* upper_bound = (uint64_t*)&memory_buffer.data()[size];
uint64_t cookie;
memcpy(&cookie, "xdebugpy", sizeof(cookie));
for (uint64_t* raddr = lower_bound; raddr < upper_bound; raddr++) {
if (raddr[0] == cookie) {
uint64_t version = raddr[1];
ParsedPyVersion parsed;
if (parsePyVersionHex(version, parsed) && parsed.major == 3 && parsed.minor >= 13) {
auto offset = (remote_addr_t)raddr - (remote_addr_t)memory_buffer.data();
auto addr = offset + base;
LOG(DEBUG) << std::hex << std::showbase << "Possible debug offsets found at address "
<< addr << " in a mapping of " << map.Path();
return addr;
}
}
}
return 0;
}
remote_addr_t
AbstractProcessManager::scanBSS() const
{
LOG(INFO) << "Scanning BSS section for PyInterpreterState";
if (!d_bss) {
LOG(INFO) << "BSS analysis could not be performed because the BSS section is missing";
return (remote_addr_t) nullptr;
}
return scanMemoryAreaForInterpreterState(d_bss.value());
}
remote_addr_t
AbstractProcessManager::scanAllAnonymousMaps() const
{
LOG(INFO) << "Scanning all anonymous maps for PyInterpreterState";
for (auto& map : d_memory_maps) {
if (!map.Path().empty()) {
continue;
}
LOG(DEBUG) << std::hex << std::showbase
<< "Attempting to locate PyInterpreterState in with map starting at " << map.Start();
remote_addr_t result = scanMemoryAreaForInterpreterState(map);
if (result != 0) {
return result;
}
}
return 0;
}
remote_addr_t
AbstractProcessManager::scanHeap() const
{
LOG(INFO) << "Scanning HEAP section for PyInterpreterState";
if (!d_heap) {
LOG(INFO) << "HEAP analysis could not be performed because the HEAP section is missing";
return (remote_addr_t) nullptr;
}
return scanMemoryAreaForInterpreterState(d_heap.value());
}
remote_addr_t
AbstractProcessManager::findDebugOffsetsFromMaps() const
{
LOG(INFO) << "Scanning all writable path-backed maps for _Py_DebugOffsets";
for (auto& map : d_memory_maps) {
if (map.Flags().find("w") != std::string::npos && !map.Path().empty()) {
LOG(DEBUG) << std::hex << std::showbase << "Attempting to locate _Py_DebugOffsets in map of "
<< map.Path() << " starting at " << map.Start() << " and ending at " << map.End();
LOG(DEBUG) << "Flags: " << map.Flags();
try {
if (remote_addr_t result = scanMemoryAreaForDebugOffsets(map)) {
return result;
}
} catch (RemoteMemCopyError& ex) {
LOG(INFO) << "Failed to scan map starting at " << map.Start();
}
}
}
return 0;
}
ssize_t
AbstractProcessManager::copyMemoryFromProcess(remote_addr_t addr, size_t size, void* destination) const
{
return d_manager->copyMemoryFromProcess(addr, size, destination);
}
bool
AbstractProcessManager::isAddressValid(remote_addr_t addr) const
{
return std::any_of(d_memory_maps.cbegin(), d_memory_maps.cend(), [&](const VirtualMap& map) {
return d_manager->isAddressValid(addr, map);
});
}
std::string
AbstractProcessManager::getStringFromAddress(remote_addr_t addr) const
{
Python2::_PyStringObject string;
std::vector<char> buffer;
ssize_t len;
remote_addr_t data_addr;
if (d_major == 2) {
LOG(DEBUG) << std::hex << std::showbase << "Handling string object of version 2 from address "
<< addr;
copyObjectFromProcess(addr, &string);
len = string.ob_base.ob_size;
buffer.resize(len);
data_addr = (remote_addr_t)((char*)addr + offsetof(Python2::_PyStringObject, ob_sval));
LOG(DEBUG) << std::hex << std::showbase << "Copying ASCII data for string object from address "
<< data_addr;
copyMemoryFromProcess(data_addr, len, buffer.data());
} else {
LOG(DEBUG) << std::hex << std::showbase << "Handling unicode object of version 3 from address "
<< addr;
Structure<py_unicode_v> unicode(shared_from_this(), addr);
AnyPyUnicodeState state = unicode.getField(&py_unicode_v::o_state);
if (versionIsAtLeast(3, 14) and isFreeThreaded()) {
if (state.python3_14t.kind != 1 || state.python3_14t.compact != 1) {
throw InvalidRemoteObject();
}
} else {
if (state.python3.kind != 1 || state.python3.compact != 1) {
throw InvalidRemoteObject();
}
}
len = unicode.getField(&py_unicode_v::o_length);
buffer.resize(len);
data_addr = unicode.getFieldRemoteAddress(&py_unicode_v::o_ascii);
LOG(DEBUG) << std::hex << std::showbase << "Copying ASCII data for unicode object from address "
<< data_addr;
copyMemoryFromProcess(data_addr, len, buffer.data());
}
return std::string(buffer.begin(), buffer.end());
}
// ----------------------------------------------------------------------------
std::string
AbstractProcessManager::getBytesFromAddress(remote_addr_t addr) const
{
ssize_t len;
std::vector<char> buffer;
remote_addr_t data_addr;
if (d_major == 2) {
LOG(DEBUG) << std::hex << std::showbase << "Handling bytes object of version 2 from address "
<< addr;
Python2::_PyStringObject string;
copyObjectFromProcess(addr, &string);
len = string.ob_base.ob_size + 1;
buffer.resize(len);
data_addr = (remote_addr_t)((char*)addr + offsetof(Python2::_PyStringObject, ob_sval));
LOG(DEBUG) << std::hex << std::showbase << "Copying data for bytes object from address "
<< data_addr;
copyMemoryFromProcess(data_addr, len, buffer.data());
} else {
LOG(DEBUG) << std::hex << std::showbase << "Handling bytes object of version 3 from address "
<< addr;
Structure<py_bytes_v> bytes(shared_from_this(), addr);
len = bytes.getField(&py_bytes_v::o_ob_size) + 1;
if (len < 1) {
throw std::runtime_error("Incorrect size of the fetched bytes object");
}
buffer.resize(len);
data_addr = bytes.getFieldRemoteAddress(&py_bytes_v::o_ob_sval);
LOG(DEBUG) << std::hex << std::showbase << "Copying data for bytes object from address "
<< data_addr;
copyMemoryFromProcess(data_addr, len, buffer.data());
}
return std::string(buffer.begin(), buffer.end() - 1);
}
remote_addr_t
AbstractProcessManager::findSymbol(const std::string& symbol) const
{
const auto elem = d_symbol_cache.find(symbol);
if (elem == d_symbol_cache.cend()) {
remote_addr_t addr = d_unwinder->getAddressforSymbol(symbol, d_main_map.value().Path());
d_symbol_cache.emplace(symbol, addr);
return addr;
}
return elem->second;
}
remote_addr_t
AbstractProcessManager::findInterpreterStateFromSymbols() const
{
LOG(INFO) << "Trying to find PyInterpreterState with symbols";
remote_addr_t pyruntime = findSymbol("_PyRuntime");
if (pyruntime) {
return findInterpreterStateFromPyRuntime(pyruntime);
}
// Older versions have a pointer to PyinterpreterState in "interp_head"
remote_addr_t interp_head = findSymbol("interp_head");
if (interp_head) {
return findInterpreterStateFromPointer(interp_head);
}
return 0;
}
std::vector<NativeFrame>
AbstractProcessManager::unwindThread(pid_t tid) const
{
return d_unwinder->unwindThread(tid);
}
pid_t
AbstractProcessManager::Pid() const
{
return d_pid;
}
remote_addr_t
AbstractProcessManager::getAddressFromCache(const std::string& symbol) const
{
return d_type_cache[symbol];
}
void
AbstractProcessManager::registerAddressInCache(const std::string& symbol, remote_addr_t address) const
{
d_type_cache[symbol] = address;
}
std::string
AbstractProcessManager::getCStringFromAddress(remote_addr_t addr) const
{
std::vector<char> result;
char character = 0;
size_t position = 0;
do {
copyObjectFromProcess(addr + ((position++) * sizeof(char)), &character);
result.push_back(character);
} while (character != 0);
return std::string(result.cbegin(), result.cend() - 1);
}
AbstractProcessManager::InterpreterStatus
AbstractProcessManager::isInterpreterActive() const
{
remote_addr_t runtime_addr = findSymbol("_PyRuntime");
if (runtime_addr) {
Structure<py_runtime_v> py_runtime(shared_from_this(), runtime_addr);
remote_addr_t p = py_runtime.getField(&py_runtime_v::o_finalizing);
return p == 0 ? InterpreterStatus::RUNNING : InterpreterStatus::FINALIZED;
}
return InterpreterStatus::UNKNOWN;
}
void
AbstractProcessManager::setPythonVersionFromDebugOffsets()
{
remote_addr_t pyruntime_addr = findSymbol("_PyRuntime");
if (!pyruntime_addr) {
pyruntime_addr = findPyRuntimeFromElfData();
}
if (!pyruntime_addr) {
pyruntime_addr = findDebugOffsetsFromMaps();
}
if (!pyruntime_addr) {
LOG(DEBUG) << "Unable to find _Py_DebugOffsets";
return;
}
try {
uint64_t cookie;
copyObjectFromProcess(pyruntime_addr, &cookie);
if (0 != memcmp(&cookie, "xdebugpy", 8)) {
LOG(DEBUG) << "Found a _PyRuntime structure without _Py_DebugOffsets";
return;
}
uint64_t version;
copyObjectFromProcess(pyruntime_addr + 8, &version);
ParsedPyVersion parsed;
if (parsePyVersionHex(version, parsed) && parsed.major == 3 && parsed.minor >= 13) {
LOG(INFO) << std::hex << std::showbase << "_Py_DebugOffsets at " << pyruntime_addr
<< " identify the version as " << parsed;
setPythonVersion(std::make_pair(parsed.major, parsed.minor));
Structure<py_runtime_v> py_runtime(shared_from_this(), pyruntime_addr);
bool is_free_threaded = py_runtime.getField(&py_runtime_v::o_dbg_off_free_threaded);
std::unique_ptr<python_v> offsets = loadDebugOffsets(py_runtime);
if (offsets) {
LOG(INFO) << "_Py_DebugOffsets appear to be valid and will be used";
warnIfOffsetsAreMismatched(pyruntime_addr);
d_debug_offsets_addr = pyruntime_addr;
d_debug_offsets = std::move(offsets);
d_is_free_threaded = is_free_threaded;
return;
}
}
} catch (const RemoteMemCopyError& ex) {
LOG(DEBUG) << std::hex << std::showbase << "Found apparently invalid _Py_DebugOffsets at "
<< pyruntime_addr;
}
LOG(DEBUG) << "Failed to validate _PyDebugOffsets structure";
d_major = 0;
d_minor = 0;
d_py_v = nullptr;
d_debug_offsets_addr = 0;
d_debug_offsets.reset();
}
std::pair<int, int>
AbstractProcessManager::findPythonVersion() const
{
if (d_py_v) {
// Already set or previously found (probably via _Py_DebugOffsets)
return std::make_pair(d_major, d_minor);
}
auto version_symbol = findSymbol("Py_Version");
if (!version_symbol) {
LOG(DEBUG) << "Failed to determine Python version from symbols";
return {-1, -1};
}
unsigned long version;
try {
copyObjectFromProcess(version_symbol, &version);
} catch (RemoteMemCopyError& ex) {
LOG(DEBUG) << "Failed to determine Python version from symbols";
return {-1, -1};
}
int major = (version >> 24) & 0xFF;
int minor = (version >> 16) & 0xFF;
int level = (version >> 4) & 0x0F;
if (major == 0 && minor == 0) {
LOG(DEBUG) << "Failed to determine Python version from symbols: empty data copied";
return {-1, -1};
}
if (major != 2 && major != 3) {
LOG(DEBUG) << "Failed to determine Python version from symbols: invalid major version";
return {-1, -1};
}
if (level != 0xA && level != 0xB && level != 0xC && level != 0xF) {
LOG(DEBUG) << "Failed to determine Python version from symbols: invalid release level";
return {-1, -1};
}
LOG(DEBUG) << "Python version determined from symbols: " << major << "." << minor;
return {major, minor};
}
void
AbstractProcessManager::setPythonVersion(const std::pair<int, int>& version)
{
d_py_v = getCPythonOffsets(version.first, version.second);
// Note: getCPythonOffsets can throw. Don't set these if it does.
d_major = version.first;
d_minor = version.second;
}
void
AbstractProcessManager::warnIfOffsetsAreMismatched(remote_addr_t runtime_addr) const
{
Structure<py_runtime_v> py_runtime(shared_from_this(), runtime_addr);
if (0 != memcmp(py_runtime.getField(&py_runtime_v::o_dbg_off_cookie), "xdebugpy", 8)) {
LOG(WARNING) << "Debug offsets cookie doesn't match!";
return;
}
// Note: It's OK for pystack's size to be smaller, but not larger.
#define compare_size(size_offset, pystack_struct) \
if ((d_py_v->py_runtime.*size_offset).offset \
&& ((uint64_t)offsets().pystack_struct.size > py_runtime.getField(size_offset))) \
{ \
LOG(INFO) << "Debug offsets mismatch: compiled-in " << sizeof(void*) * 8 << "-bit python3." \
<< d_minor << " " #pystack_struct ".size " << offsets().pystack_struct.size << " > " \
<< py_runtime.getField(size_offset) << " loaded from _Py_DebugOffsets"; \
} else \
do { \
} while (0)
#define compare_offset(field_offset_offset, pystack_field) \
if ((d_py_v->py_runtime.*field_offset_offset).offset \
&& (uint64_t)offsets().pystack_field.offset != py_runtime.getField(field_offset_offset)) \
{ \
LOG(INFO) << "Debug offsets mismatch: compiled-in " << sizeof(void*) * 8 << "-bit python3." \
<< d_minor << " " #pystack_field << " " << offsets().pystack_field.offset \
<< " != " << py_runtime.getField(field_offset_offset) \
<< " loaded from _Py_DebugOffsets"; \
} else \
do { \
} while (0)
compare_size(&py_runtime_v::o_dbg_off_runtime_state_struct_size, py_runtime);
compare_offset(&py_runtime_v::o_dbg_off_runtime_state_finalizing, py_runtime.o_finalizing);
compare_offset(&py_runtime_v::o_dbg_off_runtime_state_interpreters_head, py_runtime.o_interp_head);
compare_size(&py_runtime_v::o_dbg_off_interpreter_state_struct_size, py_is);
compare_offset(&py_runtime_v::o_dbg_off_interpreter_state_next, py_is.o_next);
compare_offset(&py_runtime_v::o_dbg_off_interpreter_state_threads_head, py_is.o_tstate_head);
compare_offset(&py_runtime_v::o_dbg_off_interpreter_state_gc, py_is.o_gc);
compare_offset(&py_runtime_v::o_dbg_off_interpreter_state_imports_modules, py_is.o_modules);
compare_offset(&py_runtime_v::o_dbg_off_interpreter_state_sysdict, py_is.o_sysdict);
compare_offset(&py_runtime_v::o_dbg_off_interpreter_state_builtins, py_is.o_builtins);
compare_offset(&py_runtime_v::o_dbg_off_interpreter_state_ceval_gil, py_is.o_gil_runtime_state);
compare_size(&py_runtime_v::o_dbg_off_thread_state_struct_size, py_thread);
compare_offset(&py_runtime_v::o_dbg_off_thread_state_prev, py_thread.o_prev);
compare_offset(&py_runtime_v::o_dbg_off_thread_state_next, py_thread.o_next);
compare_offset(&py_runtime_v::o_dbg_off_thread_state_interp, py_thread.o_interp);
compare_offset(&py_runtime_v::o_dbg_off_thread_state_current_frame, py_thread.o_frame);
compare_offset(&py_runtime_v::o_dbg_off_thread_state_thread_id, py_thread.o_thread_id);
compare_offset(&py_runtime_v::o_dbg_off_thread_state_native_thread_id, py_thread.o_native_thread_id);
compare_size(&py_runtime_v::o_dbg_off_interpreter_frame_struct_size, py_frame);
compare_offset(&py_runtime_v::o_dbg_off_interpreter_frame_previous, py_frame.o_back);
compare_offset(&py_runtime_v::o_dbg_off_interpreter_frame_executable, py_frame.o_code);
compare_offset(&py_runtime_v::o_dbg_off_interpreter_frame_instr_ptr, py_frame.o_prev_instr);
compare_offset(&py_runtime_v::o_dbg_off_interpreter_frame_localsplus, py_frame.o_localsplus);
compare_offset(&py_runtime_v::o_dbg_off_interpreter_frame_owner, py_frame.o_owner);
compare_size(&py_runtime_v::o_dbg_off_code_object_struct_size, py_code);
compare_offset(&py_runtime_v::o_dbg_off_code_object_filename, py_code.o_filename);
compare_offset(&py_runtime_v::o_dbg_off_code_object_name, py_code.o_name);
compare_offset(&py_runtime_v::o_dbg_off_code_object_linetable, py_code.o_lnotab);
compare_offset(&py_runtime_v::o_dbg_off_code_object_firstlineno, py_code.o_firstlineno);
compare_offset(&py_runtime_v::o_dbg_off_code_object_argcount, py_code.o_argcount);
compare_offset(&py_runtime_v::o_dbg_off_code_object_localsplusnames, py_code.o_varnames);
compare_offset(&py_runtime_v::o_dbg_off_code_object_co_code_adaptive, py_code.o_code_adaptive);
compare_size(&py_runtime_v::o_dbg_off_pyobject_struct_size, py_object);
compare_offset(&py_runtime_v::o_dbg_off_pyobject_ob_type, py_object.o_ob_type);
compare_size(&py_runtime_v::o_dbg_off_type_object_struct_size, py_type);
compare_offset(&py_runtime_v::o_dbg_off_type_object_tp_name, py_type.o_tp_name);
compare_offset(&py_runtime_v::o_dbg_off_type_object_tp_repr, py_type.o_tp_repr);
compare_offset(&py_runtime_v::o_dbg_off_type_object_tp_flags, py_type.o_tp_flags);
compare_size(&py_runtime_v::o_dbg_off_tuple_object_struct_size, py_tuple);
compare_offset(&py_runtime_v::o_dbg_off_tuple_object_ob_item, py_tuple.o_ob_item);
compare_offset(&py_runtime_v::o_dbg_off_tuple_object_ob_size, py_tuple.o_ob_size);
compare_size(&py_runtime_v::o_dbg_off_list_object_struct_size, py_list);
compare_offset(&py_runtime_v::o_dbg_off_list_object_ob_item, py_list.o_ob_item);
compare_offset(&py_runtime_v::o_dbg_off_list_object_ob_size, py_list.o_ob_size);
compare_size(&py_runtime_v::o_dbg_off_dict_object_struct_size, py_dict);
compare_offset(&py_runtime_v::o_dbg_off_dict_object_ma_keys, py_dict.o_ma_keys);
compare_offset(&py_runtime_v::o_dbg_off_dict_object_ma_values, py_dict.o_ma_values);
compare_size(&py_runtime_v::o_dbg_off_float_object_struct_size, py_float);
compare_offset(&py_runtime_v::o_dbg_off_float_object_ob_fval, py_float.o_ob_fval);
compare_size(&py_runtime_v::o_dbg_off_long_object_struct_size, py_long);
compare_offset(&py_runtime_v::o_dbg_off_long_object_lv_tag, py_long.o_ob_size);
compare_offset(&py_runtime_v::o_dbg_off_long_object_ob_digit, py_long.o_ob_digit);
compare_size(&py_runtime_v::o_dbg_off_bytes_object_struct_size, py_bytes);
compare_offset(&py_runtime_v::o_dbg_off_bytes_object_ob_size, py_bytes.o_ob_size);
compare_offset(&py_runtime_v::o_dbg_off_bytes_object_ob_sval, py_bytes.o_ob_sval);
compare_size(&py_runtime_v::o_dbg_off_unicode_object_struct_size, py_unicode);
compare_offset(&py_runtime_v::o_dbg_off_unicode_object_state, py_unicode.o_state);
compare_offset(&py_runtime_v::o_dbg_off_unicode_object_length, py_unicode.o_length);
compare_offset(&py_runtime_v::o_dbg_off_unicode_object_asciiobject_size, py_unicode.o_ascii);
compare_size(&py_runtime_v::o_dbg_off_gc_struct_size, py_gc);
compare_offset(&py_runtime_v::o_dbg_off_gc_collecting, py_gc.o_collecting);
#undef compare_size
#undef compare_offset
}
std::unique_ptr<python_v>
AbstractProcessManager::loadDebugOffsets(Structure<py_runtime_v>& py_runtime) const
{
if (!versionIsAtLeast(3, 13)) {
return {}; // _Py_DebugOffsets was added in 3.13
}
if (0 != memcmp(py_runtime.getField(&py_runtime_v::o_dbg_off_cookie), "xdebugpy", 8)) {
LOG(WARNING) << "Debug offsets cookie doesn't match!";
return {};
}
uint64_t version = py_runtime.getField(&py_runtime_v::o_dbg_off_py_version_hex);
int major = (version >> 24) & 0xff;
int minor = (version >> 16) & 0xff;
if (major != d_major || minor != d_minor) {
LOG(WARNING) << "Detected version " << d_major << "." << d_minor
<< " doesn't match debug offsets version " << major << "." << minor << "!";
return {};
}
python_v debug_offsets{};
if (!copyDebugOffsets(py_runtime, debug_offsets)) {
return {};
}
if (!validateDebugOffsets(py_runtime, debug_offsets)) {
return {};
}
auto ret = std::make_unique<python_v>();
*ret = debug_offsets;
clampSizes(*ret);
return ret;
}
bool
AbstractProcessManager::copyDebugOffsets(Structure<py_runtime_v>& py_runtime, python_v& debug_offsets)
const
{
// Fill in a temporary python_v with the offsets from the remote. For fields
// that aren't in _Py_DebugOffsets, assume our static offsets are correct.
#define set_size(pystack_struct, size_offset) \
debug_offsets.pystack_struct.size = py_runtime.getField(size_offset)
#define set_offset(pystack_field, field_offset_offset) \
debug_offsets.pystack_field = {(offset_t)py_runtime.getField(field_offset_offset)}
set_size(py_runtime, &py_runtime_v::o_dbg_off_runtime_state_struct_size);
set_offset(py_runtime.o_finalizing, &py_runtime_v::o_dbg_off_runtime_state_finalizing);
set_offset(py_runtime.o_interp_head, &py_runtime_v::o_dbg_off_runtime_state_interpreters_head);
set_size(py_is, &py_runtime_v::o_dbg_off_interpreter_state_struct_size);
set_offset(py_is.o_next, &py_runtime_v::o_dbg_off_interpreter_state_next);
set_offset(py_is.o_tstate_head, &py_runtime_v::o_dbg_off_interpreter_state_threads_head);
set_offset(py_is.o_gc, &py_runtime_v::o_dbg_off_interpreter_state_gc);
set_offset(py_is.o_modules, &py_runtime_v::o_dbg_off_interpreter_state_imports_modules);
set_offset(py_is.o_sysdict, &py_runtime_v::o_dbg_off_interpreter_state_sysdict);
set_offset(py_is.o_builtins, &py_runtime_v::o_dbg_off_interpreter_state_builtins);
set_offset(py_is.o_gil_runtime_state, &py_runtime_v::o_dbg_off_interpreter_state_ceval_gil);
set_size(py_thread, &py_runtime_v::o_dbg_off_thread_state_struct_size);
set_offset(py_thread.o_prev, &py_runtime_v::o_dbg_off_thread_state_prev);
set_offset(py_thread.o_next, &py_runtime_v::o_dbg_off_thread_state_next);