File: fpdmemorytools.pas

package info (click to toggle)
lazarus 2.2.6%2Bdfsg2-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 219,980 kB
  • sloc: pascal: 1,944,919; xml: 357,634; makefile: 270,608; cpp: 57,115; sh: 3,249; java: 609; perl: 297; sql: 222; ansic: 137
file content (1864 lines) | stat: -rw-r--r-- 69,959 bytes parent folder | download
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
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
unit FpdMemoryTools;

{$mode objfpc}{$H+}
{$HINT 5024 OFF}

(* Tools to read data from Target or Own memory.

   This is to deal in one place with all conversion of data from target format
   to debugger format.

   A typical read would involve the following steps:

   The code calls MemoryManager with an Address, a Size and a space for the data.

   If the data needs to be extended (SizeOf(data) > TargetSize), then
   MemConvertor is called to decide where in the provided space the read data
   should initially be stored.

   Then the data is read using MemReader.

   And finally MemConvertor is given a chance to extend or convert the data.

*)

interface

uses
  Classes, SysUtils, math, DbgIntfBaseTypes, FpErrorMessages, LazClasses,
  Laz_AVL_Tree, {$ifdef FORCE_LAZLOGGER_DUMMY} LazLoggerDummy {$else} LazLoggerBase {$endif};

const
  MINIMUM_MEMREAD_LIMIT = 1024;

type

  TBitAddr = 0..63; // 0-7 for mem read // 0-63 for register read
  TBitSize = -7..7;

  TFpDbgMemLocationType = (
    mlfUninitialized := 0,   // like invalid, but not known // This (0) is the initial value
    mlfInvalid,
    mlfTargetMem,            // an address in the target (debuggee) process
    mlfSelfMem,              // an address in this(the debuggers) process memory; the data is  in TARGET format (endian, ...)
    // the below will be mapped (and extended) according to endianess
    mlfTargetRegister,       // reads from the register
    mlfConstant,             // an (up to) SizeOf(TDbgPtr) (=8) Bytes Value (endian in format of debug process)
    mlfConstantDeref // A constant that can be used instead of an address (location parser),
                     // If a value (e.g. literal numeric constant 0x1234) has no address,
                     //   then this is treated as its virtual address.
                     // If (and only if) the value is attempted to be derefed, then
                     //   it will yield the constant as the result of the deref.
                     // It can also be tested for nil. The virtual address is never nil.
                     // Any other access must result in an error.
                     // Used for PFoo(1234)^ or TObject(1234).Foo
  );

  TFpDbgValueSize = packed record
    Size: Int64;        // Also used for stride => can be negative
    BitSize: TBitSize;  // Must have the same sign as Size
  end;
  PFpDbgValueSize = ^TFpDbgValueSize;

  TFpDbgMemLocation = packed record
    Address: TDbgPtr;
    MType: TFpDbgMemLocationType;
    BitOffset: TBitAddr;
  end;
  PFpDbgMemLocation = ^TFpDbgMemLocation;

  TFpDbgMemManager = class;
  TFpDbgMemManagerFlag = (mmfPartialRead);
  TFpDbgMemManagerFlags = set of TFpDbgMemManagerFlag;

  TByteDynArray = array of Byte;


  { TFpDbgLocationContext }

  TFpDbgLocationContext = class(TRefCountedObject)
  private
    function GetLastMemError: TFpError;
    function GetPartialReadResultLenght: QWord;
  protected
    function GetAddress: TDbgPtr; virtual; abstract;
    function GetStackFrame: Integer; virtual; abstract;
    function GetThreadId: Integer; virtual; abstract;
    function GetSizeOfAddress: Integer; virtual; abstract;
    function GetMemManager: TFpDbgMemManager; virtual; abstract;
  public
    property Address: TDbgPtr read GetAddress;
    property ThreadId: Integer read GetThreadId;
    property StackFrame: Integer read GetStackFrame;
    property SizeOfAddress: Integer read GetSizeOfAddress;
    property MemManager: TFpDbgMemManager read GetMemManager;
  public
    procedure ClearLastMemError;
    property LastMemError: TFpError read GetLastMemError;
    property PartialReadResultLenght: QWord read GetPartialReadResultLenght;
  public
    function ReadMemory(const ASourceLocation: TFpDbgMemLocation; const ASize: TFpDbgValueSize;
                        const ADest: Pointer; const AFlags: TFpDbgMemManagerFlags = []
                       ): Boolean; inline;
    function ReadMemoryEx(const ASourceLocation: TFpDbgMemLocation; AnAddressSpace: TDbgPtr; ASize: TFpDbgValueSize; ADest: Pointer): Boolean; inline;
    (* ReadRegister needs a Context, to get the thread/stackframe
    *)
    function ReadRegister(ARegNum: Cardinal; out AValue: TDbgPtr): Boolean; inline;

    function WriteMemory(const ADestLocation: TFpDbgMemLocation; const ASize: TFpDbgValueSize;
                         const ASource: Pointer; const AFlags: TFpDbgMemManagerFlags = []
                        ): Boolean; inline;

    // location will be invalid, if read failed
    function ReadAddress(const ALocation: TFpDbgMemLocation; ASize: TFpDbgValueSize): TFpDbgMemLocation; inline;
    function ReadAddressEx(const ALocation: TFpDbgMemLocation;  AnAddressSpace: TDbgPtr;
                           ASize: TFpDbgValueSize): TFpDbgMemLocation; inline;

    // ALocation and AnAddress MUST NOT be the same variable on the callers side
    function ReadAddress    (const ALocation: TFpDbgMemLocation; ASize: TFpDbgValueSize;
                             out AnAddress: TFpDbgMemLocation): Boolean; inline;
    //function ReadAddress    (const ALocation: TFpDbgMemLocation; ASize: TFpDbgValueSize;
    //                         out AnAddress: TFpDbgMemLocation;
    //                         AnOpts: TFpDbgMemReadOptionsl): Boolean; inline;
    function ReadUnsignedInt(const ALocation: TFpDbgMemLocation; ASize: TFpDbgValueSize;
                             out AValue: QWord): Boolean; inline;

    function WriteUnsignedInt(const ALocation: TFpDbgMemLocation; ASize: TFpDbgValueSize;
                             const AValue: QWord): Boolean; inline;

    //function ReadUnsignedInt(const ALocation: TFpDbgMemLocation; ASize: TFpDbgValueSize;
    //                         out AValue: QWord;
    //                         AnOpts: TFpDbgMemReadOptions): Boolean; inline;
    function ReadSignedInt  (const ALocation: TFpDbgMemLocation; ASize: TFpDbgValueSize;
                             out AValue: Int64): Boolean; inline;
    function WriteSignedInt(const ALocation: TFpDbgMemLocation; ASize: TFpDbgValueSize;
                             const AValue: Int64): Boolean; inline;
    //function ReadSignedInt  (const ALocation: TFpDbgMemLocation; ASize: TFpDbgValueSize;
    //                         out AValue: Int64;
    //                         AnOpts: TFpDbgMemReadOptions): Boolean; inline;
    // //enum/set: may need bitorder swapped
    function ReadEnum       (const ALocation: TFpDbgMemLocation; ASize: TFpDbgValueSize;
                             out AValue: QWord): Boolean; inline;
    function WriteEnum      (const ALocation: TFpDbgMemLocation; ASize: TFpDbgValueSize;
                             const AValue: QWord): Boolean; inline;
    //function ReadEnum       (const ALocation: TFpDbgMemLocation; ASize: TFpDbgValueSize;
    //                         out AValue: QWord;
    //                         AnOpts: TFpDbgMemReadOptions): Boolean; inline;
    function ReadSet        (const ALocation: TFpDbgMemLocation; ASize: TFpDbgValueSize;
                             out AValue: TBytes): Boolean; inline;
    function WriteSet        (const ALocation: TFpDbgMemLocation; ASize: TFpDbgValueSize;
                             const AValue: TBytes): Boolean; inline;
    //function ReadSet        (const ALocation: TFpDbgMemLocation; ASize: TFpDbgValueSize;
    //                         out AValue: TBytes;
    //                         AnOpts: TFpDbgMemReadOptions): Boolean; inline;
    function ReadFloat      (const ALocation: TFpDbgMemLocation; ASize: TFpDbgValueSize;
                             out AValue: Extended): Boolean; inline;
    //function ReadFloat      (const ALocation: TFpDbgMemLocation; ASize: TFpDbgValueSize;
    //                         out AValue: Extended;
    //                         AnOpts: TFpDbgMemReadOptions): Boolean; inline;
  end;


  { TFpDbgMemReaderBase }

  TFpDbgMemReaderBase = class
  protected
    // ReadMemoryPartial: workaround for subclasses that do not support partial mem read
    function ReadMemoryPartial(AnAddress: TDbgPtr; ASize: Cardinal; ADest: Pointer; out ABytesRead: Cardinal): Boolean;
  public
    function ReadMemory(AnAddress: TDbgPtr; ASize: Cardinal; ADest: Pointer): Boolean; virtual; abstract; overload;
    // inherited Memreaders should implement partial size ReadMemory, and forward it to the TDbgProcess class
    function ReadMemory(AnAddress: TDbgPtr; ASize: Cardinal; ADest: Pointer; out ABytesRead: Cardinal): Boolean; virtual; overload;
    function ReadMemoryEx(AnAddress, AnAddressSpace: TDbgPtr; ASize: Cardinal; ADest: Pointer): Boolean; virtual; abstract;
    function WriteMemory(AnAddress: TDbgPtr; ASize: Cardinal; ASource: Pointer): Boolean; virtual; abstract; overload;
    // ReadRegister may need TargetMemConvertor
    // Register with reduced size are treated as unsigned
    // TODO: ReadRegister should only take THREAD-ID, not context
    function ReadRegister(ARegNum: Cardinal; out AValue: TDbgPtr; AContext: TFpDbgLocationContext): Boolean; virtual; abstract;
    function WriteRegister(ARegNum: Cardinal; const AValue: TDbgPtr; AContext: TFpDbgLocationContext): Boolean; virtual; abstract;
    function RegisterSize(ARegNum: Cardinal): Integer; virtual; abstract;
    // Registernum from name
  end;

  (* Options for all read operation // TODO *)

  TFpDbgMemReadOptions = record
    (* potential flags
         target bit start/shift (method to map dwarf2/3 bit offse to dwarf 4
         target bit size
         target assume big/little endian
         float precisson
         AddressSpace

         ( rmBigEndian, rmLittleEndian, rmUseAddressSpace, UseBitSize)
         AddressSpace, BitOffset, precission
    *)
  end;


  TFpDbgMemReadDataType = (
    rdtRawRead, rdtAddress, rdtSignedInt, rdtUnsignedInt, rdtfloat,
    rdtEnum, rdtSet
  );

  TFpDbgMemConvData = record
    SourceLocation: TFpDbgMemLocation;
    SourceSize: TFpDbgValueSize;
    SourceFullSize: QWord;
    DestSize: QWord;
  end;

  // Todo, cpu/language specific operations, endianess, sign extend, float .... default int value for bool
  // convert from debugge format to debuger format and back
  // TODO: currently it assumes target and own mem are in the same format

  { TFpDbgMemConvertor }

  TFpDbgMemConvertor = class
  public
    (* PrepareTargetRead
       called before every Read operation.
       In case of reading from a bit-offset more memory may be needed, and must be allocated here
    *)
    function PrepareTargetRead(AReadDataType: TFpDbgMemReadDataType;
                               var AConvData: TFpDbgMemConvData;
                               const ADest: Pointer
                              ): boolean; virtual; abstract;
    {function PrepareTargetRead(AReadDataType: TFpDbgMemReadDataType;
                               ASourceMemPointer: TDbgPtr; ADestPointer: Pointer;
                               ASourceMemSize, ADestSize: Cardinal;
                               AnOpts: TFpDbgMemReadOptions;
                               out AConvertorData: TFpDbgMemConvData
                              ): boolean; virtual; abstract;}

    (* FinishTargetRead
       called after every Read operation.
    *)
    function FinishTargetRead(AReadDataType: TFpDbgMemReadDataType;
                               const AConvData: TFpDbgMemConvData;
                               const TmpData: Pointer; // can be equal to ADest
                               const ADest: Pointer
                             ): boolean; virtual; abstract;
    {function FinishTargetRead(AReadDataType: TFpDbgMemReadDataType;
                              ASourceMemPointer: TDbgPtr; ADestPointer: Pointer;
                              ASourceMemSize, ADestSize: Cardinal;
                              AnOpts: TFpDbgMemReadOptions;
                              AConvertorData: TFpDbgMemConvData
                             ): boolean; virtual; abstract;}

    // just to free any data
    procedure FailedTargetRead(AConvertorData: TFpDbgMemConvData); virtual; abstract;

    (* AdjustIntPointer:
       To copy a smaller int/cardinal (e.g. word) into a bigger (e.g. dword),
       adjust ADestPointer so it points to the low value part of the dest
       No conversion
    *)
    function AdjustIntPointer(var ADataPointer: Pointer; ADataSize, ANewSize: Cardinal): Boolean; virtual; abstract;
    //(* SignExtend:
    //   Expects a signed integer value of ASourceSize bytes in the low value end
    //   of the memory (total memory ADataPointer, ADestSize)
    //   Does zero fill the memory, if no sign extend is needed
    //*)
    //procedure SignExtend(ADataPointer: Pointer; ASourceSize, ADestSize: Cardinal); virtual; abstract;
    //(* Expects an unsigned integer value of ASourceSize bytes in the low value end
    //   of the memory (total memory ADataPointer, ADestSize)
    //   Basically zero fill the memory
    //*)
    //procedure UnsignedExtend(ADataPointer: Pointer; ASourceSize, ADestSize: Cardinal); virtual; abstract;
  end;

  { TFpDbgMemConvertorLittleEndian }

  TFpDbgMemConvertorLittleEndian = class(TFpDbgMemConvertor)
  public
    function PrepareTargetRead(AReadDataType: TFpDbgMemReadDataType;
                               var AConvData: TFpDbgMemConvData;
                               const ADest: Pointer
                              ): boolean; override;

    function FinishTargetRead(AReadDataType: TFpDbgMemReadDataType;
      const AConvData: TFpDbgMemConvData; const TmpData: Pointer;
  const ADest: Pointer): boolean; override;
    procedure FailedTargetRead({%H-}AConvertorData: TFpDbgMemConvData); override;

    function AdjustIntPointer(var ADataPointer: Pointer; ADataSize, ANewSize: Cardinal): Boolean; override;


    //procedure SignExtend(ADataPointer: Pointer; ASourceSize, ADestSize: Cardinal); override;
    //procedure UnsignedExtend(ADataPointer: Pointer; ASourceSize, ADestSize: Cardinal); override;
  end;

  { TFpDbgMemCacheBase }

  TFpDbgMemCacheBase = class
  private
    FMemReader: TFpDbgMemReaderBase;
  protected
    // Init:
    //   will be called by Manager.AddCache after the memreader is set.
    //   Earliest chance to pre-read the memory
    procedure Init; virtual;
    property MemReader: TFpDbgMemReaderBase read FMemReader;
  public
  end;

  { TFpDbgMemCacheManagerBase }

  TFpDbgMemCacheManagerBase = class
  private
    FMemReader: TFpDbgMemReaderBase;
  protected
    procedure InitalizeCache(ACache: TFpDbgMemCacheBase); // must be called by AddCache
  public
    function AddCache(AnAddress: TDbgPtr; ASize: Cardinal): TFpDbgMemCacheBase; virtual;
    function AddCacheEx(AnAddress, AnAddressSpace: TDbgPtr; ASize: Cardinal): TFpDbgMemCacheBase; virtual;
    procedure RemoveCache(ACache: TFpDbgMemCacheBase); virtual;

    function ReadMemory(AnAddress: TDbgPtr; ASize: Cardinal; ADest: Pointer): Boolean; virtual; overload;
    function ReadMemory(AnAddress: TDbgPtr; ASize: Cardinal; ADest: Pointer; ABytesRead: Cardinal): Boolean; virtual; overload;
    function ReadMemoryEx(AnAddress, AnAddressSpace: TDbgPtr; ASize: Cardinal; ADest: Pointer): Boolean; virtual;
  end;

  { TFpDbgMemCacheSimple
    MemCache for contineous mem / does not support AddressSpace
    TODO: Handle Overlaps
  }

  TFpDbgMemCacheSimple = class(TFpDbgMemCacheBase)
  private
    FCacheAddress: TDBGPtr;
    FCacheSize: Cardinal;
    FMem: Array of byte;
    FFailed: Boolean;
  public
    constructor Create(ACacheAddress: TDBGPtr; ACacheSize: Cardinal);
    function ContainsMemory(AnAddress: TDbgPtr; ASize: Cardinal): Boolean;
    function ReadMemory(AnAddress: TDbgPtr; ASize: Cardinal; ADest: Pointer): Boolean;
    property CacheAddress: TDBGPtr read FCacheAddress;
    property CacheSize: Cardinal read FCacheSize;
  end;

  { TFpDbgMemCacheManagerSimple }

  TFpDbgMemCacheManagerSimple = class(TFpDbgMemCacheManagerBase)
  private
    FCaches: TAVLTree;
  public
    constructor Create;
    destructor Destroy; override;

    function HasMemory(AnAddress: TDbgPtr; ASize: Cardinal): Boolean;
    function ReadMemory(AnAddress: TDbgPtr; ASize: Cardinal; ADest: Pointer): Boolean; override; overload;
    function ReadMemory(AnAddress: TDbgPtr; ASize: Cardinal; ADest: Pointer;
      ABytesRead: Cardinal): Boolean; override; overload;

    function AddCache(AnAddress: TDbgPtr; ASize: Cardinal): TFpDbgMemCacheBase;
      override;
    procedure RemoveCache(ACache: TFpDbgMemCacheBase); override;
  end;

  { TFpDbgMemLimits }

  TFpDbgMemLimits = class
  private
    FMaxArrayLen: QWord;
    FMaxMemReadSize: QWord;
    FMaxNullStringSearchLen: QWord;
    FMaxStringLen: QWord;
    procedure SetMaxMemReadSize(AValue: QWord);
  public
    constructor Create;
    property MaxMemReadSize: QWord read FMaxMemReadSize write SetMaxMemReadSize;
    property MaxStringLen: QWord read FMaxStringLen write FMaxStringLen;
    property MaxArrayLen: QWord read FMaxArrayLen write FMaxArrayLen;
    property MaxNullStringSearchLen: QWord read FMaxNullStringSearchLen write FMaxNullStringSearchLen;
  end;

  (* TFpDbgMemManager
   * allows to to pretend reading from the target, by using its own memory, or
       a constant.
     This is useful if an object expects to read data from the target, but the
       caller needs to "fake" another value.
     E.g. A TObject variable has the address of the (internal) pointer to the
       object data:
       SomeMethod expects "Address of variable". At that address in the target
       memory it expects another address, the pointer to the object data.
     But when doing "TObject(1234)" then 1234 is the pointer to the object data.
       1234 can not be read from the target memory. MemManager will pretend.
    * Provides access to TFpDbgMemConvertor
    * TODO: allow to pre-read and cache Target mem (e.g. before reading all fields of a record
  *)

  { TFpDbgMemManager }

  TFpDbgMemManager = class
  private const
    TMP_MEM_SIZE = 4096;
  private
    FCacheManager: TFpDbgMemCacheManagerBase;
    FLastError: TFpError;
    FMemLimits: TFpDbgMemLimits;
    FMemReader: TFpDbgMemReaderBase;
    FPartialReadResultLenght: QWord;
    FTmpMem: array[0..(TMP_MEM_SIZE div 8)+1] of qword; // MUST have at least ONE extra byte
    FTargetMemConvertor: TFpDbgMemConvertor;
    FSelfMemConvertor: TFpDbgMemConvertor; // used when resizing constants (or register values, which are already in self format)
    function GetCacheManager: TFpDbgMemCacheManagerBase;
    procedure BitShiftMem(ASrcMem, ADestMem: Pointer; ASrcSize, ADestSize: cardinal; ABitCnt: Integer);
  protected
    function ReadMemory(AReadDataType: TFpDbgMemReadDataType;
      const ASourceLocation: TFpDbgMemLocation; const ASourceSize: TFpDbgValueSize;
      const ADest: Pointer; const ADestSize: QWord; AContext: TFpDbgLocationContext;
      const AFlags: TFpDbgMemManagerFlags = []
    ): Boolean;
    function WriteMemory(AReadDataType: TFpDbgMemReadDataType;
      const ADestLocation: TFpDbgMemLocation; const ADestSize: TFpDbgValueSize;
      const ASource: Pointer; const ASourceSize: QWord; AContext: TFpDbgLocationContext;
      const AFlags: TFpDbgMemManagerFlags = []
    ): Boolean;
    function ReadMemoryEx(const ASourceLocation: TFpDbgMemLocation; AnAddressSpace: TDbgPtr; ASize: TFpDbgValueSize; ADest: Pointer; AContext: TFpDbgLocationContext = nil): Boolean;
    (* ReadRegister needs a Context, to get the thread/stackframe
    *)
    function ReadRegister(ARegNum: Cardinal; out AValue: TDbgPtr; AContext: TFpDbgLocationContext {= nil}): Boolean;
  public
    procedure SetCacheManager(ACacheMgr: TFpDbgMemCacheManagerBase);
    property CacheManager: TFpDbgMemCacheManagerBase read GetCacheManager;
  public
    constructor Create(AMemReader: TFpDbgMemReaderBase; AMemConvertor: TFpDbgMemConvertor);
    constructor Create(AMemReader: TFpDbgMemReaderBase; ATargenMemConvertor, ASelfMemConvertor: TFpDbgMemConvertor);
    destructor Destroy; override;
    procedure ClearLastError;

    function RegisterSize(ARegNum: Cardinal): Integer; // This is not context dependent

    function SetLength(var ADest: TByteDynArray; ALength: Int64): Boolean; overload;
    function SetLength(var ADest: RawByteString; ALength: Int64): Boolean; overload;
    function SetLength(var ADest: AnsiString; ALength: Int64): Boolean; overload;
    function SetLength(var ADest: WideString; ALength: Int64): Boolean; overload;
    function CheckDataSize(ASize: Int64): Boolean;

    property TargetMemConvertor: TFpDbgMemConvertor read FTargetMemConvertor;
    property SelfMemConvertor: TFpDbgMemConvertor read FSelfMemConvertor;
    property PartialReadResultLenght: QWord read FPartialReadResultLenght;
    property LastError: TFpError read FLastError;
    property MemLimits: TFpDbgMemLimits read FMemLimits;
  end;

function NilLoc: TFpDbgMemLocation; inline;
function InvalidLoc: TFpDbgMemLocation; inline;
function UnInitializedLoc: TFpDbgMemLocation; inline;
function TargetLoc(AnAddress: TDbgPtr): TFpDbgMemLocation; inline;
function RegisterLoc(ARegNum: Cardinal): TFpDbgMemLocation; inline;
function SelfLoc(AnAddress: TDbgPtr): TFpDbgMemLocation; inline;
function SelfLoc(AnAddress: Pointer): TFpDbgMemLocation; inline;
function ConstLoc(AValue: QWord): TFpDbgMemLocation; inline;

function AddBitOffset(const AnAddr: TFpDbgMemLocation; ABitOffset: Int64): TFpDbgMemLocation; inline;

function IsTargetAddr(const ALocation: TFpDbgMemLocation): Boolean; inline;
function IsConstData(const ALocation: TFpDbgMemLocation): Boolean; inline;
function IsInitializedLoc(const ALocation: TFpDbgMemLocation): Boolean; inline;
function IsValidLoc(const ALocation: TFpDbgMemLocation): Boolean; inline;     // Valid, Nil allowed
function IsReadableLoc(const ALocation: TFpDbgMemLocation): Boolean; inline;  // Valid and not Nil // can be const or reg
function IsReadableMem(const ALocation: TFpDbgMemLocation): Boolean; inline;  // Valid and target or sel <> nil
function IsNilLoc(const ALocation: TFpDbgMemLocation): Boolean; inline;    // Valid AND NIL // Does not check mlfTargetRegister
// TODO: registers should be targed.... // May have to rename some of those
function IsTargetNil(const ALocation: TFpDbgMemLocation): Boolean; inline;    // valid targed = nil
function IsTargetNotNil(const ALocation: TFpDbgMemLocation): Boolean; inline; // valid targed <> nil
function IsTargetOrRegNotNil(const ALocation: TFpDbgMemLocation): Boolean; inline; // valid targed <> nil

function ZeroSize: TFpDbgValueSize; inline;
function SizeVal(const ASize: Int64): TFpDbgValueSize; inline;
function SizeFromBits(const ABits: Int64): TFpDbgValueSize; inline;

function IsZeroSize(const ASize: TFpDbgValueSize): Boolean; inline;
function IsByteSize(const ASize: TFpDbgValueSize): Boolean; inline;
function SizeToFullBytes(const ASize: TFpDbgValueSize): Int64; inline;  // Bytes needed to contain this size
function SizeToBits(const ASize: TFpDbgValueSize): Int64; inline;  // Bytes needed to contain this size

operator =  (const a,b: TFpDbgMemLocation): Boolean; inline;

operator =  (const a,b: TFpDbgValueSize): Boolean; inline;
operator =  (const a: TFpDbgValueSize; b: Int64): Boolean; inline;
operator >  (const a: TFpDbgValueSize; b: Int64): Boolean; inline;
operator >= (const a: TFpDbgValueSize; b: Int64): Boolean; inline;
operator <  (const a: TFpDbgValueSize; b: Int64): Boolean; inline;
operator <= (const a: TFpDbgValueSize; b: Int64): Boolean; inline;

operator +  (const a,b: TFpDbgValueSize): TFpDbgValueSize; inline;
operator -  (const a,b: TFpDbgValueSize): TFpDbgValueSize; inline;
operator *  (const a: TFpDbgValueSize; b: Int64): TFpDbgValueSize; inline;

operator +  (const AnAddr: TFpDbgMemLocation; ASize: TFpDbgValueSize): TFpDbgMemLocation; inline;

function LocToAddr(const ALocation: TFpDbgMemLocation): TDbgPtr; inline;      // does not check valid
function LocToAddrOrNil(const ALocation: TFpDbgMemLocation): TDbgPtr; inline; // save version

//function EmptyMemReadOpts:TFpDbgMemReadOptions;

function dbgs(const ALocation: TFpDbgMemLocation): String; overload;
function dbgs(const ASize: TFpDbgValueSize): String; overload;
function dbgs(const AReadDataType: TFpDbgMemReadDataType): String; overload;

implementation
var
  FPDBG_VERBOSE_MEM: PLazLoggerLogGroup;

function NilLoc: TFpDbgMemLocation;
begin
  Result := Default(TFpDbgMemLocation);
  Result.Address := 0;
  Result.MType := mlfTargetMem;
end;

function InvalidLoc: TFpDbgMemLocation;
begin
  Result := Default(TFpDbgMemLocation);
  Result.Address := 0;
  Result.MType := mlfInvalid;
end;

function UnInitializedLoc: TFpDbgMemLocation;
begin
  Result := Default(TFpDbgMemLocation);
  Result.Address := 0;
  Result.MType := mlfUninitialized;
end;

function TargetLoc(AnAddress: TDbgPtr): TFpDbgMemLocation;
begin
  Result := Default(TFpDbgMemLocation);
  Result.Address := AnAddress;
  Result.MType := mlfTargetMem;
end;

function RegisterLoc(ARegNum: Cardinal): TFpDbgMemLocation;
begin
  Result := Default(TFpDbgMemLocation);
  Result.Address := ARegNum;
  Result.MType := mlfTargetRegister;
end;

function SelfLoc(AnAddress: TDbgPtr): TFpDbgMemLocation;
begin
  Result := Default(TFpDbgMemLocation);
  Result.Address := AnAddress;
  Result.MType := mlfSelfMem;
end;

function SelfLoc(AnAddress: Pointer): TFpDbgMemLocation;
begin
  Result := Default(TFpDbgMemLocation);
  Result.Address := TDbgPtr(AnAddress);
  Result.MType := mlfSelfMem;
end;

function ConstLoc(AValue: QWord): TFpDbgMemLocation;
begin
  Result := Default(TFpDbgMemLocation);
  Result.Address := AValue;
  Result.MType := mlfConstant;
end;

function AddBitOffset(const AnAddr: TFpDbgMemLocation; ABitOffset: Int64
  ): TFpDbgMemLocation;
begin
  {$PUSH}{$R-}{$Q-}
  Result := AnAddr;
  Result.Address := AnAddr.Address + ABitOffset div 8;
  if (ABitOffset < 0) and ((ABitOffset and 7) <> 0) then
    Result.Address := Result.Address - 1; // Going to ADD some bits back
                                          // E.g. b=-1 means (b and 7) = 7 and that means adding 7 bits, instead of substracting 1
  Result.BitOffset := ABitOffset and 7;
  {$POP}
end;

function IsTargetAddr(const ALocation: TFpDbgMemLocation): Boolean;
begin
  Result := ALocation.MType = mlfTargetMem;
end;

function IsConstData(const ALocation: TFpDbgMemLocation): Boolean;
begin
  Result := not(ALocation.MType in [mlfConstant, mlfConstantDeref]);
end;

function IsInitializedLoc(const ALocation: TFpDbgMemLocation): Boolean;
begin
  Result := ALocation.MType <> mlfUninitialized;
end;

function IsValidLoc(const ALocation: TFpDbgMemLocation): Boolean;
begin
  Result := not(ALocation.MType in [mlfInvalid, mlfUninitialized]);
end;

function IsReadableLoc(const ALocation: TFpDbgMemLocation): Boolean;
begin
  Result := (not(ALocation.MType in [mlfInvalid, mlfUninitialized])) and
            ( (not(ALocation.MType in [mlfTargetMem, mlfSelfMem])) or
              (ALocation.Address <> 0)
            );
end;

function IsReadableMem(const ALocation: TFpDbgMemLocation): Boolean;
begin
  Result := (ALocation.MType in [mlfTargetMem, mlfSelfMem]) and
            (ALocation.Address <> 0);
end;

function IsNilLoc(const ALocation: TFpDbgMemLocation): Boolean;
begin
  Result := (ALocation.MType in [mlfTargetMem, mlfSelfMem, mlfConstant]) and
            (ALocation.Address = 0);
end;

function IsTargetNil(const ALocation: TFpDbgMemLocation): Boolean;
begin
  Result := (ALocation.MType = mlfTargetMem) and (ALocation.Address = 0);
end;

function IsTargetNotNil(const ALocation: TFpDbgMemLocation): Boolean;
begin
  Result := (ALocation.MType = mlfTargetMem) and (ALocation.Address <> 0);
end;

function IsTargetOrRegNotNil(const ALocation: TFpDbgMemLocation): Boolean;
begin
  Result := ((ALocation.MType = mlfTargetMem) and (ALocation.Address <> 0)) or
            (ALocation.MType = mlfTargetRegister);
end;

function ZeroSize: TFpDbgValueSize;
begin
  Result.Size := 0;
  Result.BitSize := 0;
end;

function SizeVal(const ASize: Int64): TFpDbgValueSize;
begin
  Result.Size := ASize;
  Result.BitSize := 0;
end;

function SizeFromBits(const ABits: Int64): TFpDbgValueSize;
begin
  Result.Size := ABits div 8;
  if ABits < 0 then
    Result.BitSize := -((-ABits) and 7)
  else
    Result.BitSize := ABits and 7;
end;

function IsZeroSize(const ASize: TFpDbgValueSize): Boolean;
begin
  Result := (ASize.Size = 0) and (ASize.BitSize = 0);
end;

function IsByteSize(const ASize: TFpDbgValueSize): Boolean;
begin
  Result := (ASize.BitSize = 0);
end;

function SizeToFullBytes(const ASize: TFpDbgValueSize): Int64;
begin
  assert((ASize.Size=0) or (ASize.BitSize=0) or ( (ASize.Size<0) = (ASize.BitSize<0) ), '(ASize.Size=0) or (ASize.BitSize=0) or ( (ASize.Size<0) = (ASize.BitSize<0) )');
  if ASize < 0 then
    Result := ASize.Size + (ASize.BitSize - 7) div 8
  else
    Result := ASize.Size + (ASize.BitSize + 7) div 8;
end;

function SizeToBits(const ASize: TFpDbgValueSize): Int64;
begin
  assert((ASize.Size=0) or (ASize.BitSize=0) or ( (ASize.Size<0) = (ASize.BitSize<0) ), '(ASize.Size=0) or (ASize.BitSize=0) or ( (ASize.Size<0) = (ASize.BitSize<0) )');
  Result := ASize.Size * 8 + ASize.BitSize;
end;

operator = (const a, b: TFpDbgMemLocation): Boolean;
begin
  Result := (a.Address = b.Address) and (a.MType = b.MType) and (a.BitOffset = b.BitOffset);
end;

operator = (const a, b: TFpDbgValueSize): Boolean;
begin
  assert((a.Size=0) or (a.BitSize=0) or ( (a.Size<0) = (a.BitSize<0) ), '(a.Size=0) or (a.BitSize=0) or ( (a.Size<0) = (a.BitSize<0) )');
  assert((b.Size=0) or (b.BitSize=0) or ( (b.Size<0) = (b.BitSize<0) ), '(b.Size=0) or (b.BitSize=0) or ( (b.Size<0) = (b.BitSize<0) )');
  Result := (a.Size = b.Size) and (a.BitSize = b.BitSize);
end;

operator = (const a: TFpDbgValueSize; b: Int64): Boolean;
begin
  assert((a.Size=0) or (a.BitSize=0) or ( (a.Size<0) = (a.BitSize<0) ), '(a.Size=0) or (a.BitSize=0) or ( (a.Size<0) = (a.BitSize<0) )');
  Result := (a.Size = b) and (a.BitSize = 0);
end;

operator>(const a: TFpDbgValueSize; b: Int64): Boolean;
begin
  assert((a.Size=0) or (a.BitSize=0) or ( (a.Size<0) = (a.BitSize<0) ), '(a.Size=0) or (a.BitSize=0) or ( (a.Size<0) = (a.BitSize<0) )');
  Result := (a.Size > b) or
            (a.Size = b) and (a.BitSize > 0);
end;

operator>=(const a: TFpDbgValueSize; b: Int64): Boolean;
begin
  assert((a.Size=0) or (a.BitSize=0) or ( (a.Size<0) = (a.BitSize<0) ), '(a.Size=0) or (a.BitSize=0) or ( (a.Size<0) = (a.BitSize<0) )');
  Result := (a.Size > b) or
            (a.Size = b) and (a.BitSize >= 0);
end;

operator<(const a: TFpDbgValueSize; b: Int64): Boolean;
begin
  assert((a.Size=0) or (a.BitSize=0) or ( (a.Size<0) = (a.BitSize<0) ), '(a.Size=0) or (a.BitSize=0) or ( (a.Size<0) = (a.BitSize<0) )');
  Result := (a.Size < b) or
            (a.Size = b) and (a.BitSize < 0);
end;

operator<=(const a: TFpDbgValueSize; b: Int64): Boolean;
begin
  assert((a.Size=0) or (a.BitSize=0) or ( (a.Size<0) = (a.BitSize<0) ), '(a.Size=0) or (a.BitSize=0) or ( (a.Size<0) = (a.BitSize<0) )');
  Result := (a.Size < b) or
            (a.Size = b) and (a.BitSize <= 0);
end;

operator + (const a, b: TFpDbgValueSize): TFpDbgValueSize;
var
  bits, low3bits: Int64;
begin
  assert((a.Size=0) or (a.BitSize=0) or ( (a.Size<0) = (a.BitSize<0) ), '(a.Size=0) or (a.BitSize=0) or ( (a.Size<0) = (a.BitSize<0) )');
  assert((b.Size=0) or (b.BitSize=0) or ( (b.Size<0) = (b.BitSize<0) ), '(b.Size=0) or (b.BitSize=0) or ( (b.Size<0) = (b.BitSize<0) )');
  {$PUSH}{$R-}{$Q-}
  bits := a.BitSize + b.BitSize;

  Result.Size := a.Size + b.Size + bits div 8;
  low3bits := bits and 7;
  if low3bits = 0 then
    Result.BitSize := 0
  else
  if (Result.Size < 0) or ( (Result.Size=0) and (bits<0) ) then begin
    if (bits > 0) then // bits have wrong sign
      Result.Size := Result.Size + 1;
    Result.BitSize := low3bits - 8;
  end
  else begin
    if (bits < 0) then // bits have wrong sign
      Result.Size := Result.Size - 1;
    Result.BitSize := low3bits;
  end;
  {$POP}
end;

operator - (const a, b: TFpDbgValueSize): TFpDbgValueSize;
var
  bits, low3bits: Int64;
begin
  assert((a.Size=0) or (a.BitSize=0) or ( (a.Size<0) = (a.BitSize<0) ), '(a.Size=0) or (a.BitSize=0) or ( (a.Size<0) = (a.BitSize<0) )');
  assert((b.Size=0) or (b.BitSize=0) or ( (b.Size<0) = (b.BitSize<0) ), '(b.Size=0) or (b.BitSize=0) or ( (b.Size<0) = (b.BitSize<0) )');
  {$PUSH}{$R-}{$Q-}
  bits := a.BitSize - b.BitSize;

  Result.Size := a.Size - b.Size + bits div 8;
  low3bits := bits and 7;
  if low3bits = 0 then
    Result.BitSize := 0
  else
  if (Result.Size < 0) or ( (Result.Size=0) and (bits<0) ) then begin
    if (bits > 0) then // bits have wrong sign
      Result.Size := Result.Size + 1;
    Result.BitSize := low3bits - 8;
  end
  else begin
    if (bits < 0) then // bits have wrong sign
      Result.Size := Result.Size - 1;
    Result.BitSize := low3bits;
  end;
  {$POP}
end;

operator * (const a: TFpDbgValueSize; b: Int64): TFpDbgValueSize;
var
  bits, low3bits: Int64;
begin
  assert((a.Size=0) or (a.BitSize=0) or ( (a.Size<0) = (a.BitSize<0) ), '(a.Size=0) or (a.BitSize=0) or ( (a.Size<0) = (a.BitSize<0) )');
  {$PUSH}{$R-}{$Q-}
  bits := a.BitSize * b;

  Result.Size := a.Size * b + bits div 8;
  low3bits := bits and 7;
  if low3bits = 0 then
    Result.BitSize := 0
  else
  if (Result.Size < 0) or ( (Result.Size=0) and (bits<0) ) then begin
    if (bits > 0) then // bits have wrong sign
      Result.Size := Result.Size + 1;
    Result.BitSize := low3bits - 8;
  end
  else begin
    if (bits < 0) then // bits have wrong sign
      Result.Size := Result.Size - 1;
    Result.BitSize := low3bits;
  end;
  {$POP}
end;

operator + (const AnAddr: TFpDbgMemLocation; ASize: TFpDbgValueSize
  ): TFpDbgMemLocation;
var
  bits: Int64;
begin
  assert((ASize.Size=0) or (ASize.BitSize=0) or ( (ASize.Size<0) = (ASize.BitSize<0) ), '(ASize.Size=0) or (ASize.BitSize=0) or ( (ASize.Size<0) = (ASize.BitSize<0) )');
  assert(AnAddr.MType in [mlfSelfMem, mlfTargetMem], '+: AnAddr.MType in [mlfSelfMem, mlfTargetMem]');
  Result := AnAddr;
  {$PUSH}{$R-}{$Q-}
  bits := AnAddr.BitOffset + ASize.BitSize;

  Result.Address := AnAddr.Address + ASize.Size + bits div 8;
  if (bits < 0) and ((bits and 7) <> 0) then
    Result.Address := Result.Address - 1; // Going to ADD some bits back
                                          // E.g. bits=-1 means (bits and 7) = 7 and that means adding 7 bits, instead of substracting 1
  Result.BitOffset := bits and 7;
  {$POP}
end;

function LocToAddr(const ALocation: TFpDbgMemLocation): TDbgPtr;
begin
  assert(ALocation.MType = mlfTargetMem, 'LocToAddr for other than mlfTargetMem');
  Result := ALocation.Address;
end;

function LocToAddrOrNil(const ALocation: TFpDbgMemLocation): TDbgPtr;
begin
  if (ALocation.MType = mlfTargetMem) then
    Result := ALocation.Address
  else
    Result := 0;
end;

//function {%H-}EmptyMemReadOpts: TFpDbgMemReadOptions;
//begin
//  //
//end;

function dbgs(const ALocation: TFpDbgMemLocation): String;
begin
  Result := '';
  if not (ALocation.MType in [low(TFpDbgMemLocationType)..high(TFpDbgMemLocationType)]) then
    Result := 'Location=out-of-range'
  else
    WriteStr(Result, 'Location=', ALocation.Address, ':', ALocation.BitOffset, ', ', ALocation.MType);
end;

function dbgs(const ASize: TFpDbgValueSize): String;
begin
  WriteStr(Result, 'Size=', ASize.Size, ':', ASize.BitSize);
end;

function dbgs(const AReadDataType: TFpDbgMemReadDataType): String;
begin
  WriteStr(Result, AReadDataType);
end;

{ TFpDbgLocationContext }

function TFpDbgLocationContext.GetLastMemError: TFpError;
begin
  Result := MemManager.LastError;
end;

function TFpDbgLocationContext.GetPartialReadResultLenght: QWord;
begin
  Result := MemManager.PartialReadResultLenght;
end;

procedure TFpDbgLocationContext.ClearLastMemError;
begin
  MemManager.ClearLastError;
end;

function TFpDbgLocationContext.ReadMemory(
  const ASourceLocation: TFpDbgMemLocation; const ASize: TFpDbgValueSize;
  const ADest: Pointer; const AFlags: TFpDbgMemManagerFlags): Boolean;
begin
  Result := MemManager.ReadMemory(rdtRawRead, ASourceLocation, ASize, ADest, ASize.Size, Self, AFlags);
end;

function TFpDbgLocationContext.ReadMemoryEx(
  const ASourceLocation: TFpDbgMemLocation; AnAddressSpace: TDbgPtr;
  ASize: TFpDbgValueSize; ADest: Pointer): Boolean;
begin
  Result := MemManager.ReadMemoryEx(ASourceLocation, AnAddressSpace, ASize, ADest, Self);
end;

function TFpDbgLocationContext.ReadRegister(ARegNum: Cardinal; out
  AValue: TDbgPtr): Boolean;
begin
  Result := MemManager.ReadRegister(ARegNum, AValue, Self);
end;

function TFpDbgLocationContext.WriteMemory(
  const ADestLocation: TFpDbgMemLocation; const ASize: TFpDbgValueSize;
  const ASource: Pointer; const AFlags: TFpDbgMemManagerFlags): Boolean;
begin
  Result := MemManager.WriteMemory(rdtRawRead, ADestLocation, ASize, ASource, ASize.Size, Self, AFlags);
end;

function TFpDbgLocationContext.ReadAddress(const ALocation: TFpDbgMemLocation;
  ASize: TFpDbgValueSize): TFpDbgMemLocation;
begin
  Result := Default(TFpDbgMemLocation);
  Result.MType := mlfTargetMem;
  if not MemManager.ReadMemory(rdtAddress, ALocation, ASize, @Result.Address, SizeOf(Result.Address), Self) then
    Result := InvalidLoc;
end;

function TFpDbgLocationContext.ReadAddressEx(
  const ALocation: TFpDbgMemLocation; AnAddressSpace: TDbgPtr;
  ASize: TFpDbgValueSize): TFpDbgMemLocation;
begin
  Result := InvalidLoc;
end;

function TFpDbgLocationContext.ReadAddress(const ALocation: TFpDbgMemLocation;
  ASize: TFpDbgValueSize; out AnAddress: TFpDbgMemLocation): Boolean;
begin
  AnAddress := Default(TFpDbgMemLocation);
  Result := MemManager.ReadMemory(rdtAddress, ALocation, ASize, @AnAddress.Address, (SizeOf(AnAddress.Address)), Self);
  if Result
  then AnAddress.MType := mlfTargetMem
  else AnAddress := InvalidLoc;
end;

function TFpDbgLocationContext.ReadUnsignedInt(
  const ALocation: TFpDbgMemLocation; ASize: TFpDbgValueSize; out AValue: QWord
  ): Boolean;
begin
  Result := MemManager.ReadMemory(rdtUnsignedInt, ALocation, ASize, @AValue, (SizeOf(AValue)), Self);
end;

function TFpDbgLocationContext.WriteUnsignedInt(
  const ALocation: TFpDbgMemLocation; ASize: TFpDbgValueSize;
  const AValue: QWord): Boolean;
begin
  Result := MemManager.WriteMemory(rdtUnsignedInt, ALocation, ASize, @AValue, (SizeOf(AValue)), Self);
end;

function TFpDbgLocationContext.ReadSignedInt(
  const ALocation: TFpDbgMemLocation; ASize: TFpDbgValueSize; out AValue: Int64
  ): Boolean;
begin
  Result := MemManager.ReadMemory(rdtSignedInt, ALocation, ASize, @AValue, (SizeOf(AValue)), Self);
end;

function TFpDbgLocationContext.WriteSignedInt(
  const ALocation: TFpDbgMemLocation; ASize: TFpDbgValueSize;
  const AValue: Int64): Boolean;
begin
  Result := MemManager.WriteMemory(rdtSignedInt, ALocation, ASize, @AValue, (SizeOf(AValue)), Self);
end;

function TFpDbgLocationContext.ReadEnum(const ALocation: TFpDbgMemLocation;
  ASize: TFpDbgValueSize; out AValue: QWord): Boolean;
begin
  Result := MemManager.ReadMemory(rdtEnum, ALocation, ASize, @AValue, (SizeOf(AValue)), Self);
end;

function TFpDbgLocationContext.WriteEnum(const ALocation: TFpDbgMemLocation;
  ASize: TFpDbgValueSize; const AValue: QWord): Boolean;
begin
  Result := MemManager.WriteMemory(rdtEnum, ALocation, ASize, @AValue, (SizeOf(AValue)), Self);
end;

function TFpDbgLocationContext.ReadSet(const ALocation: TFpDbgMemLocation;
  ASize: TFpDbgValueSize; out AValue: TBytes): Boolean;
begin
  System.SetLength(AValue, SizeToFullBytes(ASize));
  Result := ASize > 0;
  if Result then
    Result := MemManager.ReadMemory(rdtSet, ALocation, ASize, @AValue[0], Length(AValue), Self);
end;

function TFpDbgLocationContext.WriteSet(const ALocation: TFpDbgMemLocation;
  ASize: TFpDbgValueSize; const AValue: TBytes): Boolean;
begin
  Result := MemManager.WriteMemory(rdtSet, ALocation, ASize, @AValue[0], Length(AValue), Self);
end;

function TFpDbgLocationContext.ReadFloat(const ALocation: TFpDbgMemLocation;
  ASize: TFpDbgValueSize; out AValue: Extended): Boolean;
begin
  Result := MemManager.ReadMemory(rdtfloat, ALocation, ASize, @AValue, (SizeOf(AValue)), Self);
end;

{ TFpDbgMemLimits }

procedure TFpDbgMemLimits.SetMaxMemReadSize(AValue: QWord);
begin
  if (AValue <> 0) and (AValue < MINIMUM_MEMREAD_LIMIT) then
    AValue := MINIMUM_MEMREAD_LIMIT;
  if FMaxMemReadSize = AValue then Exit;
  FMaxMemReadSize := AValue;
end;

constructor TFpDbgMemLimits.Create;
begin
  FMaxMemReadSize := 512 * 1024 * 1024; // Do not try allocating more than 0.5 GB by default
  FMaxArrayLen    := 10000;
  FMaxStringLen   := 100 * 1024;
  FMaxNullStringSearchLen := 20 * 1024;
end;

{ TFpDbgMemReaderBase }

function TFpDbgMemReaderBase.ReadMemory(AnAddress: TDbgPtr; ASize: Cardinal;
  ADest: Pointer; out ABytesRead: Cardinal): Boolean;
begin
  Result := ReadMemoryPartial(AnAddress, ASize, ADest, ABytesRead);
end;

function TFpDbgMemReaderBase.ReadMemoryPartial(AnAddress: TDbgPtr;
  ASize: Cardinal; ADest: Pointer; out ABytesRead: Cardinal): Boolean;
var
  SizeRemaining, sz: Cardinal;
  Offs: Integer;
begin
  ABytesRead := ASize;
  Result := ReadMemory(AnAddress, ASize, ADest);
  if Result then
    exit;

  SizeRemaining := ASize;
  Offs := 0;
  ABytesRead := 0;

  while SizeRemaining > 0 do begin
    Result := False;
    sz := SizeRemaining;
    while (not Result) and (sz > 1) do begin
      sz := sz div 2;
      Result := ReadMemory(AnAddress, sz, Pointer(PByte(ADest) + Offs));
    end;
    if not Result then
      break;

    ABytesRead := ABytesRead + sz;
    Offs := Offs + sz;
    AnAddress := AnAddress + sz;
    SizeRemaining := SizeRemaining - sz;
  end;

  Result := ABytesRead > 0;
end;

{ TFpDbgMemConvertorLittleEndian }

function TFpDbgMemConvertorLittleEndian.PrepareTargetRead(
  AReadDataType: TFpDbgMemReadDataType; var AConvData: TFpDbgMemConvData;
  const ADest: Pointer): boolean;
begin
  Result := AConvData.SourceFullSize <= AConvData.DestSize;
  if not Result then
    exit;
  case AReadDataType of
    rdtAddress, rdtSignedInt, rdtUnsignedInt,
    rdtEnum, rdtSet: ;
    rdtfloat:
      // TODO: reading float from register / or mlfConstant...;
      Result := IsByteSize(AConvData.SourceSize) and // only support exact size for FLOAT
                (AConvData.DestSize = SizeOf(Extended)) and // only can read to extended... TODO (if need more)
                ( (AConvData.SourceSize.Size = SizeOf(Extended)) or
                  (AConvData.SourceSize.Size = SizeOf(Double)) or
                  (AConvData.SourceSize.Size = SizeOf(Single)) or
                  (AConvData.SourceSize.Size = SizeOf(real48))
                );
    rdtRawRead: ;
    else begin
      Assert(False, 'TFpDbgMemConvertorLittleEndian.PrepareTargetRead');
      Result := False;
    end;
  end;
end;

function TFpDbgMemConvertorLittleEndian.FinishTargetRead(
  AReadDataType: TFpDbgMemReadDataType;
  const AConvData: TFpDbgMemConvData; const TmpData: Pointer;
  const ADest: Pointer): boolean;
type
  Preal48 = ^real48;
var
  s: Boolean;
  b: TBitAddr;
begin
  Result := TmpData = ADest;
  if not Result then
    exit;
  case AReadDataType of
    rdtAddress, rdtUnsignedInt, rdtEnum, rdtSet: begin
        if AConvData.SourceFullSize < AConvData.DestSize then
          FillByte((ADest + AConvData.SourceFullSize)^, AConvData.DestSize-AConvData.SourceFullSize, $00);
        if AConvData.SourceSize.BitSize <> 0 then begin
          assert(AConvData.SourceFullSize > 0, 'TFpDbgMemConvertorLittleEndian.FinishTargetRead: AConvData.SourceFullSize > 0');
          PByte(ADest + AConvData.SourceFullSize - 1)^ := Byte(PByte(ADest + AConvData.SourceFullSize - 1)^ and
            (Byte($FF) shr (8 - AConvData.SourceSize.BitSize)));
        end;
      end;
    rdtSignedInt: begin
        if AConvData.SourceFullSize < AConvData.DestSize then begin
          b := AConvData.SourceSize.BitSize;
          s := False;
          if (AConvData.SourceFullSize > 0) then begin
            if b = 0 then
              s := ((PByte(ADest + AConvData.SourceFullSize - 1)^ and $80) <> 0)
            else
              s := ((PByte(ADest + AConvData.SourceFullSize - 1)^ and (1 shl (b-1)) ) <> 0);
          end;

          if s then
            FillByte((ADest + AConvData.SourceFullSize)^, AConvData.DestSize-AConvData.SourceFullSize, $FF)
          else
            FillByte((ADest + AConvData.SourceFullSize)^, AConvData.DestSize-AConvData.SourceFullSize, $00);
          if b <> 0 then begin
            assert(AConvData.SourceFullSize > 0, 'TFpDbgMemConvertorLittleEndian.FinishTargetRead: AConvData.SourceFullSize > 0');
            if s then
              PByte(ADest + AConvData.SourceFullSize - 1)^ := Byte(PByte(ADest + AConvData.SourceFullSize - 1)^ or
                (Byte($FF) shl b))
            else
              PByte(ADest + AConvData.SourceFullSize - 1)^ := Byte(PByte(ADest + AConvData.SourceFullSize - 1)^ and
                (Byte($FF) shr (8 - b)));
          end;
        end;
      end;
    rdtfloat: begin
      assert((AConvData.DestSize = SizeOf(Extended)));
      if (AConvData.SourceFullSize = SizeOf(Extended)) then
        //
      else
      if (AConvData.SourceFullSize = SizeOf(Double)) then
        PExtended(ADest)^ := PDouble(ADest)^
      else
      if (AConvData.SourceFullSize = SizeOf(real48)) then
        PExtended(ADest)^ := Preal48(ADest)^
      else
      if (AConvData.SourceFullSize = SizeOf(Single)) then
        PExtended(ADest)^ := PSingle(ADest)^
      else
        Result := False;
    end;
    rdtRawRead: ; // TODO: cut bits?
    else begin
      Assert(False, 'TFpDbgMemConvertorLittleEndian.FailedTargetRead');
      Result := False;
    end;
  end;
end;

procedure TFpDbgMemConvertorLittleEndian.FailedTargetRead(AConvertorData: TFpDbgMemConvData);
begin
  //
end;

function TFpDbgMemConvertorLittleEndian.AdjustIntPointer(
  var ADataPointer: Pointer; ADataSize, ANewSize: Cardinal): Boolean;
begin
  Result := ANewSize <= ADataSize;
  // no adjustment needed
end;

//procedure TFpDbgMemConvertorLittleEndian.SignExtend(ADataPointer: Pointer; ASourceSize,
//  ADestSize: Cardinal);
//begin
//  Assert(ASourceSize > 0, 'TFpDbgMemConvertorLittleEndian.SignExtend');
//  if ASourceSize >= ADestSize then
//    exit;
//
//  if (PByte(ADataPointer + ASourceSize - 1)^ and $80) <> 0 then
//    FillByte((ADataPointer + ASourceSize)^, ADestSize-ASourceSize, $ff)
//  else
//    FillByte((ADataPointer + ASourceSize)^, ADestSize-ASourceSize, $00)
//end;
//
//procedure TFpDbgMemConvertorLittleEndian.UnsignedExtend(ADataPointer: Pointer;
//  ASourceSize, ADestSize: Cardinal);
//begin
//  Assert(ASourceSize > 0, 'TFpDbgMemConvertorLittleEndian.SignExtend');
//  if ASourceSize >= ADestSize then
//    exit;
//
//  FillByte((ADataPointer + ASourceSize)^, ADestSize-ASourceSize, $00)
//end;

{ TFpDbgMemCacheBase }

procedure TFpDbgMemCacheBase.Init;
begin
  //
end;

{ TFpDbgMemCacheManagerBase }

procedure TFpDbgMemCacheManagerBase.InitalizeCache(ACache: TFpDbgMemCacheBase);
begin
  ACache.FMemReader := FMemReader;
  ACache.Init;
end;

function TFpDbgMemCacheManagerBase.AddCache(AnAddress: TDbgPtr; ASize: Cardinal
  ): TFpDbgMemCacheBase;
begin
  Result := nil;
end;

function TFpDbgMemCacheManagerBase.AddCacheEx(AnAddress,
  AnAddressSpace: TDbgPtr; ASize: Cardinal): TFpDbgMemCacheBase;
begin
  Result := nil;
end;

procedure TFpDbgMemCacheManagerBase.RemoveCache(ACache: TFpDbgMemCacheBase);
begin
  //
end;

function TFpDbgMemCacheManagerBase.ReadMemory(AnAddress: TDbgPtr; ASize: Cardinal;
  ADest: Pointer): Boolean;
begin
  Result := FMemReader.ReadMemory(AnAddress, ASize, ADest);
end;

function TFpDbgMemCacheManagerBase.ReadMemory(AnAddress: TDbgPtr;
  ASize: Cardinal; ADest: Pointer; ABytesRead: Cardinal): Boolean;
begin
  Result := FMemReader.ReadMemory(AnAddress, ASize, ADest, ABytesRead);
end;

function TFpDbgMemCacheManagerBase.ReadMemoryEx(AnAddress, AnAddressSpace: TDbgPtr;
  ASize: Cardinal; ADest: Pointer): Boolean;
begin
  Result := FMemReader.ReadMemoryEx(AnAddress, AnAddressSpace, ASize, ADest);
end;

{ TFpDbgMemCacheSimple }

constructor TFpDbgMemCacheSimple.Create(ACacheAddress: TDBGPtr;
  ACacheSize: Cardinal);
begin
  FCacheAddress := ACacheAddress;
  FCacheSize := ACacheSize;
end;

function TFpDbgMemCacheSimple.ContainsMemory(AnAddress: TDbgPtr; ASize: Cardinal
  ): Boolean;
begin
  Result := (ASize <= High(TDbgPtr) - AnAddress) and // not impossible memory range
            (AnAddress >= FCacheAddress) and (AnAddress + ASize <= FCacheAddress + FCacheSize);
end;

function TFpDbgMemCacheSimple.ReadMemory(AnAddress: TDbgPtr; ASize: Cardinal;
  ADest: Pointer): Boolean;
begin
  Result := False;
  if (ASize > High(TDbgPtr) - AnAddress) or // impossible memory range
     (AnAddress < FCacheAddress) or (AnAddress + ASize > FCacheAddress + FCacheSize) or
     FFailed
  then
    exit;

  if FMem = nil then begin
    SetLength(FMem, FCacheSize);
    if not MemReader.ReadMemory(FCacheAddress, FCacheSize, @FMem[0]) then begin
      FMem := nil;
      FFailed := True;
      exit;
    end;
  end;

  Result := true;
  move(FMem[AnAddress - FCacheAddress], PByte(ADest)^, ASize);
end;

{ TFpDbgMemCacheManagerSimple }

function CompareNodes(Item1, Item2: Pointer): Integer;
begin
  if TFpDbgMemCacheSimple(Item1).CacheAddress > TFpDbgMemCacheSimple(Item2).CacheAddress
  then Result := 1
  else
  if TFpDbgMemCacheSimple(Item1).CacheAddress < TFpDbgMemCacheSimple(Item2).CacheAddress
  then Result := -1
  else Result := 0;
end;

function CompareKey(Key, Item2: Pointer): Integer;
begin
  If PDBGPtr(Key)^ > TFpDbgMemCacheSimple(Item2).CacheAddress
  then Result := 1
  else
  If PDBGPtr(Key)^ < TFpDbgMemCacheSimple(Item2).CacheAddress
  then Result := -1
  else Result := 0;
end;

constructor TFpDbgMemCacheManagerSimple.Create;
begin
  FCaches := TAVLTree.Create;
  FCaches.OnCompare := @CompareNodes;
end;

destructor TFpDbgMemCacheManagerSimple.Destroy;
begin
  inherited Destroy;
  FCaches.Free;
end;

function TFpDbgMemCacheManagerSimple.HasMemory(AnAddress: TDbgPtr;
  ASize: Cardinal): Boolean;
var
  Node: TAVLTreeNode;
begin
  Result := False;
  if ASize > High(TDbgPtr) - AnAddress then // impossible memory range
    exit;

  Node := FCaches.FindNearestKey(@AnAddress, @CompareKey);
  if Node = nil then
    exit;

  if TFpDbgMemCacheSimple(Node.Data).CacheAddress > AnAddress then
    Node := Node.Precessor;;
  if Node = nil then
    exit;

  Result := (AnAddress >= TFpDbgMemCacheSimple(Node.Data).CacheAddress) and
            (AnAddress + ASize <= TFpDbgMemCacheSimple(Node.Data).CacheAddress +
             TFpDbgMemCacheSimple(Node.Data).CacheSize);
end;

function TFpDbgMemCacheManagerSimple.ReadMemory(AnAddress: TDbgPtr;
  ASize: Cardinal; ADest: Pointer): Boolean;
var
  Node: TAVLTreeNode;
begin
  Node := FCaches.FindNearestKey(@AnAddress, @CompareKey);
  if Node = nil then
    exit(inherited ReadMemory(AnAddress, ASize, ADest));

  if TFpDbgMemCacheSimple(Node.Data).CacheAddress > AnAddress then
    Node := Node.Precessor;;
  if Node = nil then
    exit(inherited ReadMemory(AnAddress, ASize, ADest));

  if TFpDbgMemCacheSimple(Node.Data).ContainsMemory(AnAddress, ASize) then begin
    Result := TFpDbgMemCacheSimple(Node.Data).ReadMemory(AnAddress, ASize, ADest);
    exit;
  end;

  Result := inherited ReadMemory(AnAddress, ASize, ADest);
end;

function TFpDbgMemCacheManagerSimple.ReadMemory(AnAddress: TDbgPtr;
  ASize: Cardinal; ADest: Pointer; ABytesRead: Cardinal): Boolean;
var
  Node: TAVLTreeNode;
begin
  Node := FCaches.FindNearestKey(@AnAddress, @CompareKey);
  if Node = nil then
    exit(inherited ReadMemory(AnAddress, ASize, ADest, ABytesRead));

  if TFpDbgMemCacheSimple(Node.Data).CacheAddress > AnAddress then
    Node := Node.Precessor;;
  if Node = nil then
    exit(inherited ReadMemory(AnAddress, ASize, ADest, ABytesRead));

  // TODO: Allow to cache partial mem reads
  if TFpDbgMemCacheSimple(Node.Data).ContainsMemory(AnAddress, ASize) then begin
    ABytesRead := ASize;
    Result := TFpDbgMemCacheSimple(Node.Data).ReadMemory(AnAddress, ASize, ADest);
    exit;
  end;

  Result := inherited ReadMemory(AnAddress, ASize, ADest, ABytesRead);
end;

function TFpDbgMemCacheManagerSimple.AddCache(AnAddress: TDbgPtr;
  ASize: Cardinal): TFpDbgMemCacheBase;
begin
  Result := nil;
  if HasMemory(AnAddress, ASize) then
    exit;

  Result := TFpDbgMemCacheSimple.Create(AnAddress, ASize);
  InitalizeCache(Result);
  FCaches.Add(Result);
end;

procedure TFpDbgMemCacheManagerSimple.RemoveCache(ACache: TFpDbgMemCacheBase);
begin
  if ACache = nil then
    exit;

  FCaches.RemovePointer(ACache);
  ACache.Free;
end;

{ TFpDbgMemManager }

function TFpDbgMemManager.GetCacheManager: TFpDbgMemCacheManagerBase;
begin
  If FCacheManager = nil then
    SetCacheManager(TFpDbgMemCacheManagerBase.Create);
  Result := FCacheManager;
end;

procedure TFpDbgMemManager.BitShiftMem(ASrcMem, ADestMem: Pointer; ASrcSize,
  ADestSize: cardinal; ABitCnt: Integer);
var
  Next, Cur: Byte;
begin
  Next := PByte(ASrcMem)^;
  dec(ADestSize);
  while ADestSize > 0 do begin
    Cur := Next;
    Next := PByte(ASrcMem + 1)^;
    PByte(ADestMem)^ := Byte(( Cur shr ABitCnt) or ( Next shl (8 - ABitCnt) ));
    ASrcMem := ASrcMem + 1;
    ADestMem := ADestMem + 1;
    dec(ADestSize);
  end;
  Cur := Next;
  Next := 0;
  if ASrcSize > ADestSize then
    Next := PByte(ASrcMem + 1)^;
  PByte(ADestMem)^ := Byte(( Cur shr ABitCnt) or ( Next shl (8 - ABitCnt) ));
end;

function TFpDbgMemManager.ReadMemory(AReadDataType: TFpDbgMemReadDataType;
  const ASourceLocation: TFpDbgMemLocation; const ASourceSize: TFpDbgValueSize;
  const ADest: Pointer; const ADestSize: QWord; AContext: TFpDbgLocationContext;
  const AFlags: TFpDbgMemManagerFlags): Boolean;
var
  ConvData: TFpDbgMemConvData;
  ReadData, ReadData2: Pointer;
  TmpVal: TDbgPtr;
  BitOffset, SourceExtraSize: Integer;
  SourceReadSize, SourceFullSize: QWord;
begin
  Result := False;
  FPartialReadResultLenght := SizeToFullBytes(ASourceSize);
  DebugLn(FPDBG_VERBOSE_MEM, ['$ReadMem: ', dbgs(AReadDataType),' ', dbgs(ASourceLocation), ' ', dbgs(ASourceSize), ' Dest ', ADestSize]);
  assert(AContext<>nil, 'TFpDbgMemManager.ReadMemory: AContext<>nil');

  // To late for an error, Dest-mem is already allocated
  assert((FMemLimits.MaxMemReadSize = 0) or (SizeToFullBytes(ASourceSize) <= FMemLimits.MaxMemReadSize), 'TFpDbgMemManager.ReadMemory: (FMemLimits.MaxMemReadSize = 0) or (SizeToFullBytes(ASourceSize) <= FMemLimits.MaxMemReadSize)');

  if (ASourceLocation.MType in [mlfInvalid, mlfUninitialized]) or
     (ASourceSize <= 0)
  then begin
    FLastError := CreateError(fpInternalErrCanNotReadInvalidMem);
    exit;
  end;

  FLastError := NoError;

  ConvData.SourceLocation     := ASourceLocation;
  ConvData.SourceSize         := ASourceSize; // ONLY valid for target/self-mem // Currently set equal to ADestSize;
  ConvData.SourceFullSize     := SizeToFullBytes(ASourceSize);
  ConvData.DestSize           := ADestSize;

  if not TargetMemConvertor.PrepareTargetRead(AReadDataType, ConvData, ADest) then begin
    FLastError := CreateError(fpErrCanNotReadMemAtAddr, [ASourceLocation.Address]);
    exit;
  end;
  assert(ConvData.DestSize <= ADestSize, 'TFpDbgMemManager.ReadMemory: ConvData.DestSize <= ADestSize');

  // SourceFullSize: excluding any size needed for BitOffset
  SourceFullSize := ConvData.SourceFullSize;
  if (SourceFullSize > TMP_MEM_SIZE) and (SourceFullSize > ConvData.DestSize) then begin
    // The un-shifted (bit-offset) result must fully fit in either ADest or FTmpMem
    FLastError := CreateError(fpInternalErrFailedReadMem);
    exit;
  end;

  (* - If SourceFullSize does not fit into ADest,
       then FinishTargetRead *MUST* copy the desired part
     - If SourceFullSize is smaller than ADest,
       then targetconverter *MUST* fill/zero/compute the missing data.
       The read data will be alligned ot the first (smallest address) byte.
     - targetconverter MUST treat FTmpMem as read-only
  *)

  BitOffset := ConvData.SourceLocation.BitOffset;
  SourceExtraSize := (BitOffset + ConvData.SourceSize.BitSize + 7) div 8;

  case ASourceLocation.MType of
    mlfTargetMem, mlfSelfMem: begin
      assert(BitOffset < 8, 'TFpDbgMemManager.ReadMemory: BitOffset < 8');
      if QWord(ConvData.SourceSize.Size) > high(SourceReadSize) - SourceExtraSize then begin
        // bigger than max read size
        FLastError := CreateError(fpErrCanNotReadMemAtAddr, [ASourceLocation.Address]);
        exit;
      end;
      SourceReadSize := ConvData.SourceSize.Size + SourceExtraSize;
      // TODO: separate check for selfmem // requires selfmem to have a size field
      if (SourceReadSize > High(TDbgPtr) - ConvData.SourceLocation.Address) or
         ( (SourceReadSize > ConvData.DestSize) and ((SourceReadSize - ConvData.DestSize) > TMP_MEM_SIZE) )
      then begin
        FLastError := CreateError(fpErrCanNotReadMemAtAddr, [ASourceLocation.Address]);
        exit;
      end;

      case ASourceLocation.MType of
        mlfTargetMem: begin
            ReadData2 := nil;
            if SourceReadSize <= ConvData.DestSize then begin
              // full read to ADest
              ReadData := ADest;
              if mmfPartialRead in AFlags then
                Result := CacheManager.ReadMemory(ConvData.SourceLocation.Address, SourceReadSize, ADest, FPartialReadResultLenght)
              else
                Result := CacheManager.ReadMemory(ConvData.SourceLocation.Address, SourceReadSize, ADest);
            end
            else
            if SourceReadSize <= TMP_MEM_SIZE then begin
              // full read to FTmpMem;
              // This is the ONLY read that has ReadData <> ADest
              // *** FinishTargetRead must copy the data ***
              ReadData := @FTmpMem[0];
              // TODO: partial reads for bit shifting?
              Result := CacheManager.ReadMemory(ConvData.SourceLocation.Address, SourceReadSize, ReadData);
            end
            else begin
              // SPLIT read to ADest/FTmpMem;
              // BitOffset must be none zero, otherwise the data must fully fit in either ADest or FTmpMem
              // *** BitShift will copy the date into ADest ***
              assert(BitOffset <> 0, 'TFpDbgMemManager.ReadMemory: BitOffset <> 0');
              ReadData := ADest;
              ReadData2 := @FTmpMem[0];
              // TODO: partial reads for bit shifting?
              Result := CacheManager.ReadMemory(ConvData.SourceLocation.Address, ConvData.DestSize, ADest);
              if Result then
                Result := CacheManager.ReadMemory(ConvData.SourceLocation.Address + ConvData.DestSize, SourceReadSize - ConvData.DestSize, ReadData2);
            end;

            if Result and (BitOffset <> 0) then begin
              if (ReadData <> ADest) then begin
                // Read to FTmpMem only
                if (SourceFullSize <= ConvData.DestSize) then begin
                  BitShiftMem(ReadData, ADest, SourceReadSize, SourceFullSize, BitOffset);
                  ReadData := ADest;
                end
                else
                  BitShiftMem(ReadData, ReadData, SourceReadSize, SourceFullSize, BitOffset);
              end
              else
                // Read to ADest or SPLIT
                BitShiftMem(ReadData, ReadData, ConvData.DestSize, ConvData.DestSize, BitOffset);

              if ReadData2 <> nil then begin
                // SPLIT read; ReadData=ADest
                // Since SourceReadSize can have max 1 extra byte => there can only be one byte; which must fit into ADest after shifting BitOffset
                PByte(ADest+ConvData.DestSize-1)^ := Byte(PByte(ADest+ConvData.DestSize-1)^ or
                  (PByte(ReadData2)^ shl (8 - BitOffset) ));
              end;
            end;
            // ReadData is now a pointer to the FULL data. Either in ADest or FTmpMem

          end;
        mlfSelfMem: begin // Can be cached TargetMem, or can be constant data from dwarf
            try // accessinge SelfMem can fail, because there is on SelfmMem.Length that can be checked
              Result := True;
              if BitOffset <> 0 then begin
                // BitShift will copy the data
                if (SourceFullSize <= ConvData.DestSize) then
                  ReadData := @ConvData.SourceLocation.Address
                else
                  ReadData := @FTmpMem[0];
                BitShiftMem(@ConvData.SourceLocation.Address, ReadData, SourceReadSize, SourceFullSize, BitOffset)
              end
              else begin
                // no BitShift
                ReadData := ADest;
                if SourceFullSize > ConvData.DestSize then
                  ReadData := @ConvData.SourceLocation.Address  // ReadData has to be read-only // FinishTargetRead must copy the data
                else
                  move(Pointer(ConvData.SourceLocation.Address)^, ADest^, SourceFullSize);
              end;
            except
              Result := False;
            end;
          end;
      end;
    end;

    mlfConstant, mlfConstantDeref, mlfTargetRegister:
      begin
        If (BitOffset <> 0) or (not IsByteSize(ConvData.SourceSize)) then begin
          // Not yet supported
          FLastError := CreateError(fpErrCanNotReadMemAtAddr, [ConvData.SourceLocation.Address]);
          Result := False;
          exit;
        end;

        case ASourceLocation.MType of
          mlfConstant, mlfConstantDeref: begin
              TmpVal := ConvData.SourceLocation.Address;
              SourceReadSize := SizeOf(ConvData.SourceLocation.Address);
            end;
          mlfTargetRegister: begin
              SourceReadSize := FMemReader.RegisterSize(Cardinal(ConvData.SourceLocation.Address));
              if SourceReadSize = 0 then
                exit; // failed
              if not FMemReader.ReadRegister(Cardinal(ConvData.SourceLocation.Address), TmpVal, AContext) then begin
                FLastError := CreateError(fpErrFailedReadRegister);
                exit; // failed
              end
            end;
        end;
        if SourceReadSize > ConvData.SourceSize.Size then
          SourceReadSize := ConvData.SourceSize.Size;

        ReadData := @TmpVal;

        if SizeOf(TmpVal) <> SourceReadSize then
          // TODO: only needed if ADestSize > SourceReadSize ?
          // Maybe do that after Move to ADest? // Maybe as part of FinishTargetRead ?
          if not FSelfMemConvertor.AdjustIntPointer(ReadData, SizeOf(TmpVal), SourceReadSize) then begin
            FLastError := CreateError(fpInternalErrFailedReadMem);
            exit;
          end;


        if SourceReadSize <= ConvData.DestSize then begin
          move(ReadData^, ADest^, Min(SizeOf(TmpVal), Int64(ConvData.DestSize))); // Little Endian only
          ReadData := ADest;
        end;

        Result := True;
      end;
  end;

  if Result then
    Result := TargetMemConvertor.FinishTargetRead(AReadDataType, ConvData, ReadData, ADest)
  else
    TargetMemConvertor.FailedTargetRead(ConvData);

  if (not Result) and (not IsError(FLastError)) then
    FLastError := CreateError(fpInternalErrFailedReadMem);
end;

function TFpDbgMemManager.WriteMemory(AReadDataType: TFpDbgMemReadDataType;
  const ADestLocation: TFpDbgMemLocation; const ADestSize: TFpDbgValueSize; const ASource: Pointer;
  const ASourceSize: QWord; AContext: TFpDbgLocationContext; const AFlags: TFpDbgMemManagerFlags
  ): Boolean;
var
  TmpVal: TDbgPtr;
  BitOffset: Integer;
  DestWriteSize: QWord;
begin
  Result := False;
  DebugLn(FPDBG_VERBOSE_MEM, ['$WriteMem: ', dbgs(AReadDataType),' ', dbgs(ADestLocation), ' ', dbgs(ADestSize), ' Source ', ASource]);
  assert(AContext<>nil, 'TFpDbgMemManager.WriteMemory: AContext<>nil');

  if (ADestLocation.MType in [mlfInvalid, mlfUninitialized]) or
     (ADestSize <= 0)
  then begin
    FLastError := CreateError(fpInternalErrCanNotWriteInvalidMem);
    exit;
  end;

  FLastError := NoError;

  // ToDo: Use a TargetMemConverter

  BitOffset := ADestLocation.BitOffset;
  //DestExtraSize := (BitOffset + ADestSize.BitSize + 7) div 8;

  case ADestLocation.MType of
    // ToDo: Add the ability to write to memory
    mlfTargetRegister:
      begin
        If (BitOffset <> 0) or (not IsByteSize(ADestSize)) then begin
          // Not yet supported
          FLastError := CreateError(fpErrCanNotWriteMemAtAddr, [ADestLocation.Address]);
          Result := False;
          exit;
        end;

        DestWriteSize := FMemReader.RegisterSize(Cardinal(ADestLocation.Address));
        if DestWriteSize = 0 then
          exit; // failed

        if SizeOf(TmpVal) < DestWriteSize then
          Exit; // failed

        move(ASource^, TmpVal, Min(SizeOf(TmpVal), Int64(ASourceSize))); // Little Endian only

        if (DestWriteSize < 8) and
           (TmpVal and (QWord($ffffffffffffffff) << (DestWriteSize*8)) <> 0) and
           ( (AReadDataType <> rdtSignedInt) or
             (TmpVal and (QWord($ffffffffffffffff) << (DestWriteSize*8)) <> (QWord($ffffffffffffffff) << (DestWriteSize*8)) )
           )
        then
          exit; // failed

        if not FMemReader.WriteRegister(Cardinal(ADestLocation.Address), TmpVal, AContext) then
          exit; // failed

        Result := True;
      end;
    mlfTargetMem:
      begin
        if (BitOffset = 0) and (ADestSize.BitSize = 0) and (ADestSize.Size > 0) then begin
          FMemReader.WriteMemory(LocToAddr(ADestLocation), SizeToFullBytes(ADestSize), ASource);
        end;
      end;
  end;

  if (not Result) and (not IsError(FLastError)) then
    FLastError := CreateError(fpErrFailedWriteMem);
end;



procedure TFpDbgMemManager.SetCacheManager(ACacheMgr: TFpDbgMemCacheManagerBase);
begin
  if FCacheManager = ACacheMgr then exit;
  FCacheManager.Free;
  FCacheManager := ACacheMgr;
  if FCacheManager <> nil then
    FCacheManager.FMemReader := FMemReader;
end;

constructor TFpDbgMemManager.Create(AMemReader: TFpDbgMemReaderBase;
  AMemConvertor: TFpDbgMemConvertor);
begin
  FMemLimits := TFpDbgMemLimits.Create;
  FMemReader := AMemReader;
  FTargetMemConvertor := AMemConvertor;
  FSelfMemConvertor := AMemConvertor;
end;

constructor TFpDbgMemManager.Create(AMemReader: TFpDbgMemReaderBase; ATargenMemConvertor,
  ASelfMemConvertor: TFpDbgMemConvertor);
begin
  FMemLimits := TFpDbgMemLimits.Create;
  FMemReader := AMemReader;
  FTargetMemConvertor := ATargenMemConvertor;
  FSelfMemConvertor := ASelfMemConvertor;
end;

destructor TFpDbgMemManager.Destroy;
begin
  SetCacheManager(nil);
  inherited Destroy;
  FMemLimits.Free;
end;

procedure TFpDbgMemManager.ClearLastError;
begin
  FLastError := NoError;
end;

function TFpDbgMemManager.RegisterSize(ARegNum: Cardinal): Integer;
begin
  Result := FMemReader.RegisterSize(ARegNum);
end;

function TFpDbgMemManager.ReadMemoryEx(
  const ASourceLocation: TFpDbgMemLocation; AnAddressSpace: TDbgPtr;
  ASize: TFpDbgValueSize; ADest: Pointer; AContext: TFpDbgLocationContext
  ): Boolean;
begin
  assert(AContext<>nil, 'TFpDbgMemManager.ReadMemoryEx: AContext<>nil');
  FLastError := NoError;
  if (ASourceLocation.BitOffset <> 0) then begin
    // Not supported to read at bit offset
    FLastError := CreateError(fpInternalErrFailedReadMem);
    Result := False;
    exit;
  end;

  // AnAddressSpace is ignored, when not actually reading from target address
  case ASourceLocation.MType of
    mlfTargetMem: Result := FMemReader.ReadMemoryEx(ASourceLocation.Address, AnAddressSpace, SizeToFullBytes(ASize), ADest);
    else
      Result := ReadMemory(rdtRawRead, ASourceLocation, ASize, ADest, ASize.Size, AContext);
  end;
  if (not Result) and (not IsError(FLastError)) then
    FLastError := CreateError(fpInternalErrFailedReadMem);
end;

function TFpDbgMemManager.ReadRegister(ARegNum: Cardinal; out AValue: TDbgPtr;
  AContext: TFpDbgLocationContext): Boolean;
begin
  assert(AContext<>nil, 'TFpDbgMemManager.ReadRegister: AContext<>nil');
  FLastError := NoError;

  // TODO: If stackframe <> 0 then get the register internally (unroll stack)
  Result := FMemReader.ReadRegister(ARegNum, AValue, AContext);
  if not Result then
    FLastError := CreateError(fpErrFailedReadRegister);
end;

function TFpDbgMemManager.SetLength(var ADest: TByteDynArray; ALength: Int64
  ): Boolean;
begin
  Result := False;
  if (FMemLimits.MaxMemReadSize > 0) and (ALength > FMemLimits.MaxMemReadSize) then begin
    FLastError := CreateError(fpErrReadMemSizeLimit);
    exit;
  end;
  Result := True;
  System.SetLength(ADest, ALength);
end;

function TFpDbgMemManager.SetLength(var ADest: RawByteString; ALength: Int64
  ): Boolean;
begin
  Result := False;
  if (FMemLimits.MaxMemReadSize > 0) and (ALength > FMemLimits.MaxMemReadSize) then begin
    FLastError := CreateError(fpErrReadMemSizeLimit);
    exit;
  end;
  Result := True;
  System.SetLength(ADest, ALength);
end;

function TFpDbgMemManager.SetLength(var ADest: AnsiString; ALength: Int64
  ): Boolean;
begin
  Result := False;
  if (FMemLimits.MaxMemReadSize > 0) and (ALength > FMemLimits.MaxMemReadSize) then begin
    FLastError := CreateError(fpErrReadMemSizeLimit);
    exit;
  end;
  Result := True;
  System.SetLength(ADest, ALength);
end;

function TFpDbgMemManager.SetLength(var ADest: WideString; ALength: Int64
  ): Boolean;
begin
  Result := False;
  if (FMemLimits.MaxMemReadSize > 0) and (ALength * 2 > FMemLimits.MaxMemReadSize) then begin
    FLastError := CreateError(fpErrReadMemSizeLimit);
    exit;
  end;
  Result := True;
  System.SetLength(ADest, ALength);
end;

function TFpDbgMemManager.CheckDataSize(ASize: Int64): Boolean;
begin
  Result := False;
  if (FMemLimits.MaxMemReadSize > 0) and (ASize > FMemLimits.MaxMemReadSize) then begin
    FLastError := CreateError(fpErrReadMemSizeLimit);
    exit;
  end;
  Result := True;
end;


initialization
  FPDBG_VERBOSE_MEM := DebugLogger.FindOrRegisterLogGroup('FPDBG_VERBOSE_MEM' {$IFDEF FPDBG_VERBOSE_MEM} , True {$ENDIF} );

end.