-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloader.cpp
More file actions
1178 lines (1009 loc) 路 38.5 KB
/
Copy pathloader.cpp
File metadata and controls
1178 lines (1009 loc) 路 38.5 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
// Python Bytecode Loader Module for IDA Pro
// Handles .pyc file detection, parsing, and segment creation
#include <ida.hpp>
#include <idp.hpp>
#include <loader.hpp>
#include <diskio.hpp>
#include <bytes.hpp>
#include <name.hpp>
#include <nalt.hpp>
#include <segment.hpp>
#include <entry.hpp>
#include <auto.hpp>
#include <typeinf.hpp>
#include "../../core/common/types.hpp"
#include "../../core/common/platform.hpp"
#include "../../core/config/constants.hpp"
#include "../../core/version/version.hpp"
#include "../../core/version/magic.hpp"
#include "../../marshal/types/type_codes.hpp"
#include "../../marshal/code_object/code_object.hpp"
#include "../../format/header/header.hpp"
namespace pyc {
namespace loader {
// ============================================================================
// Global Version State (set during loading)
// ============================================================================
static uint8_t g_py_major = 0;
static uint8_t g_py_minor = 0;
// ============================================================================
// Marshal Reference Table
// ============================================================================
// Reference table for resolving TYPE_REF during marshal parsing
// Objects with FLAG_REF set are added to this table in order,
// then TYPE_REF can look them up by index.
// We track ALL objects (strings get actual values, others get placeholders)
// because reference indices must be consistent.
struct marshal_refs_t {
qvector<qstring> values; // Reference values (strings get actual content)
qvector<bool> is_string; // Whether this entry is a real string
void clear() {
values.clear();
is_string.clear();
}
void add_string(const qstring& s) {
values.push_back(s);
is_string.push_back(true);
}
void add_placeholder() {
values.push_back(qstring());
is_string.push_back(false);
}
bool get_string(uint32_t idx, qstring* out) const {
if (idx < values.size() && is_string[idx]) {
*out = values[idx];
return true;
}
return false;
}
size_t size() const { return values.size(); }
};
static marshal_refs_t g_refs;
// ============================================================================
// Helper Functions
// ============================================================================
static uint32_t read_le32(linput_t* li) {
uint8_t buf[4];
if (qlread(li, buf, 4) != 4) return 0;
return buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24);
}
static uint8_t read_byte(linput_t* li) {
uint8_t b;
if (qlread(li, &b, 1) != 1) return 0;
return b;
}
// ============================================================================
// Segment Creation Helper
// ============================================================================
static bool create_pyc_segment(ea_t start, ea_t end, const char* name,
const char* sclass, uchar perm) {
segment_t seg;
seg.start_ea = start;
seg.end_ea = end;
seg.sel = allocate_selector((start >> 4) & 0xFFFF);
seg.bitness = 1; // 32-bit addressing
seg.align = saRelByte;
seg.comb = scPub;
seg.perm = perm;
if (!add_segm_ex(&seg, name, sclass, ADDSEG_NOSREG | ADDSEG_OR_DIE))
return false;
return true;
}
// ============================================================================
// Code Object Info Structure
// ============================================================================
struct pyc_except_entry_t {
uint32_t start;
uint32_t end;
uint32_t target;
uint32_t depth;
bool lasti;
};
struct pyc_code_info_t {
qstring name; // Function/code name
qstring qualname; // Qualified name (3.11+)
qstring filename; // Source filename
uint32_t argcount;
uint32_t posonlyargcount;
uint32_t kwonlyargcount;
uint32_t nlocals;
uint32_t stacksize;
uint32_t flags;
uint32_t firstlineno;
qvector<uint8_t> code;
qvector<qstring> consts;
qvector<qstring> names;
qvector<qstring> varnames;
qvector<qstring> freevars;
qvector<qstring> cellvars;
qvector<uint8_t> linetable;
ea_t code_ea; // Where code is loaded
int depth; // Nesting depth (0 for module)
qvector<pyc_except_entry_t> exc_table;
// Nested code objects found in consts
qvector<pyc_code_info_t> nested_codes;
};
// ============================================================================
// Forward Declarations
// ============================================================================
static bool skip_marshal_object(linput_t* li);
static bool read_marshal_string(linput_t* li, qstring* out);
static bool read_marshal_as_string(linput_t* li, qstring* out,
qvector<pyc_code_info_t>* nested_codes, int depth);
static bool parse_code_object_inner(linput_t* li, pyc_code_info_t* info, int depth);
// ============================================================================
// Skip Marshal Object (version-aware)
// ============================================================================
static bool skip_string(linput_t* li, uint8_t type) {
uint32_t len;
if (type == marshal::TYPE_SHORT_ASCII || type == marshal::TYPE_SHORT_ASCII_INTERNED) {
len = read_byte(li);
} else {
len = read_le32(li);
}
return qlseek(li, len, SEEK_CUR) != -1;
}
static bool skip_code_object(linput_t* li) {
// Skip code object fields based on Python version
bool is_py3 = g_py_major >= 3;
bool has_posonlyargcount = is_py3 && g_py_minor >= 8;
bool has_qualname = is_py3 && g_py_minor >= 11;
bool has_exceptiontable = is_py3 && g_py_minor >= 11;
bool nlocals_separate = !(is_py3 && g_py_minor >= 11);
// Skip integer fields
qlseek(li, 4, SEEK_CUR); // argcount
if (has_posonlyargcount)
qlseek(li, 4, SEEK_CUR); // posonlyargcount
qlseek(li, 4, SEEK_CUR); // kwonlyargcount
if (nlocals_separate)
qlseek(li, 4, SEEK_CUR); // nlocals
qlseek(li, 4, SEEK_CUR); // stacksize
qlseek(li, 4, SEEK_CUR); // flags
// Skip code (bytes)
if (!skip_marshal_object(li)) return false;
// Skip consts (tuple) - recursive, may contain code objects
if (!skip_marshal_object(li)) return false;
// Skip names (tuple)
if (!skip_marshal_object(li)) return false;
// Python 3.11+ changed order
if (is_py3 && g_py_minor >= 11) {
// localsplusnames
if (!skip_marshal_object(li)) return false;
// localspluskinds
if (!skip_marshal_object(li)) return false;
} else {
// varnames
if (!skip_marshal_object(li)) return false;
// freevars
if (!skip_marshal_object(li)) return false;
// cellvars
if (!skip_marshal_object(li)) return false;
}
// filename
if (!skip_marshal_object(li)) return false;
// name
if (!skip_marshal_object(li)) return false;
// qualname (3.11+)
if (has_qualname) {
if (!skip_marshal_object(li)) return false;
}
// firstlineno - raw int in 3.11+, marshal object in earlier versions
if (is_py3 && g_py_minor >= 11) {
qlseek(li, 4, SEEK_CUR); // Raw 4-byte int
} else {
if (!skip_marshal_object(li)) return false;
}
// linetable/lnotab
if (!skip_marshal_object(li)) return false;
// exceptiontable (3.11+)
if (has_exceptiontable) {
if (!skip_marshal_object(li)) return false;
}
return true;
}
static bool skip_marshal_object(linput_t* li) {
uint8_t raw_type;
if (qlread(li, &raw_type, 1) != 1) return false;
bool has_ref = (raw_type & marshal::FLAG_REF) != 0;
uint8_t type = raw_type & ~marshal::FLAG_REF;
// Track reference - add placeholder for non-strings
// (strings are tracked in read_marshal_string)
if (has_ref && type != marshal::TYPE_STRING &&
type != marshal::TYPE_INTERNED && type != marshal::TYPE_ASCII &&
type != marshal::TYPE_ASCII_INTERNED && type != marshal::TYPE_UNICODE &&
type != marshal::TYPE_SHORT_ASCII && type != marshal::TYPE_SHORT_ASCII_INTERNED) {
g_refs.add_placeholder();
}
switch (type) {
case marshal::TYPE_NULL:
case marshal::TYPE_NONE:
case marshal::TYPE_STOPITER:
case marshal::TYPE_ELLIPSIS:
case marshal::TYPE_FALSE:
case marshal::TYPE_TRUE:
return true;
case marshal::TYPE_INT:
return qlseek(li, 4, SEEK_CUR) != -1;
case marshal::TYPE_INT64:
case marshal::TYPE_BINARY_FLOAT:
return qlseek(li, 8, SEEK_CUR) != -1;
case marshal::TYPE_BINARY_COMPLEX:
return qlseek(li, 16, SEEK_CUR) != -1;
case marshal::TYPE_LONG: {
int32_t n = (int32_t)read_le32(li);
if (n < 0) n = -n;
return qlseek(li, n * 2, SEEK_CUR) != -1;
}
case marshal::TYPE_STRING:
case marshal::TYPE_INTERNED:
case marshal::TYPE_ASCII:
case marshal::TYPE_ASCII_INTERNED:
case marshal::TYPE_UNICODE: {
// Track string in reference table if FLAG_REF
if (has_ref) {
int64_t pos = qltell(li) - 1; // Rewind to type byte
qlseek(li, pos);
qstring s;
return read_marshal_string(li, &s); // This adds to g_refs
}
return skip_string(li, type);
}
case marshal::TYPE_SHORT_ASCII:
case marshal::TYPE_SHORT_ASCII_INTERNED: {
if (has_ref) {
int64_t pos = qltell(li) - 1;
qlseek(li, pos);
qstring s;
return read_marshal_string(li, &s);
}
return skip_string(li, type);
}
case marshal::TYPE_TUPLE:
case marshal::TYPE_LIST:
case marshal::TYPE_SET:
case marshal::TYPE_FROZENSET: {
uint32_t n = read_le32(li);
for (uint32_t i = 0; i < n; i++)
if (!skip_marshal_object(li)) return false;
return true;
}
case marshal::TYPE_SMALL_TUPLE: {
uint8_t n = read_byte(li);
for (uint8_t i = 0; i < n; i++)
if (!skip_marshal_object(li)) return false;
return true;
}
case marshal::TYPE_DICT: {
while (true) {
int64_t pos = qltell(li);
uint8_t key_type;
if (qlread(li, &key_type, 1) != 1) return false;
if ((key_type & ~marshal::FLAG_REF) == marshal::TYPE_NULL) return true;
qlseek(li, pos);
if (!skip_marshal_object(li)) return false;
if (!skip_marshal_object(li)) return false;
}
}
case marshal::TYPE_CODE:
return skip_code_object(li);
case marshal::TYPE_REF:
case marshal::TYPE_STRINGREF:
return qlseek(li, 4, SEEK_CUR) != -1;
case marshal::TYPE_FLOAT: {
uint8_t len = read_byte(li);
return qlseek(li, len, SEEK_CUR) != -1;
}
case marshal::TYPE_COMPLEX: {
uint8_t rlen = read_byte(li);
if (qlseek(li, rlen, SEEK_CUR) == -1) return false;
uint8_t ilen = read_byte(li);
return qlseek(li, ilen, SEEK_CUR) != -1;
}
default:
msg("PYC: Unknown marshal type 0x%02X at offset %lld\n", type, (long long)qltell(li)-1);
return false;
}
}
// ============================================================================
// Read Marshal String
// ============================================================================
static bool read_marshal_string(linput_t* li, qstring* out) {
uint8_t raw_type;
if (qlread(li, &raw_type, 1) != 1) return false;
bool has_ref = (raw_type & marshal::FLAG_REF) != 0;
uint8_t type = raw_type & ~marshal::FLAG_REF;
uint32_t len;
switch (type) {
case marshal::TYPE_SHORT_ASCII:
case marshal::TYPE_SHORT_ASCII_INTERNED:
len = read_byte(li);
break;
case marshal::TYPE_ASCII:
case marshal::TYPE_ASCII_INTERNED:
case marshal::TYPE_STRING:
case marshal::TYPE_INTERNED:
case marshal::TYPE_UNICODE:
len = read_le32(li);
break;
case marshal::TYPE_NONE:
*out = "None";
if (has_ref) g_refs.add_string(*out);
return true;
case marshal::TYPE_REF: {
// Look up reference in table
uint32_t ref_idx = read_le32(li);
if (g_refs.get_string(ref_idx, out))
return true;
out->sprnt("<ref_%u>", ref_idx);
return true;
}
case marshal::TYPE_STRINGREF: {
// Reference to an interned string (Python 2.x)
uint32_t ref_idx = read_le32(li);
if (g_refs.get_string(ref_idx, out))
return true;
out->sprnt("<ref_%u>", ref_idx);
return true;
}
default:
return false;
}
out->resize(len);
if (len > 0 && qlread(li, out->begin(), len) != len)
return false;
// Add to reference table if FLAG_REF was set
if (has_ref)
g_refs.add_string(*out);
return true;
}
// ============================================================================
// Read Marshal Bytes
// ============================================================================
static bool read_marshal_bytes(linput_t* li, qvector<uint8_t>* out) {
uint8_t raw_type;
if (qlread(li, &raw_type, 1) != 1) return false;
bool has_ref = (raw_type & marshal::FLAG_REF) != 0;
uint8_t type = raw_type & ~marshal::FLAG_REF;
// Handle reference to previously seen bytes object
if (type == marshal::TYPE_REF) {
qlseek(li, 4, SEEK_CUR); // Skip ref index
out->clear();
return true;
}
// Track in reference table if FLAG_REF was set (bytes are non-string, use placeholder)
if (has_ref) {
g_refs.add_placeholder();
}
uint32_t len;
if (type == marshal::TYPE_SHORT_ASCII || type == marshal::TYPE_SHORT_ASCII_INTERNED) {
len = read_byte(li);
} else if (type == marshal::TYPE_STRING || type == marshal::TYPE_ASCII ||
type == marshal::TYPE_ASCII_INTERNED || type == marshal::TYPE_INTERNED) {
len = read_le32(li);
} else {
return false;
}
out->resize(len);
if (len > 0 && qlread(li, out->begin(), len) != len)
return false;
return true;
}
// ==========================================================================
// Parse Exception Table (Python 3.11+)
// ============================================================================
static bool parse_exception_table(const qvector<uint8_t>& data,
qvector<pyc_except_entry_t>* out) {
out->clear();
size_t pos = 0;
auto read_varint = [&](uint32_t* value) -> bool {
if (pos >= data.size())
return false;
uint8_t b = data[pos++];
uint32_t val = b & 0x3F;
while (b & 0x40) {
if (pos >= data.size())
return false;
b = data[pos++];
val = (val << 6) | (b & 0x3F);
}
*value = val;
return true;
};
while (pos < data.size()) {
uint32_t start = 0, length = 0, target = 0, depth_lasti = 0;
if (!read_varint(&start) || !read_varint(&length) ||
!read_varint(&target) || !read_varint(&depth_lasti)) {
return false;
}
pyc_except_entry_t entry;
entry.start = start * 2;
entry.end = entry.start + length * 2;
entry.target = target * 2;
entry.depth = depth_lasti >> 1;
entry.lasti = (depth_lasti & 1) != 0;
out->push_back(entry);
}
return true;
}
// ============================================================================
// Read Tuple Header
// ============================================================================
static bool read_tuple_header(linput_t* li, uint32_t* count) {
uint8_t raw_type;
if (qlread(li, &raw_type, 1) != 1) return false;
bool has_ref = (raw_type & marshal::FLAG_REF) != 0;
uint8_t type = raw_type & ~marshal::FLAG_REF;
// Tuples with FLAG_REF must be tracked in reference table
// Add placeholder BEFORE reading contents (reference index assigned at type byte)
if (has_ref && (type == marshal::TYPE_TUPLE || type == marshal::TYPE_SMALL_TUPLE)) {
g_refs.add_placeholder();
}
if (type == marshal::TYPE_SMALL_TUPLE) {
*count = read_byte(li);
return true;
} else if (type == marshal::TYPE_TUPLE) {
*count = read_le32(li);
return true;
} else if (type == marshal::TYPE_REF) {
// Reference to a previously-seen tuple
// For tuples, we can't easily resolve them, so return 0 items
// This typically happens when the same tuple is used multiple times
qlseek(li, 4, SEEK_CUR);
*count = 0;
return true;
}
return false;
}
// ============================================================================
// Read Marshal as String Representation
// ============================================================================
static bool read_marshal_as_string(linput_t* li, qstring* out,
qvector<pyc_code_info_t>* nested_codes, int depth) {
int64_t start_pos = qltell(li);
uint8_t raw_type;
if (qlread(li, &raw_type, 1) != 1) return false;
bool has_ref = (raw_type & marshal::FLAG_REF) != 0;
uint8_t type = raw_type & ~marshal::FLAG_REF;
switch (type) {
case marshal::TYPE_NONE:
*out = "None";
if (has_ref) g_refs.add_string(*out);
return true;
case marshal::TYPE_TRUE:
*out = "True";
if (has_ref) g_refs.add_string(*out);
return true;
case marshal::TYPE_FALSE:
*out = "False";
if (has_ref) g_refs.add_string(*out);
return true;
case marshal::TYPE_ELLIPSIS:
*out = "...";
if (has_ref) g_refs.add_string(*out);
return true;
case marshal::TYPE_INT: {
int32_t val = (int32_t)read_le32(li);
out->sprnt("%d", val);
if (has_ref) g_refs.add_string(*out);
return true;
}
case marshal::TYPE_INT64: {
int64_t val;
if (qlread(li, &val, 8) != 8) return false;
out->sprnt("%lld", (long long)val);
if (has_ref) g_refs.add_string(*out);
return true;
}
case marshal::TYPE_BINARY_FLOAT: {
double val;
if (qlread(li, &val, 8) != 8) return false;
out->sprnt("%g", val);
if (has_ref) g_refs.add_string(*out);
return true;
}
case marshal::TYPE_STRING:
case marshal::TYPE_INTERNED:
case marshal::TYPE_ASCII:
case marshal::TYPE_ASCII_INTERNED:
case marshal::TYPE_UNICODE:
case marshal::TYPE_SHORT_ASCII:
case marshal::TYPE_SHORT_ASCII_INTERNED: {
qlseek(li, start_pos); // Rewind to let read_marshal_string handle FLAG_REF
qstring str;
if (!read_marshal_string(li, &str)) return false;
// Escape and quote the string
out->sprnt("'%s'", str.c_str());
return true;
}
case marshal::TYPE_TUPLE:
case marshal::TYPE_SMALL_TUPLE: {
// Add placeholder BEFORE parsing contents (for FLAG_REF)
if (has_ref)
g_refs.add_placeholder();
qlseek(li, start_pos); // Rewind to re-read tuple header
uint32_t count;
if (!read_tuple_header(li, &count)) return false;
*out = "(";
for (uint32_t i = 0; i < count; i++) {
if (i > 0) out->append(", ");
qstring item;
if (!read_marshal_as_string(li, &item, nested_codes, depth)) {
item = "?";
}
out->append(item);
if (out->length() > 60) {
out->append("...");
// Skip remaining items
for (uint32_t j = i + 1; j < count; j++)
skip_marshal_object(li);
break;
}
}
out->append(")");
return true;
}
case marshal::TYPE_CODE: {
// Add placeholder BEFORE parsing (reference index is assigned at type byte)
if (has_ref)
g_refs.add_placeholder();
// Parse the nested code object and store it
pyc_code_info_t nested;
if (parse_code_object_inner(li, &nested, depth + 1)) {
out->sprnt("<code '%s'>", nested.name.c_str());
if (nested_codes)
nested_codes->push_back(nested);
} else {
*out = "<code ?>";
}
return true;
}
case marshal::TYPE_REF: {
// Look up reference in table
uint32_t ref_idx = read_le32(li);
if (g_refs.get_string(ref_idx, out))
return true;
out->sprnt("<ref_%u>", ref_idx);
return true;
}
case marshal::TYPE_LONG: {
int32_t n = (int32_t)read_le32(li);
bool neg = n < 0;
if (neg) n = -n;
qlseek(li, n * 2, SEEK_CUR); // Skip the digits
out->sprnt("<long%s>", neg ? "-" : "+");
if (has_ref) g_refs.add_string(*out);
return true;
}
default: {
out->sprnt("<type:0x%02X>", type);
qlseek(li, start_pos); // Rewind
skip_marshal_object(li); // Skip it
if (has_ref) g_refs.add_string(*out);
return true;
}
}
}
// ============================================================================
// Parse String Tuple
// ============================================================================
static bool parse_string_tuple(linput_t* li, qvector<qstring>* out) {
// Check type first - might be a ref to a previously seen tuple
uint8_t type;
int64_t pos = qltell(li);
if (qlread(li, &type, 1) != 1) return false;
type &= ~marshal::FLAG_REF;
if (type == marshal::TYPE_REF) {
// Reference to a previously seen object - skip the 4-byte index
// We can't resolve refs without tracking all objects, so return empty
qlseek(li, 4, SEEK_CUR);
out->clear();
return true;
}
// Rewind and read as tuple
qlseek(li, pos);
uint32_t count;
if (!read_tuple_header(li, &count))
return false;
out->resize(count);
for (uint32_t i = 0; i < count; i++) {
if (!read_marshal_string(li, &(*out)[i])) {
// Not a string - skip and use placeholder
(*out)[i].sprnt("<item_%u>", i);
}
}
return true;
}
// ============================================================================
// Parse Code Object
// ============================================================================
static bool parse_code_object_inner(linput_t* li, pyc_code_info_t* info, int depth) {
info->depth = depth;
bool is_py3 = g_py_major >= 3;
bool has_kwonlyargcount = is_py3; // Python 3.0+ only
bool has_posonlyargcount = is_py3 && g_py_minor >= 8;
bool has_qualname = is_py3 && g_py_minor >= 11;
bool has_linetable = is_py3 && g_py_minor >= 10;
bool has_exceptiontable = is_py3 && g_py_minor >= 11;
bool nlocals_separate = !(is_py3 && g_py_minor >= 11);
// Read code object fields
info->argcount = read_le32(li);
if (has_posonlyargcount)
info->posonlyargcount = read_le32(li);
else
info->posonlyargcount = 0;
if (has_kwonlyargcount)
info->kwonlyargcount = read_le32(li);
else
info->kwonlyargcount = 0;
if (nlocals_separate)
info->nlocals = read_le32(li);
else
info->nlocals = 0;
info->stacksize = read_le32(li);
info->flags = read_le32(li);
// Remap flags for versions < 3.8 (future flags shifted in 3.8)
if (g_py_major < 3 || (g_py_major == 3 && g_py_minor < 8)) {
uint32_t high = (info->flags & 0x0FFF0000) << 4;
info->flags = (info->flags & 0x0000FFFF) | high;
}
// Read code bytes
if (!read_marshal_bytes(li, &info->code)) {
msg("PYC: Failed to read code bytes at depth %d\n", depth);
return false;
}
// Read consts tuple - may contain nested code objects
uint32_t const_count;
if (!read_tuple_header(li, &const_count)) {
msg("PYC: Failed to read consts tuple header at depth %d\n", depth);
return false;
}
info->consts.resize(const_count);
for (uint32_t i = 0; i < const_count; i++) {
if (!read_marshal_as_string(li, &info->consts[i], &info->nested_codes, depth)) {
info->consts[i].sprnt("<const_%u>", i);
}
}
// Read names tuple
if (!parse_string_tuple(li, &info->names)) {
msg("PYC: Failed to read names tuple at depth %d\n", depth);
return false;
}
// Python 3.11+ changed order
if (is_py3 && g_py_minor >= 11) {
// localsplusnames
if (!parse_string_tuple(li, &info->varnames)) {
msg("PYC: Failed to read localsplusnames at depth %d\n", depth);
return false;
}
// localspluskinds (bytes object)
qvector<uint8_t> kinds;
if (!read_marshal_bytes(li, &kinds))
kinds.clear();
// Decode locals/freevars/cellvars from kinds
info->freevars.clear();
info->cellvars.clear();
uint32_t local_count = 0;
const uint8_t CO_FAST_LOCAL = 0x20;
const uint8_t CO_FAST_CELL = 0x40;
const uint8_t CO_FAST_FREE = 0x80;
size_t count = info->varnames.size();
if (kinds.size() < count)
count = kinds.size();
for (size_t i = 0; i < count; i++) {
const qstring& name = info->varnames[i];
uint8_t kind = kinds[i];
if (kind & CO_FAST_LOCAL) {
local_count++;
if (kind & CO_FAST_CELL)
info->cellvars.push_back(name);
} else if (kind & CO_FAST_CELL) {
info->cellvars.push_back(name);
} else if (kind & CO_FAST_FREE) {
info->freevars.push_back(name);
}
}
info->nlocals = local_count;
} else {
// Pre-3.11: varnames, freevars, cellvars
if (!parse_string_tuple(li, &info->varnames)) {
info->varnames.clear();
}
if (!parse_string_tuple(li, &info->freevars)) {
info->freevars.clear();
}
if (!parse_string_tuple(li, &info->cellvars)) {
info->cellvars.clear();
}
}
// Read filename
if (!read_marshal_string(li, &info->filename)) {
info->filename = "<unknown>";
}
// Read name
if (!read_marshal_string(li, &info->name)) {
info->name = "<code>";
}
// Read qualname (3.11+)
if (has_qualname) {
if (!read_marshal_string(li, &info->qualname))
info->qualname = info->name;
} else {
info->qualname = info->name;
}
// Read firstlineno - raw 4-byte int in all Python versions
info->firstlineno = read_le32(li);
// Read linetable/lnotab
read_marshal_bytes(li, &info->linetable);
// Read exception table (3.11+)
if (has_exceptiontable) {
qvector<uint8_t> exctable;
if (read_marshal_bytes(li, &exctable)) {
parse_exception_table(exctable, &info->exc_table);
}
}
return true;
}
// ============================================================================
// Load All Code Objects into IDA
// ============================================================================
static ea_t g_next_code_addr = 0x10000;
static void load_code_object(pyc_code_info_t& code, const qstring& prefix) {
// Create segment name
qstring seg_name;
if (code.name == "<module>")
seg_name = ".code";
else if (prefix.empty())
seg_name.sprnt(".code_%s", code.name.c_str());
else
seg_name.sprnt(".code_%s.%s", prefix.c_str(), code.name.c_str());
// Calculate addresses
ea_t code_base = g_next_code_addr;
ea_t code_end = code_base + code.code.size();
g_next_code_addr = (code_end + 0x100) & ~0xFF; // Align to 256 bytes
// Create code segment
if (!create_pyc_segment(code_base, code_end, seg_name.c_str(), "CODE",
SEGPERM_READ | SEGPERM_EXEC)) {
msg("PYC: Failed to create segment %s\n", seg_name.c_str());
return;
}
// Load code bytes
mem2base(code.code.begin(), code_base, code_end, -1);
code.code_ea = code_base;
// Store code object metadata in netnode
qstring co_node_name;
co_node_name.sprnt("%s%llX", config::CODE_NODE_PREFIX, (uint64_t)code_base);
netnode co_node;
co_node.create(co_node_name.c_str());
co_node.altset(config::CO_ARGCOUNT, code.argcount);
co_node.altset(config::CO_KWONLYARGCOUNT, code.kwonlyargcount);
co_node.altset(config::CO_NLOCALS, code.nlocals);
co_node.altset(config::CO_STACKSIZE, code.stacksize);
co_node.altset(config::CO_FLAGS, code.flags);
co_node.altset(config::CO_FIRSTLINENO, code.firstlineno);
co_node.altset(config::CO_CODE_SIZE, (uint32_t)code.code.size());
// Store names as null-separated blob
qstring names_blob;
for (const auto& name : code.names) {
names_blob.append(name);
names_blob.append('\0');
}
co_node.supset(config::CO_NAMES_BLOB, names_blob.c_str(), names_blob.length());
// Store varnames
qstring varnames_blob;
for (const auto& name : code.varnames) {
varnames_blob.append(name);
varnames_blob.append('\0');
}
co_node.supset(config::CO_VARNAMES_BLOB, varnames_blob.c_str(), varnames_blob.length());
// Store freevars
qstring freevars_blob;
for (const auto& name : code.freevars) {
freevars_blob.append(name);
freevars_blob.append('\0');
}
co_node.supset(config::CO_FREEVARS_BLOB, freevars_blob.c_str(), freevars_blob.length());
// Store cellvars
qstring cellvars_blob;
for (const auto& name : code.cellvars) {
cellvars_blob.append(name);
cellvars_blob.append('\0');
}
co_node.supset(config::CO_CELLVARS_BLOB, cellvars_blob.c_str(), cellvars_blob.length());
// Store consts representations
qstring consts_blob;
for (const auto& c : code.consts) {
consts_blob.append(c);
consts_blob.append('\0');
}
co_node.supset(config::CO_CONSTS_BLOB, consts_blob.c_str(), consts_blob.length());
// Add exception handler comments (3.11+)
if (!code.exc_table.empty()) {
uint32_t code_size = (uint32_t)code.code.size();
for (const auto& entry : code.exc_table) {
if (entry.target >= code_size)
continue;
ea_t target_ea = code_base + entry.target;
qstring cmt;
cmt.sprnt("except: +0x%X..+0x%X depth=%u lasti=%u",
entry.start, entry.end, entry.depth, entry.lasti ? 1 : 0);
qstring existing;
if (get_cmt(&existing, target_ea, true) > 0) {
existing.append("\n");
existing.append(cmt);
set_cmt(target_ea, existing.c_str(), true);
} else {
set_cmt(target_ea, cmt.c_str(), true);
}
}
}
// Create entry point / function name
qstring func_name;
if (prefix.empty())
func_name = code.name;
else
func_name.sprnt("%s.%s", prefix.c_str(), code.name.c_str());
// Clean up name for IDA (replace <> with _)
func_name.replace("<", "_");
func_name.replace(">", "_");
if (code.depth == 0) {
add_entry(0, code_base, func_name.c_str(), true);
} else {
force_name(code_base, func_name.c_str());
}
// Queue for auto-analysis
auto_make_proc(code_base);
msg("PYC: Loaded %s at %llX (%zu bytes, %zu consts, %zu names)\n",
func_name.c_str(), (uint64_t)code_base,
code.code.size(), code.consts.size(), code.names.size());
// Recursively load nested code objects
qstring new_prefix;
if (prefix.empty()) {
if (code.name != "<module>")
new_prefix = code.name;
} else {
new_prefix.sprnt("%s.%s", prefix.c_str(), code.name.c_str());