-
Notifications
You must be signed in to change notification settings - Fork 1
/
dumper.py
4127 lines (3638 loc) · 162 KB
/
dumper.py
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
############################################################################
#
# Copyright (C) 2016 The Qt Company Ltd.
# Contact: https://www.qt.io/licensing/
#
# This file is part of Qt Creator.
#
# Commercial License Usage
# Licensees holding valid commercial Qt licenses may use this file in
# accordance with the commercial license agreement provided with the
# Software or, alternatively, in accordance with the terms contained in
# a written agreement between you and The Qt Company. For licensing terms
# and conditions see https://www.qt.io/terms-conditions. For further
# information use the contact form at https://www.qt.io/contact-us.
#
# GNU General Public License Usage
# Alternatively, this file may be used under the terms of the GNU
# General Public License version 3 as published by the Free Software
# Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
# included in the packaging of this file. Please review the following
# information to ensure the GNU General Public License requirements will
# be met: https://www.gnu.org/licenses/gpl-3.0.html.
#
############################################################################
import os
import codecs
import collections
import glob
import struct
import sys
import base64
import re
import time
import inspect
from utils import DisplayFormat, TypeCode
try:
# That's only used in native combined debugging right now, so
# we do not need to hard fail in cases of partial python installation
# that will never use this.
import json
except:
print("Python module json not found. "
"Native combined debugging might not work.")
pass
if sys.version_info[0] >= 3:
toInteger = int
else:
toInteger = long
class ReportItem():
"""
Helper structure to keep temporary 'best' information about a value
or a type scheduled to be reported. This might get overridden be
subsequent better guesses during a putItem() run.
"""
def __init__(self, value=None, encoding=None, priority=-100, elided=None):
self.value = value
self.priority = priority
self.encoding = encoding
self.elided = elided
def __str__(self):
return 'Item(value: %s, encoding: %s, priority: %s, elided: %s)' \
% (self.value, self.encoding, self.priority, self.elided)
class Timer():
def __init__(self, d, desc):
self.d = d
self.desc = desc + '-' + d.currentIName
def __enter__(self):
self.starttime = time.time()
def __exit__(self, exType, exValue, exTraceBack):
elapsed = int(1000 * (time.time() - self.starttime))
self.d.timings.append([self.desc, elapsed])
class Children():
def __init__(self, d, numChild=1, childType=None, childNumChild=None,
maxNumChild=None, addrBase=None, addrStep=None):
self.d = d
self.numChild = numChild
self.childNumChild = childNumChild
self.maxNumChild = maxNumChild
if childType is None:
self.childType = None
else:
self.childType = childType.name
if not self.d.isCli:
self.d.putField('childtype', self.childType)
if childNumChild is not None:
self.d.putField('childnumchild', childNumChild)
self.childNumChild = childNumChild
if addrBase is not None and addrStep is not None:
self.d.put('addrbase="0x%x",addrstep="%d",' % (addrBase, addrStep))
def __enter__(self):
self.savedChildType = self.d.currentChildType
self.savedChildNumChild = self.d.currentChildNumChild
self.savedNumChild = self.d.currentNumChild
self.savedMaxNumChild = self.d.currentMaxNumChild
self.d.currentChildType = self.childType
self.d.currentChildNumChild = self.childNumChild
self.d.currentNumChild = self.numChild
self.d.currentMaxNumChild = self.maxNumChild
self.d.put(self.d.childrenPrefix)
def __exit__(self, exType, exValue, exTraceBack):
if exType is not None:
if self.d.passExceptions:
self.d.showException('CHILDREN', exType, exValue, exTraceBack)
self.d.putSpecialValue('notaccessible')
self.d.putNumChild(0)
if self.d.currentMaxNumChild is not None:
if self.d.currentMaxNumChild < self.d.currentNumChild:
self.d.put('{name="<incomplete>",value="",type="",numchild="0"},')
self.d.currentChildType = self.savedChildType
self.d.currentChildNumChild = self.savedChildNumChild
self.d.currentNumChild = self.savedNumChild
self.d.currentMaxNumChild = self.savedMaxNumChild
if self.d.isCli:
self.d.output += '\n' + ' ' * self.d.indent
self.d.put(self.d.childrenSuffix)
return True
class SubItem():
def __init__(self, d, component):
self.d = d
self.name = component
self.iname = None
def __enter__(self):
self.d.enterSubItem(self)
def __exit__(self, exType, exValue, exTraceBack):
return self.d.exitSubItem(self, exType, exValue, exTraceBack)
class TopLevelItem(SubItem):
def __init__(self, d, iname):
self.d = d
self.iname = iname
self.name = None
class UnnamedSubItem(SubItem):
def __init__(self, d, component):
self.d = d
self.iname = '%s.%s' % (self.d.currentIName, component)
self.name = None
class DumperBase():
@staticmethod
def warn(message):
print('bridgemessage={msg="%s"},' % message.replace('"', '$').encode('latin1'))
@staticmethod
def showException(msg, exType, exValue, exTraceback):
DumperBase.warn('**** CAUGHT EXCEPTION: %s ****' % msg)
try:
import traceback
for line in traceback.format_exception(exType, exValue, exTraceback):
DumperBase.warn('%s' % line)
except:
pass
def timer(self, desc):
return Timer(self, desc)
def __init__(self):
self.isCdb = False
self.isGdb = False
self.isLldb = False
self.isCli = False
# Later set, or not set:
self.stringCutOff = 10000
self.displayStringLimit = 100
self.useTimeStamps = False
self.output = ''
self.typesReported = {}
self.typesToReport = {}
self.qtNamespaceToReport = None
self.qtCustomEventFunc = 0
self.qtCustomEventPltFunc = 0
self.qtPropertyFunc = 0
self.fallbackQtVersion = 0x50200
self.passExceptions = False
self.isTesting = False
self.typeData = {}
self.isBigEndian = False
self.packCode = '<'
self.resetCaches()
self.resetStats()
self.childrenPrefix = 'children=['
self.childrenSuffix = '],'
self.dumpermodules = [
os.path.splitext(os.path.basename(p))[0] for p in
glob.glob(os.path.join(os.path.dirname(__file__), '*types.py'))
]
# These values are never used, but the variables need to have
# some value base for the swapping logic in Children.__enter__()
# and Children.__exit__().
self.currentIName = None
self.currentValue = None
self.currentType = None
self.currentNumChild = None
self.currentMaxNumChild = None
self.currentPrintsAddress = True
self.currentChildType = None
self.currentChildNumChild = None
self.registerKnownTypes()
def setVariableFetchingOptions(self, args):
self.resultVarName = args.get('resultvarname', '')
self.expandedINames = set(args.get('expanded', []))
self.stringCutOff = int(args.get('stringcutoff', 10000))
self.displayStringLimit = int(args.get('displaystringlimit', 100))
self.typeformats = args.get('typeformats', {})
self.formats = args.get('formats', {})
self.watchers = args.get('watchers', {})
self.useDynamicType = int(args.get('dyntype', '0'))
self.useFancy = int(args.get('fancy', '0'))
self.forceQtNamespace = int(args.get('forcens', '0'))
self.passExceptions = int(args.get('passexceptions', '0'))
self.isTesting = int(args.get('testing', '0'))
self.showQObjectNames = int(args.get('qobjectnames', '1'))
self.nativeMixed = int(args.get('nativemixed', '0'))
self.autoDerefPointers = int(args.get('autoderef', '0'))
self.useTimeStamps = int(args.get('timestamps', '0'))
self.partialVariable = args.get('partialvar', '')
self.uninitialized = args.get('uninitialized', [])
self.uninitialized = list(map(lambda x: self.hexdecode(x), self.uninitialized))
self.partialUpdate = int(args.get('partial', '0'))
#DumperBase.warn('NAMESPACE: "%s"' % self.qtNamespace())
#DumperBase.warn('EXPANDED INAMES: %s' % self.expandedINames)
#DumperBase.warn('WATCHERS: %s' % self.watchers)
def setFallbackQtVersion(self, args):
version = int(args.get('version', self.fallbackQtVersion))
DumperBase.warn("got fallback qt version 0x%x" % version)
self.fallbackQtVersion = version
def resetPerStepCaches(self):
self.perStepCache = {}
pass
def resetCaches(self):
# This is a cache mapping from 'type name' to 'display alternatives'.
self.qqFormats = {'QVariant (QVariantMap)': [DisplayFormat.CompactMap]}
# This is a cache of all known dumpers.
self.qqDumpers = {} # Direct type match
self.qqDumpersEx = {} # Using regexp
# This is a cache of all dumpers that support writing.
self.qqEditable = {}
# This keeps canonical forms of the typenames, without array indices etc.
self.cachedFormats = {}
# Maps type names to static metaobjects. If a type is known
# to not be QObject derived, it contains a 0 value.
self.knownStaticMetaObjects = {}
# A dictionary to serve as a per debugging step cache.
# Cleared on each step over / into / continue.
self.perStepCache = {}
# A dictionary to serve as a general cache throughout the whole
# debug session.
self.generalCache = {}
self.counts = {}
self.structPatternCache = {}
self.timings = []
self.expandableINames = set({})
def resetStats(self):
# Timing collection
self.timings = []
pass
def dumpStats(self):
msg = [self.counts, self.timings]
self.resetStats()
return msg
def bump(self, key):
if key in self.counts:
self.counts[key] += 1
else:
self.counts[key] = 1
def childRange(self):
if self.currentMaxNumChild is None:
return range(0, self.currentNumChild)
return range(min(self.currentMaxNumChild, self.currentNumChild))
def enterSubItem(self, item):
if self.useTimeStamps:
item.startTime = time.time()
if not item.iname:
item.iname = '%s.%s' % (self.currentIName, item.name)
if not self.isCli:
self.put('{')
if isinstance(item.name, str):
self.putField('name', item.name)
else:
self.indent += 1
self.output += '\n' + ' ' * self.indent
if isinstance(item.name, str):
self.output += item.name + ' = '
item.savedIName = self.currentIName
item.savedValue = self.currentValue
item.savedType = self.currentType
self.currentIName = item.iname
self.currentValue = ReportItem()
self.currentType = ReportItem()
def exitSubItem(self, item, exType, exValue, exTraceBack):
#DumperBase.warn('CURRENT VALUE: %s: %s %s' %
# (self.currentIName, self.currentValue, self.currentType))
if exType is not None:
if self.passExceptions:
self.showException('SUBITEM', exType, exValue, exTraceBack)
self.putSpecialValue('notaccessible')
self.putNumChild(0)
if not self.isCli:
try:
if self.currentType.value:
typeName = self.currentType.value
if len(typeName) > 0 and typeName != self.currentChildType:
self.putField('type', typeName)
if self.currentValue.value is None:
self.put('value="",encoding="notaccessible",numchild="0",')
else:
if self.currentValue.encoding is not None:
self.put('valueencoded="%s",' % self.currentValue.encoding)
if self.currentValue.elided:
self.put('valueelided="%s",' % self.currentValue.elided)
self.put('value="%s",' % self.currentValue.value)
except:
pass
if self.useTimeStamps:
self.put('time="%s",' % (time.time() - item.startTime))
self.put('},')
else:
self.indent -= 1
try:
if self.currentType.value:
typeName = self.currentType.value
self.put('<%s> = {' % typeName)
if self.currentValue.value is None:
self.put('<not accessible>')
else:
value = self.currentValue.value
if self.currentValue.encoding == 'latin1':
value = self.hexdecode(value)
elif self.currentValue.encoding == 'utf8':
value = self.hexdecode(value)
elif self.currentValue.encoding == 'utf16':
b = bytes(bytearray.fromhex(value))
value = codecs.decode(b, 'utf-16')
self.put('"%s"' % value)
if self.currentValue.elided:
self.put('...')
if self.currentType.value:
self.put('}')
except:
pass
self.currentIName = item.savedIName
self.currentValue = item.savedValue
self.currentType = item.savedType
return True
def stripForFormat(self, typeName):
if not isinstance(typeName, str):
raise RuntimeError('Expected string in stripForFormat(), got %s' % type(typeName))
if typeName in self.cachedFormats:
return self.cachedFormats[typeName]
stripped = ''
inArray = 0
for c in typeName:
if c == '<':
break
if c == ' ':
continue
if c == '[':
inArray += 1
elif c == ']':
inArray -= 1
if inArray and ord(c) >= 48 and ord(c) <= 57:
continue
stripped += c
self.cachedFormats[typeName] = stripped
return stripped
def templateArgument(self, typeobj, position):
return typeobj.templateArgument(position)
def intType(self):
result = self.lookupType('int')
self.intType = lambda: result
return result
def charType(self):
result = self.lookupType('char')
self.intType = lambda: result
return result
def ptrSize(self):
result = self.lookupType('void*').size()
self.ptrSize = lambda: result
return result
def lookupType(self, typeName):
nativeType = self.lookupNativeType(typeName)
return None if nativeType is None else self.fromNativeType(nativeType)
def registerKnownTypes(self):
typeId = 'unsigned short'
tdata = self.TypeData(self)
tdata.name = typeId
tdata.typeId = typeId
tdata.lbitsize = 16
tdata.code = TypeCode.Integral
self.registerType(typeId, tdata)
typeId = 'QChar'
tdata = self.TypeData(self)
tdata.name = typeId
tdata.typeId = typeId
tdata.lbitsize = 16
tdata.code = TypeCode.Struct
tdata.lfields = [self.Field(dumper=self, name='ucs',
type='unsigned short', bitsize=16, bitpos=0)]
tdata.lalignment = 2
tdata.templateArguments = []
self.registerType(typeId, tdata)
def nativeDynamicType(self, address, baseType):
return baseType # Override in backends.
def listTemplateParameters(self, typename):
return self.listTemplateParametersManually(typename)
def listTemplateParametersManually(self, typename):
targs = []
if not typename.endswith('>'):
return targs
def push(inner):
# Handle local struct definitions like QList<main(int, char**)::SomeStruct>
inner = inner.strip()[::-1]
p = inner.find(')::')
if p > -1:
inner = inner[p + 3:].strip()
if inner.startswith('const '):
inner = inner[6:].strip()
if inner.endswith(' const'):
inner = inner[:-6].strip()
#DumperBase.warn("FOUND: %s" % inner)
targs.append(inner)
#DumperBase.warn("SPLITTING %s" % typename)
level = 0
inner = ''
for c in typename[::-1]: # Reversed...
#DumperBase.warn("C: %s" % c)
if c == '>':
if level > 0:
inner += c
level += 1
elif c == '<':
level -= 1
if level > 0:
inner += c
else:
push(inner)
inner = ''
break
elif c == ',':
#DumperBase.warn('c: %s level: %s' % (c, level))
if level == 1:
push(inner)
inner = ''
else:
inner += c
else:
inner += c
#DumperBase.warn("TARGS: %s %s" % (typename, targs))
res = []
for item in targs[::-1]:
if len(item) == 0:
continue
c = ord(item[0])
if c in (45, 46) or (c >= 48 and c < 58): # '-', '.' or digit.
if item.find('.') > -1:
res.append(float(item))
else:
if item.endswith('l'):
item = item[:-1]
if item.endswith('u'):
item = item[:-1]
val = toInteger(item)
if val > 0x80000000:
val -= 0x100000000
res.append(val)
else:
res.append(self.Type(self, item))
#DumperBase.warn("RES: %s %s" % (typename, [(None if t is None else t.name) for t in res]))
return res
# Hex decoding operating on str, return str.
@staticmethod
def hexdecode(s, encoding='utf8'):
if sys.version_info[0] == 2:
# For python2 we need an extra str() call to return str instead of unicode
return str(s.decode('hex').decode(encoding))
return bytes.fromhex(s).decode(encoding)
# Hex encoding operating on str or bytes, return str.
@staticmethod
def hexencode(s):
if s is None:
s = ''
if sys.version_info[0] == 2:
if isinstance(s, buffer):
return bytes(s).encode('hex')
return s.encode('hex')
if isinstance(s, str):
s = s.encode('utf8')
return base64.b16encode(s).decode('utf8')
def isQt3Support(self):
# assume no Qt 3 support by default
return False
# Clamps size to limit.
def computeLimit(self, size, limit):
if limit == 0:
limit = self.displayStringLimit
if limit is None or size <= limit:
return 0, size
return size, limit
def vectorData(self, value):
if self.qtVersion() >= 0x060000:
data, size, alloc = self.qArrayData(value)
elif self.qtVersion() >= 0x050000:
vector_data_ptr = self.extractPointer(value)
if self.ptrSize() == 4:
(ref, size, alloc, offset) = self.split('IIIp', vector_data_ptr)
else:
(ref, size, alloc, pad, offset) = self.split('IIIIp', vector_data_ptr)
alloc = alloc & 0x7ffffff
data = vector_data_ptr + offset
else:
vector_data_ptr = self.extractPointer(value)
(ref, alloc, size) = self.split('III', vector_data_ptr)
data = vector_data_ptr + 16
self.check(0 <= size and size <= alloc and alloc <= 1000 * 1000 * 1000)
return data, size
def qArrayData(self, value):
if self.qtVersion() >= 0x60000:
dd, data, size = self.split('ppp', value)
if dd:
_, _, alloc = self.split('iip', dd)
else: # fromRawData
alloc = size
return data, size, alloc
return self.qArrayDataHelper(self.extractPointer(value))
def qArrayDataHelper(self, array_data_ptr):
# array_data_ptr is what is e.g. stored in a QByteArray's d_ptr.
if self.qtVersion() >= 0x050000:
# QTypedArray:
# - QtPrivate::RefCount ref
# - int size
# - uint alloc : 31, capacityReserved : 1
# - qptrdiff offset
(ref, size, alloc, offset) = self.split('IIpp', array_data_ptr)
alloc = alloc & 0x7ffffff
data = array_data_ptr + offset
if self.ptrSize() == 4:
data = data & 0xffffffff
else:
data = data & 0xffffffffffffffff
elif self.qtVersion() >= 0x040000:
# Data:
# - QBasicAtomicInt ref;
# - int alloc, size;
# - [padding]
# - char *data;
if self.ptrSize() == 4:
(ref, alloc, size, data) = self.split('IIIp', array_data_ptr)
else:
(ref, alloc, size, pad, data) = self.split('IIIIp', array_data_ptr)
else:
# Data:
# - QShared count;
# - QChar *unicode
# - char *ascii
# - uint len: 30
(dummy, dummy, dummy, size) = self.split('IIIp', array_data_ptr)
size = self.extractInt(array_data_ptr + 3 * self.ptrSize()) & 0x3ffffff
alloc = size # pretend.
data = self.extractPointer(array_data_ptr + self.ptrSize())
return data, size, alloc
def encodeStringHelper(self, value, limit):
data, size, alloc = self.qArrayData(value)
if alloc != 0:
self.check(0 <= size and size <= alloc and alloc <= 100 * 1000 * 1000)
elided, shown = self.computeLimit(2 * size, 2 * limit)
return elided, self.readMemory(data, shown)
def encodeByteArrayHelper(self, value, limit):
data, size, alloc = self.qArrayData(value)
if alloc != 0:
self.check(0 <= size and size <= alloc and alloc <= 100 * 1000 * 1000)
elided, shown = self.computeLimit(size, limit)
return elided, self.readMemory(data, shown)
def putCharArrayValue(self, data, size, charSize,
displayFormat=DisplayFormat.Automatic):
bytelen = size * charSize
elided, shown = self.computeLimit(bytelen, self.displayStringLimit)
mem = self.readMemory(data, shown)
if charSize == 1:
if displayFormat in (DisplayFormat.Latin1String, DisplayFormat.SeparateLatin1String):
encodingType = 'latin1'
else:
encodingType = 'utf8'
#childType = 'char'
elif charSize == 2:
encodingType = 'utf16'
#childType = 'short'
else:
encodingType = 'ucs4'
#childType = 'int'
self.putValue(mem, encodingType, elided=elided)
if displayFormat in (
DisplayFormat.SeparateLatin1String,
DisplayFormat.SeparateUtf8String,
DisplayFormat.Separate):
elided, shown = self.computeLimit(bytelen, 100000)
self.putDisplay(encodingType + ':separate', self.readMemory(data, shown))
def putCharArrayHelper(self, data, size, charType,
displayFormat=DisplayFormat.Automatic,
makeExpandable=True):
charSize = charType.size()
self.putCharArrayValue(data, size, charSize, displayFormat=displayFormat)
if makeExpandable:
self.putNumChild(size)
if self.isExpanded():
with Children(self):
for i in range(size):
self.putSubItem(size, self.createValue(data + i * charSize, charType))
def readMemory(self, addr, size):
return self.hexencode(bytes(self.readRawMemory(addr, size)))
def encodeByteArray(self, value, limit=0):
elided, data = self.encodeByteArrayHelper(value, limit)
return data
def putByteArrayValue(self, value):
elided, data = self.encodeByteArrayHelper(value, self.displayStringLimit)
self.putValue(data, 'latin1', elided=elided)
def encodeString(self, value, limit=0):
elided, data = self.encodeStringHelper(value, limit)
return data
def encodedUtf16ToUtf8(self, s):
return ''.join([chr(int(s[i:i + 2], 16)) for i in range(0, len(s), 4)])
def encodeStringUtf8(self, value, limit=0):
return self.encodedUtf16ToUtf8(self.encodeString(value, limit))
def stringData(self, value): # -> (data, size, alloc)
return self.qArrayData(value)
def extractTemplateArgument(self, typename, position):
level = 0
skipSpace = False
inner = ''
for c in typename[typename.find('<') + 1: -1]:
if c == '<':
inner += c
level += 1
elif c == '>':
level -= 1
inner += c
elif c == ',':
if level == 0:
if position == 0:
return inner.strip()
position -= 1
inner = ''
else:
inner += c
skipSpace = True
else:
if skipSpace and c == ' ':
pass
else:
inner += c
skipSpace = False
# Handle local struct definitions like QList<main(int, char**)::SomeStruct>
inner = inner.strip()
p = inner.find(')::')
if p > -1:
inner = inner[p + 3:]
return inner
def putStringValue(self, value):
elided, data = self.encodeStringHelper(value, self.displayStringLimit)
self.putValue(data, 'utf16', elided=elided)
def putPtrItem(self, name, value):
with SubItem(self, name):
self.putValue('0x%x' % value)
self.putType('void*')
def putIntItem(self, name, value):
with SubItem(self, name):
if isinstance(value, self.Value):
self.putValue(value.display())
else:
self.putValue(value)
self.putType('int')
def putEnumItem(self, name, ival, typish):
buf = bytearray(struct.pack('i', ival))
val = self.Value(self)
val.ldata = bytes(buf)
val._type = self.createType(typish)
with SubItem(self, name):
self.putItem(val)
def putBoolItem(self, name, value):
with SubItem(self, name):
self.putValue(value)
self.putType('bool')
def putPairItem(self, index, pair, keyName='first', valueName='second'):
with SubItem(self, index):
self.putPairContents(index, pair, keyName, valueName)
def putPairContents(self, index, pair, kname, vname):
with Children(self):
first, second = pair if isinstance(pair, tuple) else pair.members(False)
key = self.putSubItem(kname, first)
value = self.putSubItem(vname, second)
if self.isCli:
self.putEmptyValue()
else:
if index is not None:
self.putField('keyprefix', '[%s] ' % index)
self.putField('key', key.value)
if key.encoding is not None:
self.putField('keyencoded', key.encoding)
self.putValue(value.value, value.encoding)
def putEnumValue(self, ival, vals):
nice = vals.get(ival, None)
display = ('%d' % ival) if nice is None else ('%s (%d)' % (nice, ival))
self.putValue(display)
def putCallItem(self, name, rettype, value, func, *args):
with SubItem(self, name):
try:
result = self.callHelper(rettype, value, func, args)
except Exception as error:
if self.passExceptions:
raise error
children = [('error', error)]
self.putSpecialValue("notcallable", children=children)
else:
self.putItem(result)
def call(self, rettype, value, func, *args):
return self.callHelper(rettype, value, func, args)
def putAddress(self, address):
if address is not None and not self.isCli:
self.put('address="0x%x",' % address)
def putPlainChildren(self, value, dumpBase=True):
self.putExpandable()
if self.isExpanded():
self.putEmptyValue(-99)
with Children(self):
self.putFields(value, dumpBase)
def putNamedChildren(self, values, names):
self.putEmptyValue(-99)
self.putExpandable()
if self.isExpanded():
with Children(self):
for n, v in zip(names, values):
self.putSubItem(n, v)
def prettySymbolByAddress(self, address):
return '0x%x' % address
def putSymbolValue(self, address):
self.putValue(self.prettySymbolByAddress(address))
def putVTableChildren(self, item, itemCount):
p = item.pointer()
for i in range(itemCount):
deref = self.extractPointer(p)
if deref == 0:
itemCount = i
break
with SubItem(self, i):
self.putItem(self.createPointerValue(deref, 'void'))
p += self.ptrSize()
return itemCount
def putFields(self, value, dumpBase=True):
baseIndex = 0
for item in value.members(True):
if item.name is not None:
if item.name.startswith('_vptr.') or item.name.startswith('__vfptr'):
with SubItem(self, '[vptr]'):
# int (**)(void)
self.putType(' ')
self.putSortGroup(20)
self.putValue(item.name)
n = 100
if self.isExpanded():
with Children(self):
n = self.putVTableChildren(item, n)
self.putNumChild(n)
continue
if item.isBaseClass and dumpBase:
baseIndex += 1
# We cannot use nativeField.name as part of the iname as
# it might contain spaces and other strange characters.
with UnnamedSubItem(self, "@%d" % baseIndex):
self.putField('iname', self.currentIName)
self.putField('name', '[%s]' % item.name)
if not self.isCli:
self.putSortGroup(1000 - baseIndex)
self.putAddress(item.address())
self.putItem(item)
continue
with SubItem(self, item.name):
self.putItem(item)
def putExpandable(self):
self.putNumChild(1)
self.expandableINames.add(self.currentIName)
if self.isCli:
self.putValue('{...}', -99)
def putMembersItem(self, value, sortorder=10):
with SubItem(self, '[members]'):
self.putSortGroup(sortorder)
self.putPlainChildren(value)
def put(self, stuff):
self.output += stuff
def check(self, exp):
if not exp:
raise RuntimeError('Check failed: %s' % exp)
def checkRef(self, ref):
# Assume there aren't a million references to any object.
self.check(ref >= -1)
self.check(ref < 1000000)
def checkIntType(self, thing):
if not self.isInt(thing):
raise RuntimeError('Expected an integral value, got %s' % type(thing))
def readToFirstZero(self, base, tsize, maximum):
self.checkIntType(base)
self.checkIntType(tsize)
self.checkIntType(maximum)
code = self.packCode + (None, 'b', 'H', None, 'I')[tsize]
#blob = self.readRawMemory(base, 1)
blob = bytes()
while maximum > 1:
try:
blob = self.readRawMemory(base, maximum)
break
except:
maximum = int(maximum / 2)
self.warn('REDUCING READING MAXIMUM TO %s' % maximum)
#DumperBase.warn('BASE: 0x%x TSIZE: %s MAX: %s' % (base, tsize, maximum))
for i in range(0, maximum, tsize):
t = struct.unpack_from(code, blob, i)[0]
if t == 0:
return 0, i, self.hexencode(blob[:i])
# Real end is unknown.
return -1, maximum, self.hexencode(blob[:maximum])
def encodeCArray(self, p, tsize, limit):
elided, shown, blob = self.readToFirstZero(p, tsize, limit)
return elided, blob
def putItemCount(self, count, maximum=1000000000):
# This needs to override the default value, so don't use 'put' directly.
if count > maximum:
self.putSpecialValue('minimumitemcount', maximum)
else:
self.putSpecialValue('itemcount', count)
self.putNumChild(count)
def resultToMi(self, value):
if isinstance(value, bool):
return '"%d"' % int(value)
if isinstance(value, dict):
return '{' + ','.join(['%s=%s' % (k, self.resultToMi(v))
for (k, v) in list(value.items())]) + '}'
if isinstance(value, list):
return '[' + ','.join([self.resultToMi(k)
for k in value]) + ']'
return '"%s"' % value
def variablesToMi(self, value, prefix):
if isinstance(value, bool):
return '"%d"' % int(value)
if isinstance(value, dict):
pairs = []
for (k, v) in list(value.items()):
if k == 'iname':
if v.startswith('.'):
v = '"%s%s"' % (prefix, v)
else:
v = '"%s"' % v
else:
v = self.variablesToMi(v, prefix)
pairs.append('%s=%s' % (k, v))
return '{' + ','.join(pairs) + '}'
if isinstance(value, list):
index = 0
pairs = []
for item in value:
if item.get('type', '') == 'function':
continue
name = item.get('name', '')
if len(name) == 0:
name = str(index)
index += 1
pairs.append((name, self.variablesToMi(item, prefix)))
pairs.sort(key=lambda pair: pair[0])
return '[' + ','.join([pair[1] for pair in pairs]) + ']'
return '"%s"' % value
def filterPrefix(self, prefix, items):
return [i[len(prefix):] for i in items if i.startswith(prefix)]
def tryFetchInterpreterVariables(self, args):
if not int(args.get('nativemixed', 0)):
return (False, '')
context = args.get('context', '')
if not len(context):
return (False, '')
expanded = args.get('expanded')
args['expanded'] = self.filterPrefix('local', expanded)
res = self.sendInterpreterRequest('variables', args)