aboutsummaryrefslogtreecommitdiffstats
path: root/share/qtcreator/debugger/gdbbridge.py
blob: ecc53a8f32888f7a6cce38caa023cbc88dfbc279 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
############################################################################
#
# 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.
#
############################################################################

try:
    import __builtin__
except:
    import builtins

import gdb
import os
import os.path
import re
import sys
import struct
import tempfile

from dumper import DumperBase, Children, toInteger, TopLevelItem
from utils import TypeCode

#######################################################################
#
# Infrastructure
#
#######################################################################


def safePrint(output):
    try:
        print(output)
    except:
        out = ''
        for c in output:
            cc = ord(c)
            if cc > 127:
                out += '\\\\%d' % cc
            elif cc < 0:
                out += '\\\\%d' % (cc + 256)
            else:
                out += c
        print(out)


def registerCommand(name, func):

    class Command(gdb.Command):
        def __init__(self):
            super(Command, self).__init__(name, gdb.COMMAND_OBSCURE)

        def invoke(self, args, from_tty):
            safePrint(func(args))

    Command()


#######################################################################
#
# Convenience
#
#######################################################################

# For CLI dumper use, see README.txt
class PPCommand(gdb.Command):
    def __init__(self):
        super(PPCommand, self).__init__('pp', gdb.COMMAND_OBSCURE)

    def invoke(self, args, from_tty):
        print(theCliDumper.fetchVariable(args))


PPCommand()

# Just convenience for 'python print gdb.parse_and_eval(...)'


class PPPCommand(gdb.Command):
    def __init__(self):
        super(PPPCommand, self).__init__('ppp', gdb.COMMAND_OBSCURE)

    def invoke(self, args, from_tty):
        print(gdb.parse_and_eval(args))


PPPCommand()


def scanStack(p, n):
    p = int(p)
    r = []
    for i in range(n):
        f = gdb.parse_and_eval('{void*}%s' % p)
        m = gdb.execute('info symbol %s' % f, to_string=True)
        if not m.startswith('No symbol matches'):
            r.append(m)
        p += f.type.sizeof
    return r


class ScanStackCommand(gdb.Command):
    def __init__(self):
        super(ScanStackCommand, self).__init__('scanStack', gdb.COMMAND_OBSCURE)

    def invoke(self, args, from_tty):
        if len(args) == 0:
            args = 20
        safePrint(scanStack(gdb.parse_and_eval('$sp'), int(args)))


ScanStackCommand()


#######################################################################
#
# Import plain gdb pretty printers
#
#######################################################################

class PlainDumper():
    def __init__(self, printer):
        self.printer = printer
        self.typeCache = {}

    def __call__(self, d, value):
        try:
            printer = self.printer.gen_printer(value.nativeValue)
        except:
            printer = self.printer.invoke(value.nativeValue)
        d.putType(value.nativeValue.type.name)
        val = printer.to_string()
        if isinstance(val, str):
            # encode and avoid extra quotes ('"') at beginning and end
            d.putValue(d.hexencode(val), 'utf8:1:0')
        elif sys.version_info[0] <= 2 and isinstance(val, unicode):
            d.putValue(val)
        elif val is not None:  # Assuming LazyString
            d.putCharArrayValue(val.address, val.length,
                                val.type.target().sizeof)

        lister = getattr(printer, 'children', None)
        if lister is None:
            d.putNumChild(0)
        else:
            if d.isExpanded():
                children = lister()
                with Children(d):
                    i = 0
                    for (name, child) in children:
                        d.putSubItem(name, d.fromNativeValue(child))
                        i += 1
                        if i > 1000:
                            break
            d.putNumChild(1)


def importPlainDumpers(args):
    if args == 'off':
        try:
            gdb.execute('disable pretty-printer .* .*')
        except:
            # Might occur in non-ASCII directories
            DumperBase.warn('COULD NOT DISABLE PRETTY PRINTERS')
    else:
        theDumper.importPlainDumpers()


registerCommand('importPlainDumpers', importPlainDumpers)


class OutputSaver():
    def __init__(self, d):
        self.d = d

    def __enter__(self):
        self.savedOutput = self.d.output
        self.d.output = ''

    def __exit__(self, exType, exValue, exTraceBack):
        if self.d.passExceptions and exType is not None:
            self.d.showException('OUTPUTSAVER', exType, exValue, exTraceBack)
            self.d.output = self.savedOutput
        else:
            self.savedOutput += self.d.output
            self.d.output = self.savedOutput
        return False


#######################################################################
#
# The Dumper Class
#
#######################################################################


class Dumper(DumperBase):

    def __init__(self):
        DumperBase.__init__(self)

        # These values will be kept between calls to 'fetchVariables'.
        self.isGdb = True
        self.typeCache = {}
        self.interpreterBreakpointResolvers = []

    def prepare(self, args):
        self.output = ''
        self.setVariableFetchingOptions(args)

    def fromFrameValue(self, nativeValue):
        #DumperBase.warn('FROM FRAME VALUE: %s' % nativeValue.address)
        val = nativeValue
        try:
            val = nativeValue.cast(nativeValue.dynamic_type)
        except:
            pass
        return self.fromNativeValue(val)

    def fromNativeValue(self, nativeValue):
        #DumperBase.warn('FROM NATIVE VALUE: %s' % nativeValue)
        self.check(isinstance(nativeValue, gdb.Value))
        nativeType = nativeValue.type
        code = nativeType.code
        if code == gdb.TYPE_CODE_REF:
            targetType = self.fromNativeType(nativeType.target().unqualified())
            val = self.createReferenceValue(toInteger(nativeValue.address), targetType)
            val.nativeValue = nativeValue
            #DumperBase.warn('CREATED REF: %s' % val)
            return val
        if code == gdb.TYPE_CODE_PTR:
            try:
                nativeTargetValue = nativeValue.dereference()
            except:
                nativeTargetValue = None
            targetType = self.fromNativeType(nativeType.target().unqualified())
            val = self.createPointerValue(toInteger(nativeValue), targetType)
            # The nativeValue is needed in case of multiple inheritance, see
            # QTCREATORBUG-17823. Using it triggers nativeValueDereferencePointer()
            # later which
            # is surprisingly expensive.
            val.nativeValue = nativeValue
            #DumperBase.warn('CREATED PTR 1: %s' % val)
            if nativeValue.address is not None:
                val.laddress = toInteger(nativeValue.address)
            #DumperBase.warn('CREATED PTR 2: %s' % val)
            return val
        if code == gdb.TYPE_CODE_TYPEDEF:
            targetType = nativeType.strip_typedefs().unqualified()
            #DumperBase.warn('TARGET TYPE: %s' % targetType)
            if targetType.code == gdb.TYPE_CODE_ARRAY:
                val = self.Value(self)
            else:
                try:
                    # Cast may fail for arrays, for typedefs to __uint128_t with
                    # gdb.error: That operation is not available on integers
                    # of more than 8 bytes.
                    # See test for Bug5799, QTCREATORBUG-18450.
                    val = self.fromNativeValue(nativeValue.cast(targetType))
                except:
                    val = self.Value(self)
            #DumperBase.warn('CREATED TYPEDEF: %s' % val)
        else:
            val = self.Value(self)

        val.nativeValue = nativeValue
        if nativeValue.address is not None:
            val.laddress = toInteger(nativeValue.address)
        else:
            size = nativeType.sizeof
            chars = self.lookupNativeType('unsigned char')
            y = nativeValue.cast(chars.array(0, int(nativeType.sizeof - 1)))
            buf = bytearray(struct.pack('x' * size))
            for i in range(size):
                try:
                    buf[i] = int(y[i])
                except:
                    pass
            val.ldata = bytes(buf)

        val.type = self.fromNativeType(nativeType)
        val.lIsInScope = not nativeValue.is_optimized_out
        code = nativeType.code
        if code == gdb.TYPE_CODE_ENUM:
            val.ldisplay = str(nativeValue)
            intval = int(nativeValue)
            if val.ldisplay != intval:
                val.ldisplay += ' (%s)' % intval
        elif code == gdb.TYPE_CODE_COMPLEX:
            val.ldisplay = str(nativeValue)
        #elif code == gdb.TYPE_CODE_ARRAY:
        #    val.type.ltarget = nativeValue[0].type.unqualified()
        return val

    def ptrSize(self):
        result = gdb.lookup_type('void').pointer().sizeof
        self.ptrSize = lambda: result
        return result

    def fromNativeType(self, nativeType):
        self.check(isinstance(nativeType, gdb.Type))
        code = nativeType.code
        #DumperBase.warn('FROM NATIVE TYPE: %s' % nativeType)
        nativeType = nativeType.unqualified()

        if code == gdb.TYPE_CODE_PTR:
            #DumperBase.warn('PTR')
            targetType = self.fromNativeType(nativeType.target().unqualified())
            return self.createPointerType(targetType)

        if code == gdb.TYPE_CODE_REF:
            #DumperBase.warn('REF')
            targetType = self.fromNativeType(nativeType.target().unqualified())
            return self.createReferenceType(targetType)

        if hasattr(gdb, "TYPE_CODE_RVALUE_REF"):
            if code == gdb.TYPE_CODE_RVALUE_REF:
                #DumperBase.warn('RVALUEREF')
                targetType = self.fromNativeType(nativeType.target())
                return self.createRValueReferenceType(targetType)

        if code == gdb.TYPE_CODE_ARRAY:
            #DumperBase.warn('ARRAY')
            nativeTargetType = nativeType.target().unqualified()
            targetType = self.fromNativeType(nativeTargetType)
            if nativeType.sizeof == 0:
                # QTCREATORBUG-23998, note that nativeType.name == None here,
                # whereas str(nativeType) returns sth like 'QObject [5]'
                count = self.arrayItemCountFromTypeName(str(nativeType), 1)
            else:
                count = nativeType.sizeof // nativeTargetType.sizeof
            return self.createArrayType(targetType, count)

        if code == gdb.TYPE_CODE_TYPEDEF:
            #DumperBase.warn('TYPEDEF')
            nativeTargetType = nativeType.unqualified()
            while nativeTargetType.code == gdb.TYPE_CODE_TYPEDEF:
                nativeTargetType = nativeTargetType.strip_typedefs().unqualified()
            targetType = self.fromNativeType(nativeTargetType)
            return self.createTypedefedType(targetType, str(nativeType),
                                            self.nativeTypeId(nativeType))

        if code == gdb.TYPE_CODE_ERROR:
            self.warn('Type error: %s' % nativeType)
            return self.Type(self, '')

        typeId = self.nativeTypeId(nativeType)
        res = self.typeData.get(typeId, None)
        if res is None:
            tdata = self.TypeData(self)
            tdata.name = str(nativeType)
            tdata.typeId = typeId
            tdata.lbitsize = nativeType.sizeof * 8
            tdata.code = {
                #gdb.TYPE_CODE_TYPEDEF : TypeCode.Typedef, # Handled above.
                gdb.TYPE_CODE_METHOD: TypeCode.Function,
                gdb.TYPE_CODE_VOID: TypeCode.Void,
                gdb.TYPE_CODE_FUNC: TypeCode.Function,
                gdb.TYPE_CODE_METHODPTR: TypeCode.Function,
                gdb.TYPE_CODE_MEMBERPTR: TypeCode.Function,
                #gdb.TYPE_CODE_PTR : TypeCode.Pointer,  # Handled above.
                #gdb.TYPE_CODE_REF : TypeCode.Reference,  # Handled above.
                gdb.TYPE_CODE_BOOL: TypeCode.Integral,
                gdb.TYPE_CODE_CHAR: TypeCode.Integral,
                gdb.TYPE_CODE_INT: TypeCode.Integral,
                gdb.TYPE_CODE_FLT: TypeCode.Float,
                gdb.TYPE_CODE_ENUM: TypeCode.Enum,
                #gdb.TYPE_CODE_ARRAY : TypeCode.Array,
                gdb.TYPE_CODE_STRUCT: TypeCode.Struct,
                gdb.TYPE_CODE_UNION: TypeCode.Struct,
                gdb.TYPE_CODE_COMPLEX: TypeCode.Complex,
                gdb.TYPE_CODE_STRING: TypeCode.FortranString,
            }[code]
            if tdata.code == TypeCode.Enum:
                tdata.enumDisplay = lambda intval, addr, form: \
                    self.nativeTypeEnumDisplay(nativeType, intval, form)
            if tdata.code == TypeCode.Struct:
                tdata.lalignment = lambda: \
                    self.nativeStructAlignment(nativeType)
                tdata.lfields = lambda value: \
                    self.listMembers(value, nativeType)
            tdata.templateArguments = self.listTemplateParameters(nativeType)
            self.registerType(typeId, tdata)  # Fix up fields and template args
        #    warn('CREATE TYPE: %s' % typeId)
        #else:
        #    warn('REUSE TYPE: %s' % typeId)
        return self.Type(self, typeId)

    def listTemplateParameters(self, nativeType):
        targs = []
        pos = 0
        while True:
            try:
                targ = nativeType.template_argument(pos)
            except:
                break
            if isinstance(targ, gdb.Type):
                targs.append(self.fromNativeType(targ.unqualified()))
            elif isinstance(targ, gdb.Value):
                targs.append(self.fromNativeValue(targ).value())
            else:
                raise RuntimeError('UNKNOWN TEMPLATE PARAMETER')
            pos += 1
        targs2 = self.listTemplateParametersManually(str(nativeType))
        return targs if len(targs) >= len(targs2) else targs2

    def nativeTypeEnumDisplay(self, nativeType, intval, form):
        try:
            enumerators = []
            for field in nativeType.fields():
                # If we found an exact match, return it immediately
                if field.enumval == intval:
                    return field.name + ' (' + (form % intval) + ')'
                enumerators.append((field.name, field.enumval))

            # No match was found, try to return as flags
            enumerators.sort(key=lambda x: x[1])
            flags = []
            v = intval
            found = False
            for (name, value) in enumerators:
                if v & value != 0:
                    flags.append(name)
                    v = v & ~value
                    found = True
            if not found or v != 0:
                # Leftover value
                flags.append('unknown: %d' % v)
            return '(' + " | ".join(flags) + ') (' + (form % intval) + ')'
        except:
            pass
        return form % intval

    def nativeTypeId(self, nativeType):
        if nativeType and (nativeType.code == gdb.TYPE_CODE_TYPEDEF):
            return '%s{%s}' % (nativeType, nativeType.strip_typedefs())
        name = str(nativeType)
        if len(name) == 0:
            c = '0'
        elif name == 'union {...}':
            c = 'u'
        elif name.endswith('{...}'):
            c = 's'
        else:
            return name
        typeId = c + ''.join(['{%s:%s}' % (f.name, self.nativeTypeId(f.type))
                              for f in nativeType.fields()])
        return typeId

    def nativeStructAlignment(self, nativeType):
        #DumperBase.warn('NATIVE ALIGN FOR %s' % nativeType.name)
        def handleItem(nativeFieldType, align):
            a = self.fromNativeType(nativeFieldType).alignment()
            return a if a > align else align
        align = 1
        for f in nativeType.fields():
            align = handleItem(f.type, align)
        return align

        #except:
        #    # Happens in the BoostList dumper for a 'const bool'
        #    # item named 'constant_time_size'. There isn't anything we can do
        #    # in this case.
        #   pass

        #yield value.extractField(field)

    def memberFromNativeFieldAndValue(self, nativeField, nativeValue, fieldName, value):
        nativeMember = self.nativeMemberFromField(nativeValue, nativeField)
        if nativeMember is None:
            val = self.Value(self)
            val.name = fieldName
            val.type = self.fromNativeType(nativeField.type)
            val.lIsInScope = False
            return val
        val = self.fromNativeValue(nativeMember)
        nativeFieldType = nativeField.type.unqualified()
        if nativeField.bitsize:
            val.lvalue = int(nativeMember)
            val.laddress = None
            fieldType = self.fromNativeType(nativeFieldType)
            val.type = self.createBitfieldType(fieldType, nativeField.bitsize)
        val.isBaseClass = nativeField.is_base_class
        val.name = fieldName
        return val

    def nativeMemberFromField(self, nativeValue, nativeField):
        if nativeField.is_base_class:
            return nativeValue.cast(nativeField.type)
        try:
            return nativeValue[nativeField]
        except:
            pass
        try:
            return nativeValue[nativeField.name]
        except:
            pass
        return None

    def listMembers(self, value, nativeType):
        nativeValue = value.nativeValue

        anonNumber = 0

        #DumperBase.warn('LISTING FIELDS FOR %s' % nativeType)
        for nativeField in nativeType.fields():
            fieldName = nativeField.name
            # Something without a name.
            # Anonymous union? We need a dummy name to distinguish
            # multiple anonymous unions in the struct.
            # Since GDB commit b5b08fb4 anonymous structs get also reported
            # with a 'None' name.
            if fieldName is None or len(fieldName) == 0:
                # Something without a name.
                # Anonymous union? We need a dummy name to distinguish
                # multiple anonymous unions in the struct.
                anonNumber += 1
                fieldName = '#%s' % anonNumber
            #DumperBase.warn('FIELD: %s' % fieldName)
            # hasattr(nativeField, 'bitpos') == False indicates a static field,
            # but if we have access to a nativeValue .fromNativeField will
            # also succeed. We essentially skip only static members from
            # artificial values, like array members constructed from address.
            if hasattr(nativeField, 'bitpos') or nativeValue is not None:
                yield self.fromNativeField(nativeField, nativeValue, fieldName)

    def fromNativeField(self, nativeField, nativeValue, fieldName):
        nativeFieldType = nativeField.type.unqualified()
        #DumperBase.warn('  TYPE: %s' % nativeFieldType)
        #DumperBase.warn('  TYPEID: %s' % self.nativeTypeId(nativeFieldType))

        if hasattr(nativeField, 'bitpos'):
            bitpos = nativeField.bitpos
        else:
            bitpos = 0

        if hasattr(nativeField, 'bitsize') and nativeField.bitsize != 0:
            bitsize = nativeField.bitsize
        else:
            bitsize = 8 * nativeFieldType.sizeof

        fieldType = self.fromNativeType(nativeFieldType)
        if bitsize != nativeFieldType.sizeof * 8:
            fieldType = self.createBitfieldType(fieldType, bitsize)
        else:
            fieldType = fieldType

        if nativeValue is None:
            extractor = None
        else:
            extractor = lambda value, \
                capturedNativeField = nativeField, \
                capturedNativeValue = nativeValue, \
                capturedFieldName = fieldName: \
                self.memberFromNativeFieldAndValue(capturedNativeField,
                                                   capturedNativeValue,
                                                   capturedFieldName,
                                                   value)

        #DumperBase.warn("FOUND NATIVE FIELD: %s bitpos: %s" % (fieldName, bitpos))
        return self.Field(dumper=self, name=fieldName, isBase=nativeField.is_base_class,
                          bitsize=bitsize, bitpos=bitpos, type=fieldType,
                          extractor=extractor)

    def listLocals(self, partialVar):
        frame = gdb.selected_frame()

        try:
            block = frame.block()
            #DumperBase.warn('BLOCK: %s ' % block)
        except RuntimeError as error:
            #DumperBase.warn('BLOCK IN FRAME NOT ACCESSIBLE: %s' % error)
            return []
        except:
            self.warn('BLOCK NOT ACCESSIBLE FOR UNKNOWN REASONS')
            return []

        items = []
        shadowed = {}
        while True:
            if block is None:
                self.warn("UNEXPECTED 'None' BLOCK")
                break
            for symbol in block:

                # Filter out labels etc.
                if symbol.is_variable or symbol.is_argument:
                    name = symbol.print_name

                    if name in ('__in_chrg', '__PRETTY_FUNCTION__'):
                        continue

                    if partialVar is not None and partialVar != name:
                        continue

                    # 'NotImplementedError: Symbol type not yet supported in
                    # Python scripts.'
                    #DumperBase.warn('SYMBOL %s  (%s, %s)): ' % (symbol, name, symbol.name))
                    if self.passExceptions and not self.isTesting:
                        nativeValue = frame.read_var(name, block)
                        value = self.fromFrameValue(nativeValue)
                        value.name = name
                        #DumperBase.warn('READ 0: %s' % value.stringify())
                        items.append(value)
                        continue

                    try:
                        # Same as above, but for production.
                        nativeValue = frame.read_var(name, block)
                        value = self.fromFrameValue(nativeValue)
                        value.name = name
                        #DumperBase.warn('READ 1: %s' % value.stringify())
                        items.append(value)
                        continue
                    except:
                        pass

                    try:
                        #DumperBase.warn('READ 2: %s' % item.value)
                        value = self.fromFrameValue(frame.read_var(name))
                        value.name = name
                        items.append(value)
                        continue
                    except:
                        # RuntimeError: happens for
                        #     void foo() { std::string s; std::wstring w; }
                        # ValueError: happens for (as of 2010/11/4)
                        #     a local struct as found e.g. in
                        #     gcc sources in gcc.c, int execute()
                        pass

                    try:
                        #DumperBase.warn('READ 3: %s %s' % (name, item.value))
                        #DumperBase.warn('ITEM 3: %s' % item.value)
                        value = self.fromFrameValue(gdb.parse_and_eval(name))
                        value.name = name
                        items.append(value)
                    except:
                        # Can happen in inlined code (see last line of
                        # RowPainter::paintChars(): 'RuntimeError:
                        # No symbol '__val' in current context.\n'
                        pass

            # The outermost block in a function has the function member
            # FIXME: check whether this is guaranteed.
            if block.function is not None:
                break

            block = block.superblock

        return items

    def reportToken(self, args):
        pass

    # Hack to avoid QDate* dumper timeouts with GDB 7.4 on 32 bit
    # due to misaligned %ebx in SSE calls (qstring.cpp:findChar)
    # This seems to be fixed in 7.9 (or earlier)
    def canCallLocale(self):
        return self.ptrSize() == 8

    def fetchVariables(self, args):
        self.resetStats()
        self.prepare(args)

        self.isBigEndian = gdb.execute('show endian', to_string=True).find('big endian') > 0
        self.packCode = '>' if self.isBigEndian else '<'

        (ok, res) = self.tryFetchInterpreterVariables(args)
        if ok:
            safePrint(res)
            return

        self.output += 'data=['

        partialVar = args.get('partialvar', '')
        isPartial = len(partialVar) > 0
        partialName = partialVar.split('.')[1].split('@')[0] if isPartial else None

        variables = self.listLocals(partialName)
        #DumperBase.warn('VARIABLES: %s' % variables)

        # Take care of the return value of the last function call.
        if len(self.resultVarName) > 0:
            try:
                value = self.parseAndEvaluate(self.resultVarName)
                value.name = self.resultVarName
                value.iname = 'return.' + self.resultVarName
                variables.append(value)
            except:
                # Don't bother. It's only supplementary information anyway.
                pass

        self.handleLocals(variables)
        self.handleWatches(args)

        self.output += '],typeinfo=['
        for name in self.typesToReport.keys():
            typeobj = self.typesToReport[name]
            # Happens e.g. for '(anonymous namespace)::InsertDefOperation'
            #if not typeobj is None:
            #    self.output.append('{name="%s",size="%s"}'
            #        % (self.hexencode(name), typeobj.sizeof))
        self.output += ']'
        self.typesToReport = {}

        if self.forceQtNamespace:
            self.qtNamespaceToReport = self.qtNamespace()

        if self.qtNamespaceToReport:
            self.output += ',qtnamespace="%s"' % self.qtNamespaceToReport
            self.qtNamespaceToReport = None

        self.output += ',partial="%d"' % isPartial
        self.output += ',counts=%s' % self.counts
        self.output += ',timings=%s' % self.timings
        self.reportResult(self.output)

    def parseAndEvaluate(self, exp):
        val = self.nativeParseAndEvaluate(exp)
        return None if val is None else self.fromNativeValue(val)

    def nativeParseAndEvaluate(self, exp):
        #DumperBase.warn('EVALUATE "%s"' % exp)
        try:
            val = gdb.parse_and_eval(exp)
            return val
        except RuntimeError as error:
            if self.passExceptions:
                self.warn("Cannot evaluate '%s': %s" % (exp, error))
            return None

    def callHelper(self, rettype, value, function, args):
        if self.isWindowsTarget():
            raise Exception("gdb crashes when calling functions on Windows")
        # args is a tuple.
        arg = ''
        for i in range(len(args)):
            if i:
                arg += ','
            a = args[i]
            if (':' in a) and not ("'" in a):
                arg = "'%s'" % a
            else:
                arg += a

        #DumperBase.warn('CALL: %s -> %s(%s)' % (value, function, arg))
        typeName = value.type.name
        if typeName.find(':') >= 0:
            typeName = "'" + typeName + "'"
        # 'class' is needed, see http://sourceware.org/bugzilla/show_bug.cgi?id=11912
        #exp = '((class %s*)%s)->%s(%s)' % (typeName, value.laddress, function, arg)
        addr = value.address()
        if addr is None:
            addr = self.pokeValue(value)
        #DumperBase.warn('PTR: %s -> %s(%s)' % (value, function, addr))
        exp = '((%s*)0x%x)->%s(%s)' % (typeName, addr, function, arg)
        #DumperBase.warn('CALL: %s' % exp)
        result = gdb.parse_and_eval(exp)
        #DumperBase.warn('  -> %s' % result)
        res = self.fromNativeValue(result)
        if value.address() is None:
            self.releaseValue(addr)
        return res

    def makeExpression(self, value):
        typename = '::' + value.type.name
        #DumperBase.warn('  TYPE: %s' % typename)
        exp = '(*(%s*)(0x%x))' % (typename, value.address())
        #DumperBase.warn('  EXP: %s' % exp)
        return exp

    def makeStdString(init):
        # Works only for small allocators, but they are usually empty.
        gdb.execute('set $d=(std::string*)calloc(sizeof(std::string), 2)')
        gdb.execute('call($d->basic_string("' + init +
                    '",*(std::allocator<char>*)(1+$d)))')
        value = gdb.parse_and_eval('$d').dereference()
        return value

    def pokeValue(self, value):
        # Allocates inferior memory and copies the contents of value.
        # Returns a pointer to the copy.
        # Avoid malloc symbol clash with QVector
        size = value.type.size()
        data = value.data()
        h = self.hexencode(data)
        #DumperBase.warn('DATA: %s' % h)
        string = ''.join('\\x' + h[2 * i:2 * i + 2] for i in range(size))
        exp = '(%s*)memcpy(calloc(%d, 1), "%s", %d)' \
            % (value.type.name, size, string, size)
        #DumperBase.warn('EXP: %s' % exp)
        res = gdb.parse_and_eval(exp)
        #DumperBase.warn('RES: %s' % res)
        return toInteger(res)

    def releaseValue(self, address):
        gdb.parse_and_eval('free(0x%x)' % address)

    def setValue(self, address, typename, value):
        cmd = 'set {%s}%s=%s' % (typename, address, value)
        gdb.execute(cmd)

    def setValues(self, address, typename, values):
        cmd = 'set {%s[%s]}%s={%s}' \
            % (typename, len(values), address, ','.join(map(str, values)))
        gdb.execute(cmd)

    def selectedInferior(self):
        try:
            # gdb.Inferior is new in gdb 7.2
            self.cachedInferior = gdb.selected_inferior()
        except:
            # Pre gdb 7.4. Right now we don't have more than one inferior anyway.
            self.cachedInferior = gdb.inferiors()[0]

        # Memoize result.
        self.selectedInferior = lambda: self.cachedInferior
        return self.cachedInferior

    def readRawMemory(self, address, size):
        #DumperBase.warn('READ: %s FROM 0x%x' % (size, address))
        if address == 0 or size == 0:
            return bytes()
        res = self.selectedInferior().read_memory(address, size)
        return res

    def findStaticMetaObject(self, type):
        symbolName = type.name + '::staticMetaObject'
        symbol = gdb.lookup_global_symbol(symbolName, gdb.SYMBOL_VAR_DOMAIN)
        if not symbol:
            return 0
        try:
            # Older GDB ~7.4 don't have gdb.Symbol.value()
            return toInteger(symbol.value().address)
        except:
            pass

        address = gdb.parse_and_eval("&'%s'" % symbolName)
        return toInteger(address)

    def isArmArchitecture(self):
        return 'arm' in gdb.TARGET_CONFIG.lower()

    def isQnxTarget(self):
        return 'qnx' in gdb.TARGET_CONFIG.lower()

    def isWindowsTarget(self):
        # We get i686-w64-mingw32
        return 'mingw' in gdb.TARGET_CONFIG.lower()

    def isMsvcTarget(self):
        return False

    def prettySymbolByAddress(self, address):
        try:
            return str(gdb.parse_and_eval('(void(*))0x%x' % address))
        except:
            return '0x%x' % address

    def qtVersionString(self):
        try:
            return str(gdb.lookup_symbol('qVersion')[0].value()())
        except:
            pass
        try:
            ns = self.qtNamespace()
            return str(gdb.parse_and_eval("((const char*(*)())'%sqVersion')()" % ns))
        except:
            pass
        return None

    def qtVersion(self):
        try:
            # Only available with Qt 5.3+
            qtversion = int(str(gdb.parse_and_eval('((void**)&qtHookData)[2]')), 16)
            self.qtVersion = lambda: qtversion
            return qtversion
        except:
            pass

        try:
            version = self.qtVersionString()
            (major, minor, patch) = version[version.find('"') + 1:version.rfind('"')].split('.')
            qtversion = 0x10000 * int(major) + 0x100 * int(minor) + int(patch)
            self.qtVersion = lambda: qtversion
            return qtversion
        except:
            # Use fallback until we have a better answer.
            return self.fallbackQtVersion

    def createSpecialBreakpoints(self, args):
        self.specialBreakpoints = []

        def newSpecial(spec):
            # GDB < 8.1 does not have the 'qualified' parameter here,
            # GDB >= 8.1 applies some generous pattern matching, hitting
            # e.g. also Foo::abort() when asking for '::abort'
            class Pre81SpecialBreakpoint(gdb.Breakpoint):
                def __init__(self, spec):
                    super(Pre81SpecialBreakpoint, self).__init__(spec,
                                                                 gdb.BP_BREAKPOINT, internal=True)
                    self.spec = spec

                def stop(self):
                    print("Breakpoint on '%s' hit." % self.spec)
                    return True

            class SpecialBreakpoint(gdb.Breakpoint):
                def __init__(self, spec):
                    super(SpecialBreakpoint, self).__init__(spec,
                                                            gdb.BP_BREAKPOINT,
                                                            internal=True,
                                                            qualified=True)
                    self.spec = spec

                def stop(self):
                    print("Breakpoint on '%s' hit." % self.spec)
                    return True

            try:
                return SpecialBreakpoint(spec)
            except:
                return Pre81SpecialBreakpoint(spec)

        # FIXME: ns is accessed too early. gdb.Breakpoint() has no
        # 'rbreak' replacement, and breakpoints created with
        # 'gdb.execute('rbreak...') cannot be made invisible.
        # So let's ignore the existing of namespaced builds for this
        # fringe feature here for now.
        ns = self.qtNamespace()
        if args.get('breakonabort', 0):
            self.specialBreakpoints.append(newSpecial('abort'))

        if args.get('breakonwarning', 0):
            self.specialBreakpoints.append(newSpecial(ns + 'qWarning'))
            self.specialBreakpoints.append(newSpecial(ns + 'QMessageLogger::warning'))

        if args.get('breakonfatal', 0):
            self.specialBreakpoints.append(newSpecial(ns + 'qFatal'))
            self.specialBreakpoints.append(newSpecial(ns + 'QMessageLogger::fatal'))

    #def threadname(self, maximalStackDepth, objectPrivateType):
    #    e = gdb.selected_frame()
    #    out = ''
    #    ns = self.qtNamespace()
    #    while True:
    #        maximalStackDepth -= 1
    #        if maximalStackDepth < 0:
    #            break
    #        e = e.older()
    #        if e == None or e.name() == None:
    #            break
    #        if e.name() in (ns + 'QThreadPrivate::start', '_ZN14QThreadPrivate5startEPv@4'):
    #            try:
    #                thrptr = e.read_var('thr').dereference()
    #                d_ptr = thrptr['d_ptr']['d'].cast(objectPrivateType).dereference()
    #                try:
    #                    objectName = d_ptr['objectName']
    #                except: # Qt 5
    #                    p = d_ptr['extraData']
    #                    if not self.isNull(p):
    #                        objectName = p.dereference()['objectName']
    #                if not objectName is None:
    #                    (data, size, alloc) = self.stringData(objectName)
    #                    if size > 0:
    #                         s = self.readMemory(data, 2 * size)
    #
    #                thread = gdb.selected_thread()
    #                inner = '{valueencoded="uf16:2:0",id="'
    #                inner += str(thread.num) + '",value="'
    #                inner += s
    #                #inner += self.encodeString(objectName)
    #                inner += '"},'
    #
    #                out += inner
    #            except:
    #                pass
    #    return out

    def threadnames(self, maximalStackDepth):
        # FIXME: This needs a proper implementation for MinGW, and only there.
        # Linux, Mac and QNX mirror the objectName() to the underlying threads,
        # so we get the names already as part of the -thread-info output.
        return '[]'
        #out = '['
        #oldthread = gdb.selected_thread()
        #if oldthread:
        #    try:
        #        objectPrivateType = gdb.lookup_type(ns + 'QObjectPrivate').pointer()
        #        inferior = self.selectedInferior()
        #        for thread in inferior.threads():
        #            thread.switch()
        #            out += self.threadname(maximalStackDepth, objectPrivateType)
        #    except:
        #        pass
        #    oldthread.switch()
        #return out + ']'

    def importPlainDumper(self, printer):
        name = printer.name.replace('::', '__')
        self.qqDumpers[name] = PlainDumper(printer)
        self.qqFormats[name] = ''

    def importPlainDumpers(self):
        for obj in gdb.objfiles():
            for printers in obj.pretty_printers + gdb.pretty_printers:
                for printer in printers.subprinters:
                    self.importPlainDumper(printer)

    def qtNamespace(self):
        # This function is replaced by handleQtCoreLoaded()
        return ''

    def findSymbol(self, symbolName):
        try:
            return toInteger(gdb.parse_and_eval("(size_t)&'%s'" % symbolName))
        except:
            return 0

    def handleNewObjectFile(self, objfile):
        name = objfile.filename
        if self.isWindowsTarget():
            qtCoreMatch = re.match(r'.*Qt5?Core[^/.]*d?\.dll', name)
        else:
            qtCoreMatch = re.match(r'.*/libQt5?Core[^/.]*\.so', name)

        if qtCoreMatch is not None:
            self.addDebugLibs(objfile)
            self.handleQtCoreLoaded(objfile)

    def addDebugLibs(self, objfile):
        # The directory where separate debug symbols are searched for
        # is "/usr/lib/debug".
        try:
            cooked = gdb.execute('show debug-file-directory', to_string=True)
            clean = cooked.split('"')[1]
            newdir = '/'.join(objfile.filename.split('/')[:-1])
            gdb.execute('set debug-file-directory %s:%s' % (clean, newdir))
        except:
            pass

    def handleQtCoreLoaded(self, objfile):
        fd, tmppath = tempfile.mkstemp()
        os.close(fd)
        cmd = 'maint print msymbols %s "%s"' % (tmppath, objfile.filename)
        try:
            symbols = gdb.execute(cmd, to_string=True)
        except:
            # command syntax depends on gdb version - below is gdb 8+
            cmd = 'maint print msymbols -objfile "%s" -- %s' % (objfile.filename, tmppath)
            try:
                symbols = gdb.execute(cmd, to_string=True)
            except:
                pass
        ns = ''
        with open(tmppath) as f:
            for line in f:
                if line.find('msgHandlerGrabbed ') >= 0:
                    # [11] b 0x7ffff683c000 _ZN4MynsL17msgHandlerGrabbedE
                    # section .tbss Myns::msgHandlerGrabbed  qlogging.cpp
                    ns = re.split(r'_ZN?(\d*)(\w*)L17msgHandlerGrabbedE? ', line)[2]
                    if len(ns):
                        ns += '::'
                    break
                if line.find('currentThreadData ') >= 0:
                    # [ 0] b 0x7ffff67d3000 _ZN2UUL17currentThreadDataE
                    # section .tbss  UU::currentThreadData qthread_unix.cpp\\n
                    ns = re.split(r'_ZN?(\d*)(\w*)L17currentThreadDataE? ', line)[2]
                    if len(ns):
                        ns += '::'
                    break
        os.remove(tmppath)

        lenns = len(ns)
        strns = ('%d%s' % (lenns - 2, ns[:lenns - 2])) if lenns else ''

        if lenns:
            # This might be wrong, but we can't do better: We found
            # a libQt5Core and could not extract a namespace.
            # The best guess is that there isn't any.
            self.qtNamespaceToReport = ns
            self.qtNamespace = lambda: ns

            sym = '_ZN%s7QObject11customEventEPNS_6QEventE' % strns
        else:
            sym = '_ZN7QObject11customEventEP6QEvent'
        self.qtCustomEventFunc = self.findSymbol(sym)

        sym += '@plt'
        self.qtCustomEventPltFunc = self.findSymbol(sym)

        sym = '_ZNK%s7QObject8propertyEPKc' % strns
        self.qtPropertyFunc = self.findSymbol(sym)

    def assignValue(self, args):
        typeName = self.hexdecode(args['type'])
        expr = self.hexdecode(args['expr'])
        value = self.hexdecode(args['value'])
        simpleType = int(args['simpleType'])
        ns = self.qtNamespace()
        if typeName.startswith(ns):
            typeName = typeName[len(ns):]
        typeName = typeName.replace('::', '__')
        pos = typeName.find('<')
        if pos != -1:
            typeName = typeName[0:pos]
        if typeName in self.qqEditable and not simpleType:
            #self.qqEditable[typeName](self, expr, value)
            expr = self.parseAndEvaluate(expr)
            self.qqEditable[typeName](self, expr, value)
        else:
            cmd = 'set variable (%s)=%s' % (expr, value)
            gdb.execute(cmd)

    def appendSolibSearchPath(self, args):
        new = list(map(self.hexdecode, args['path']))
        old = [gdb.parameter('solib-search-path')]
        gdb.execute('set solib-search-path %s' % args['separator'].join(old + new))

    def watchPoint(self, args):
        self.reportToken(args)
        ns = self.qtNamespace()
        lenns = len(ns)
        strns = ('%d%s' % (lenns - 2, ns[:lenns - 2])) if lenns else ''
        sym = '_ZN%s12QApplication8widgetAtEii' % strns
        expr = '%s(%s,%s)' % (sym, args['x'], args['y'])
        res = self.parseAndEvaluate(expr)
        p = 0 if res is None else res.pointer()
        n = ("'%sQWidget'" % ns) if lenns else 'QWidget'
        self.reportResult('selected="0x%x",expr="(%s*)0x%x"' % (p, n, p), args)

    def nativeValueDereferencePointer(self, value):
        # This is actually pretty expensive, up to 100ms.
        deref = value.nativeValue.dereference()
        return self.fromNativeValue(deref.cast(deref.dynamic_type))

    def nativeValueDereferenceReference(self, value):
        nativeValue = value.nativeValue
        return self.fromNativeValue(nativeValue.cast(nativeValue.type.target()))

    def nativeDynamicTypeName(self, address, baseType):
        # Needed for Gdb13393 test.
        nativeType = self.lookupNativeType(baseType.name)
        if nativeType is None:
            return None
        nativeTypePointer = nativeType.pointer()
        nativeValue = gdb.Value(address).cast(nativeTypePointer).dereference()
        val = nativeValue.cast(nativeValue.dynamic_type)
        return str(val.type)
        #try:
        #    vtbl = gdb.execute('info symbol {%s*}0x%x' % (baseType.name, address), to_string = True)
        #except:
        #    return None
        #pos1 = vtbl.find('vtable ')
        #if pos1 == -1:
        #    return None
        #pos1 += 11
        #pos2 = vtbl.find(' +', pos1)
        #if pos2 == -1:
        #    return None
        #return vtbl[pos1 : pos2]

    def nativeDynamicType(self, address, baseType):
        # Needed for Gdb13393 test.
        nativeType = self.lookupNativeType(baseType.name)
        if nativeType is None:
            return baseType
        nativeTypePointer = nativeType.pointer()
        nativeValue = gdb.Value(address).cast(nativeTypePointer).dereference()
        return self.fromNativeType(nativeValue.dynamic_type)

    def enumExpression(self, enumType, enumValue):
        return self.qtNamespace() + 'Qt::' + enumValue

    def lookupNativeType(self, typeName):
        nativeType = self.lookupNativeTypeHelper(typeName)
        if nativeType is not None:
            self.check(isinstance(nativeType, gdb.Type))
        return nativeType

    def lookupNativeTypeHelper(self, typeName):
        typeobj = self.typeCache.get(typeName)
        #DumperBase.warn('LOOKUP 1: %s -> %s' % (typeName, typeobj))
        if typeobj is not None:
            return typeobj

        if typeName == 'void':
            typeobj = gdb.lookup_type(typeName)
            self.typeCache[typeName] = typeobj
            self.typesToReport[typeName] = typeobj
            return typeobj

        #try:
        #    typeobj = gdb.parse_and_eval('{%s}&main' % typeName).typeobj
        #    if not typeobj is None:
        #        self.typeCache[typeName] = typeobj
        #        self.typesToReport[typeName] = typeobj
        #        return typeobj
        #except:
        #    pass

        # See http://sourceware.org/bugzilla/show_bug.cgi?id=13269
        # gcc produces '{anonymous}', gdb '(anonymous namespace)'
        # '<unnamed>' has been seen too. The only thing gdb
        # understands when reading things back is '(anonymous namespace)'
        if typeName.find('{anonymous}') != -1:
            ts = typeName
            ts = ts.replace('{anonymous}', '(anonymous namespace)')
            typeobj = self.lookupNativeType(ts)
            if typeobj is not None:
                self.typeCache[typeName] = typeobj
                self.typesToReport[typeName] = typeobj
                return typeobj

        #DumperBase.warn(" RESULT FOR 7.2: '%s': %s" % (typeName, typeobj))

        # This part should only trigger for
        # gdb 7.1 for types with namespace separators.
        # And anonymous namespaces.

        ts = typeName
        while True:
            if ts.startswith('class '):
                ts = ts[6:]
            elif ts.startswith('struct '):
                ts = ts[7:]
            elif ts.startswith('const '):
                ts = ts[6:]
            elif ts.startswith('volatile '):
                ts = ts[9:]
            elif ts.startswith('enum '):
                ts = ts[5:]
            elif ts.endswith(' const'):
                ts = ts[:-6]
            elif ts.endswith(' volatile'):
                ts = ts[:-9]
            elif ts.endswith('*const'):
                ts = ts[:-5]
            elif ts.endswith('*volatile'):
                ts = ts[:-8]
            else:
                break

        if ts.endswith('*'):
            typeobj = self.lookupNativeType(ts[0:-1])
            if typeobj is not None:
                typeobj = typeobj.pointer()
                self.typeCache[typeName] = typeobj
                self.typesToReport[typeName] = typeobj
                return typeobj

        try:
            #DumperBase.warn("LOOKING UP 1 '%s'" % ts)
            typeobj = gdb.lookup_type(ts)
        except RuntimeError as error:
            #DumperBase.warn("LOOKING UP 2 '%s' ERROR %s" % (ts, error))
            # See http://sourceware.org/bugzilla/show_bug.cgi?id=11912
            exp = "(class '%s'*)0" % ts
            try:
                typeobj = self.parse_and_eval(exp).type.target()
                #DumperBase.warn("LOOKING UP 3 '%s'" % typeobj)
            except:
                # Can throw 'RuntimeError: No type named class Foo.'
                pass
        except:
            #DumperBase.warn("LOOKING UP '%s' FAILED" % ts)
            pass

        if typeobj is not None:
            #DumperBase.warn('CACHING: %s' % typeobj)
            self.typeCache[typeName] = typeobj
            self.typesToReport[typeName] = typeobj

        # This could still be None as gdb.lookup_type('char[3]') generates
        # 'RuntimeError: No type named char[3]'
        #self.typeCache[typeName] = typeobj
        #self.typesToReport[typeName] = typeobj
        return typeobj

    def doContinue(self):
        gdb.execute('continue')

    def fetchStack(self, args):
        def fromNativePath(string):
            return string.replace('\\', '/')

        extraQml = int(args.get('extraqml', '0'))
        limit = int(args['limit'])
        if limit <= 0:
            limit = 10000

        self.prepare(args)
        self.output = ''

        i = 0
        if extraQml:
            frame = gdb.newest_frame()
            ns = self.qtNamespace()
            needle = self.qtNamespace() + 'QV4::ExecutionEngine'
            pat = '%sqt_v4StackTraceForEngine((void*)0x%x)'
            done = False
            while i < limit and frame and not done:
                block = None
                try:
                    block = frame.block()
                except:
                    pass
                if block is not None:
                    for symbol in block:
                        if symbol.is_variable or symbol.is_argument:
                            value = symbol.value(frame)
                            typeobj = value.type
                            if typeobj.code == gdb.TYPE_CODE_PTR:
                                dereftype = typeobj.target().unqualified()
                                if dereftype.name == needle:
                                    addr = toInteger(value)
                                    expr = pat % (ns, addr)
                                    res = str(gdb.parse_and_eval(expr))
                                    pos = res.find('"stack=[')
                                    if pos != -1:
                                        res = res[pos + 8:-2]
                                        res = res.replace('\\\"', '\"')
                                        res = res.replace('func=', 'function=')
                                        self.put(res)
                                        done = True
                                        break
                frame = frame.older()
                i += 1

        frame = gdb.newest_frame()
        self.currentCallContext = None
        while i < limit and frame:
            with OutputSaver(self):
                name = frame.name()
                functionName = '??' if name is None else name
                fileName = ''
                objfile = ''
                symtab = ''
                pc = frame.pc()
                sal = frame.find_sal()
                line = -1
                if sal:
                    line = sal.line
                    symtab = sal.symtab
                    if symtab is not None:
                        objfile = fromNativePath(symtab.objfile.filename)
                        fullname = symtab.fullname()
                        if fullname is None:
                            fileName = ''
                        else:
                            fileName = fromNativePath(fullname)

                if self.nativeMixed and functionName == 'qt_qmlDebugMessageAvailable':
                    interpreterStack = self.extractInterpreterStack()
                    #print('EXTRACTED INTEPRETER STACK: %s' % interpreterStack)
                    for interpreterFrame in interpreterStack.get('frames', []):
                        function = interpreterFrame.get('function', '')
                        fileName = interpreterFrame.get('file', '')
                        language = interpreterFrame.get('language', '')
                        lineNumber = interpreterFrame.get('line', 0)
                        context = interpreterFrame.get('context', 0)

                        self.put(('frame={function="%s",file="%s",'
                                  'line="%s",language="%s",context="%s"}')
                                 % (function, self.hexencode(fileName), lineNumber, language, context))

                    if False and self.isInternalInterpreterFrame(functionName):
                        frame = frame.older()
                        self.put(('frame={address="0x%x",function="%s",'
                                  'file="%s",line="%s",'
                                  'module="%s",language="c",usable="0"}') %
                                 (pc, functionName, fileName, line, objfile))
                        i += 1
                        frame = frame.older()
                        continue

                self.put(('frame={level="%s",address="0x%x",function="%s",'
                          'file="%s",line="%s",module="%s",language="c"}') %
                         (i, pc, functionName, fileName, line, objfile))

            frame = frame.older()
            i += 1
        self.reportResult('stack={frames=[' + self.output + ']}')

    def createResolvePendingBreakpointsHookBreakpoint(self, args):
        class Resolver(gdb.Breakpoint):
            def __init__(self, dumper, args):
                self.dumper = dumper
                self.args = args
                spec = 'qt_qmlDebugConnectorOpen'
                super(Resolver, self).\
                    __init__(spec, gdb.BP_BREAKPOINT, internal=True, temporary=False)

            def stop(self):
                self.dumper.resolvePendingInterpreterBreakpoint(args)
                self.enabled = False
                return False

        self.interpreterBreakpointResolvers.append(Resolver(self, args))

    def exitGdb(self, _):
        gdb.execute('quit')

    def reportResult(self, result, args={}):
        print('result={token="%s",%s}' % (args.get("token", 0), result))

    def profile1(self, args):
        '''Internal profiling'''
        import cProfile
        tempDir = tempfile.gettempdir() + '/bbprof'
        cProfile.run('theDumper.fetchVariables(%s)' % args, tempDir)
        import pstats
        pstats.Stats(tempDir).sort_stats('time').print_stats()

    def profile2(self, args):
        import timeit
        print(timeit.repeat('theDumper.fetchVariables(%s)' % args,
                            'from __main__ import theDumper', number=10))


class CliDumper(Dumper):
    def __init__(self):
        Dumper.__init__(self)
        self.childrenPrefix = '['
        self.chidrenSuffix = '] '
        self.indent = 0
        self.isCli = True
        self.setupDumpers({})

    def put(self, line):
        if self.output.endswith('\n'):
            self.output = self.output[0:-1]
        self.output += line

    def putNumChild(self, numchild):
        pass

    def putOriginalAddress(self, address):
        pass

    def fetchVariable(self, name):
        args = {}
        args['fancy'] = 1
        args['passexception'] = 1
        args['autoderef'] = 1
        args['qobjectnames'] = 1
        args['varlist'] = name
        self.prepare(args)
        self.output = name + ' = '
        value = self.parseAndEvaluate(name)
        with TopLevelItem(self, name):
            self.putItem(value)
        return self.output


# Global instances.
theDumper = Dumper()
theCliDumper = CliDumper()


######################################################################
#
# ThreadNames Command
#
#######################################################################

def threadnames(arg):
    return theDumper.threadnames(int(arg))


registerCommand('threadnames', threadnames)

#######################################################################
#
# Native Mixed
#
#######################################################################


class InterpreterMessageBreakpoint(gdb.Breakpoint):
    def __init__(self):
        spec = 'qt_qmlDebugMessageAvailable'
        super(InterpreterMessageBreakpoint, self).\
            __init__(spec, gdb.BP_BREAKPOINT, internal=True)

    def stop(self):
        print('Interpreter event received.')
        return theDumper.handleInterpreterMessage()


#######################################################################
#
# Shared objects
#
#######################################################################

def new_objfile_handler(event):
    return theDumper.handleNewObjectFile(event.new_objfile)


gdb.events.new_objfile.connect(new_objfile_handler)


#InterpreterMessageBreakpoint()