Welcome to mirror list, hosted at ThFree Co, Russian Federation.

DmgHandler.cpp « Archive « 7zip « CPP - github.com/kornelski/7z.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 608ad4c41c174c4e925f64af0d9a330012982dc7 (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
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
// DmgHandler.cpp

#include "StdAfx.h"

#include "../../../C/CpuArch.h"

#include "../../Common/ComTry.h"
#include "../../Common/IntToString.h"
#include "../../Common/MyXml.h"
#include "../../Common/UTFConvert.h"

#include "../../Windows/PropVariant.h"

#include "../Common/LimitedStreams.h"
#include "../Common/ProgressUtils.h"
#include "../Common/RegisterArc.h"
#include "../Common/StreamObjects.h"
#include "../Common/StreamUtils.h"

#include "../Compress/BZip2Decoder.h"
#include "../Compress/CopyCoder.h"
#include "../Compress/LzfseDecoder.h"
#include "../Compress/ZlibDecoder.h"

#include "Common/OutStreamWithCRC.h"

// #define DMG_SHOW_RAW

// #include <stdio.h>
#define PRF(x) // x

#define Get16(p) GetBe16(p)
#define Get32(p) GetBe32(p)
#define Get64(p) GetBe64(p)

static const Byte k_Base64Table[256] =
{
  66,77,77,77,77,77,77,77,77,65,65,77,77,65,77,77,
  77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,
  65,77,77,77,77,77,77,77,77,77,77,62,77,77,77,63,
  52,53,54,55,56,57,58,59,60,61,77,77,77,64,77,77,
  77, 0, 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,77,77,77,77,77,
  77,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,77,77,77,77,77,
  77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,
  77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,
  77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,
  77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,
  77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,
  77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,
  77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,
  77,77,77,77,77,77,77,77,77,77,77,77,77,77,77,77
};

static Byte *Base64ToBin(Byte *dest, const char *src)
{
  UInt32 val = 1;
  
  for (;;)
  {
    UInt32 c = k_Base64Table[(Byte)(*src++)];

    if (c < 64)
    {
      val = (val << 6) | c;
      if ((val & ((UInt32)1 << 24)) == 0)
        continue;
      dest[0] = (Byte)(val >> 16);
      dest[1] = (Byte)(val >> 8);
      dest[2] = (Byte)(val);
      dest += 3;
      val = 1;
      continue;
    }
    
    if (c == 65) // space
      continue;
    
    if (c == 64) // '='
      break;
    
    if (c == 66 && val == 1) // end of string
      return dest;
    
    return NULL;
  }

  if (val < (1 << 12))
    return NULL;

  if (val & (1 << 18))
  {
    *dest++ = (Byte)(val >> 10);
    *dest++ = (Byte)(val >> 2);
  }
  else if (k_Base64Table[(Byte)(*src++)] != 64) // '='
    return NULL;
  else
    *dest++ = (Byte)(val >> 4);

  for (;;)
  {
    Byte c = k_Base64Table[(Byte)(*src++)];
    if (c == 65) // space
      continue;
    if (c == 66) // end of string
      return dest;
    return NULL;
  }
}


namespace NArchive {
namespace NDmg {

enum
{
  METHOD_ZERO_0 = 0,
  METHOD_COPY   = 1,
  METHOD_ZERO_2 = 2, // without file CRC calculation
  METHOD_ADC    = 0x80000004,
  METHOD_ZLIB   = 0x80000005,
  METHOD_BZIP2  = 0x80000006,
  METHOD_LZFSE  = 0x80000007,
  METHOD_COMMENT = 0x7FFFFFFE, // is used to comment "+beg" and "+end" in extra field.
  METHOD_END    = 0xFFFFFFFF
};

struct CBlock
{
  UInt32 Type;
  UInt64 UnpPos;
  UInt64 UnpSize;
  UInt64 PackPos;
  UInt64 PackSize;
  
  UInt64 GetNextPackOffset() const { return PackPos + PackSize; }
  UInt64 GetNextUnpPos() const { return UnpPos + UnpSize; }

  bool IsZeroMethod() const { return Type == METHOD_ZERO_0 || Type == METHOD_ZERO_2; }
  bool ThereAreDataInBlock() const { return Type != METHOD_COMMENT && Type != METHOD_END; }
};

static const UInt32 kCheckSumType_CRC = 2;

static const size_t kChecksumSize_Max = 0x80;

struct CChecksum
{
  UInt32 Type;
  UInt32 NumBits;
  Byte Data[kChecksumSize_Max];

  bool IsCrc32() const { return Type == kCheckSumType_CRC && NumBits == 32; }
  UInt32 GetCrc32() const { return Get32(Data); }
  void Parse(const Byte *p);
};

void CChecksum::Parse(const Byte *p)
{
  Type = Get32(p);
  NumBits = Get32(p + 4);
  memcpy(Data, p + 8, kChecksumSize_Max);
};

struct CFile
{
  UInt64 Size;
  UInt64 PackSize;
  UInt64 StartPos;
  AString Name;
  CRecordVector<CBlock> Blocks;
  CChecksum Checksum;
  bool FullFileChecksum;

  HRESULT Parse(const Byte *p, UInt32 size);
};

#ifdef DMG_SHOW_RAW
struct CExtraFile
{
  CByteBuffer Data;
  AString Name;
};
#endif


struct CForkPair
{
  UInt64 Offset;
  UInt64 Len;
  
  void Parse(const Byte *p)
  {
    Offset = Get64(p);
    Len = Get64(p + 8);
  }

  bool UpdateTop(UInt64 limit, UInt64 &top)
  {
    if (Offset > limit || Len > limit - Offset)
      return false;
    UInt64 top2 = Offset + Len;
    if (top <= top2)
      top = top2;
    return true;
  }
};


class CHandler:
  public IInArchive,
  public IInArchiveGetStream,
  public CMyUnknownImp
{
  CMyComPtr<IInStream> _inStream;
  CObjectVector<CFile> _files;
  bool _masterCrcError;
  bool _headersError;

  UInt64 _startPos;
  UInt64 _phySize;

  AString _name;
  
  #ifdef DMG_SHOW_RAW
  CObjectVector<CExtraFile> _extras;
  #endif

  HRESULT ReadData(IInStream *stream, const CForkPair &pair, CByteBuffer &buf);
  bool ParseBlob(const CByteBuffer &data);
  HRESULT Open2(IInStream *stream);
  HRESULT Extract(IInStream *stream);
public:
  MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream)
  INTERFACE_IInArchive(;)
  STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream);
};

// that limit can be increased, if there are such dmg files
static const size_t kXmlSizeMax = 0xFFFF0000; // 4 GB - 64 KB;

struct CMethods
{
  CRecordVector<UInt32> Types;
  CRecordVector<UInt32> ChecksumTypes;

  void Update(const CFile &file);
  void GetString(AString &s) const;
};

void CMethods::Update(const CFile &file)
{
  ChecksumTypes.AddToUniqueSorted(file.Checksum.Type);
  FOR_VECTOR (i, file.Blocks)
    Types.AddToUniqueSorted(file.Blocks[i].Type);
}

void CMethods::GetString(AString &res) const
{
  res.Empty();

  unsigned i;
  
  for (i = 0; i < Types.Size(); i++)
  {
    UInt32 type = Types[i];
    if (type == METHOD_COMMENT || type == METHOD_END)
      continue;
    char buf[16];
    const char *s;
    switch (type)
    {
      case METHOD_ZERO_0: s = "Zero0"; break;
      case METHOD_ZERO_2: s = "Zero2"; break;
      case METHOD_COPY:   s = "Copy";  break;
      case METHOD_ADC:    s = "ADC";   break;
      case METHOD_ZLIB:   s = "ZLIB";  break;
      case METHOD_BZIP2:  s = "BZip2"; break;
      case METHOD_LZFSE:  s = "LZFSE"; break;
      default: ConvertUInt32ToString(type, buf); s = buf;
    }
    res.Add_OptSpaced(s);
  }
  
  for (i = 0; i < ChecksumTypes.Size(); i++)
  {
    res.Add_Space_if_NotEmpty();
    UInt32 type = ChecksumTypes[i];
    switch (type)
    {
      case kCheckSumType_CRC: res += "CRC"; break;
      default:
        res += "Check";
        res.Add_UInt32(type);
    }
  }
}

struct CAppleName
{
  bool IsFs;
  const char *Ext;
  const char *AppleName;
};

static const CAppleName k_Names[] =
{
  { true,  "hfs",  "Apple_HFS" },
  { true,  "hfsx", "Apple_HFSX" },
  { true,  "ufs",  "Apple_UFS" },

  // efi_sys partition is FAT32, but it's not main file. So we use (IsFs = false)
  { false,  "efi_sys", "C12A7328-F81F-11D2-BA4B-00A0C93EC93B" },

  { false, "free", "Apple_Free" },
  { false, "ddm",  "DDM" },
  { false, NULL,   "Apple_partition_map" },
  { false, NULL,   " GPT " },
  { false, NULL,   "MBR" },
  { false, NULL,   "Driver" },
  { false, NULL,   "Patches" }
};
  
static const unsigned kNumAppleNames = ARRAY_SIZE(k_Names);

static const Byte kProps[] =
{
  kpidPath,
  kpidSize,
  kpidPackSize,
  kpidCRC,
  kpidComment,
  kpidMethod
};

IMP_IInArchive_Props

static const Byte kArcProps[] =
{
  kpidMethod,
  kpidNumBlocks,
  kpidComment
};

STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
{
  COM_TRY_BEGIN
  NWindows::NCOM::CPropVariant prop;
  switch (propID)
  {
    case kpidMethod:
    {
      CMethods m;
      FOR_VECTOR (i, _files)
        m.Update(_files[i]);
      AString s;
      m.GetString(s);
      if (!s.IsEmpty())
        prop = s;
      break;
    }
    case kpidNumBlocks:
    {
      UInt64 numBlocks = 0;
      FOR_VECTOR (i, _files)
        numBlocks += _files[i].Blocks.Size();
      prop = numBlocks;
      break;
    }
    case kpidMainSubfile:
    {
      int mainIndex = -1;
      unsigned numFS = 0;
      unsigned numUnknown = 0;
      FOR_VECTOR (i, _files)
      {
        const AString &name = _files[i].Name;
        unsigned n;
        for (n = 0; n < kNumAppleNames; n++)
        {
          const CAppleName &appleName = k_Names[n];
          // if (name.Find(appleName.AppleName) >= 0)
          if (strstr(name, appleName.AppleName))
          {
            if (appleName.IsFs)
            {
              numFS++;
              mainIndex = i;
            }
            break;
          }
        }
        if (n == kNumAppleNames)
        {
          mainIndex = i;
          numUnknown++;
        }
      }
      if (numFS + numUnknown == 1)
        prop = (UInt32)mainIndex;
      break;
    }
    case kpidWarning:
      if (_masterCrcError)
        prop = "Master CRC error";

    case kpidWarningFlags:
    {
      UInt32 v = 0;
      if (_headersError) v |= kpv_ErrorFlags_HeadersError;
      if (v != 0)
        prop = v;
      break;
    }

    case kpidOffset: prop = _startPos; break;
    case kpidPhySize: prop = _phySize; break;

    case kpidComment:
      if (!_name.IsEmpty() && _name.Len() < 256)
        prop = _name;
      break;

    case kpidName:
      if (!_name.IsEmpty() && _name.Len() < 256)
      {
        prop = _name + ".dmg";
      }
      break;
  }
  prop.Detach(value);
  return S_OK;
  COM_TRY_END
}

IMP_IInArchive_ArcProps

HRESULT CFile::Parse(const Byte *p, UInt32 size)
{
  const UInt32 kHeadSize = 0xCC;
  if (size < kHeadSize)
    return S_FALSE;
  if (Get32(p) != 0x6D697368) // "mish" signature
    return S_FALSE;
  if (Get32(p + 4) != 1) // version
    return S_FALSE;
  // UInt64 firstSectorNumber = Get64(p + 8);
  UInt64 numSectors = Get64(p + 0x10);

  StartPos = Get64(p + 0x18);

  // UInt32 decompressedBufRequested = Get32(p + 0x20); // ???
  // UInt32 blocksDescriptor = Get32(p + 0x24); // number starting from -1?
  // char Reserved1[24];
  
  Checksum.Parse(p + 0x40);
  PRF(printf("\n\nChecksum Type = %2d", Checksum.Type));

  UInt32 numBlocks = Get32(p + 0xC8);
  if (numBlocks > ((UInt32)1 << 28))
    return S_FALSE;

  const UInt32 kRecordSize = 40;
  if (numBlocks * kRecordSize + kHeadSize != size)
    return S_FALSE;

  PackSize = 0;
  Size = 0;
  Blocks.ClearAndReserve(numBlocks);
  FullFileChecksum = true;

  p += kHeadSize;
  UInt32 i;
 
  for (i = 0; i < numBlocks; i++, p += kRecordSize)
  {
    CBlock b;
    b.Type = Get32(p);
    b.UnpPos   = Get64(p + 0x08) << 9;
    b.UnpSize  = Get64(p + 0x10) << 9;
    b.PackPos  = Get64(p + 0x18);
    b.PackSize = Get64(p + 0x20);
    
    // b.PackPos can be 0 for some types. So we don't check it
    if (!Blocks.IsEmpty())
      if (b.UnpPos != Blocks.Back().GetNextUnpPos())
        return S_FALSE;
    
    PRF(printf("\nType=%8x  m[1]=%8x  uPos=%8x  uSize=%7x  pPos=%8x  pSize=%7x",
        b.Type, Get32(p + 4), (UInt32)b.UnpPos, (UInt32)b.UnpSize, (UInt32)b.PackPos, (UInt32)b.PackSize));
    
    if (b.Type == METHOD_COMMENT)
      continue;
    if (b.Type == METHOD_END)
      break;
    PackSize += b.PackSize;
  
    if (b.UnpSize != 0)
    {
      if (b.Type == METHOD_ZERO_2)
        FullFileChecksum = false;
      Blocks.AddInReserved(b);
    }
  }
  
  if (i != numBlocks - 1)
    return S_FALSE;
  if (!Blocks.IsEmpty())
    Size = Blocks.Back().GetNextUnpPos();
  if (Size != (numSectors << 9))
    return S_FALSE;
  
  return S_OK;
}

static int FindKeyPair(const CXmlItem &item, const char *key, const char *nextTag)
{
  for (unsigned i = 0; i + 1 < item.SubItems.Size(); i++)
  {
    const CXmlItem &si = item.SubItems[i];
    if (si.IsTagged("key") && si.GetSubString() == key && item.SubItems[i + 1].IsTagged(nextTag))
      return i + 1;
  }
  return -1;
}

static const AString *GetStringFromKeyPair(const CXmlItem &item, const char *key, const char *nextTag)
{
  int index = FindKeyPair(item, key, nextTag);
  if (index >= 0)
    return item.SubItems[index].GetSubStringPtr();
  return NULL;
}

static const unsigned HEADER_SIZE = 0x200;

static const Byte k_Signature[] = { 'k','o','l','y', 0, 0, 0, 4, 0, 0, 2, 0 };

static inline bool IsKoly(const Byte *p)
{
  return memcmp(p, k_Signature, ARRAY_SIZE(k_Signature)) == 0;
  /*
  if (Get32(p) != 0x6B6F6C79) // "koly" signature
    return false;
  if (Get32(p + 4) != 4) // version
    return false;
  if (Get32(p + 8) != HEADER_SIZE)
    return false;
  return true;
  */
}


HRESULT CHandler::ReadData(IInStream *stream, const CForkPair &pair, CByteBuffer &buf)
{
  size_t size = (size_t)pair.Len;
  if (size != pair.Len)
    return E_OUTOFMEMORY;
  buf.Alloc(size);
  RINOK(stream->Seek(_startPos + pair.Offset, STREAM_SEEK_SET, NULL));
  return ReadStream_FALSE(stream, buf, size);
}


bool CHandler::ParseBlob(const CByteBuffer &data)
{
  if (data.Size() < 12)
    return false;
  const Byte *p = (const Byte *)data;
  if (Get32(p) != 0xFADE0CC0)
    return true;
  const UInt32 size = Get32(p + 4);
  if (size != data.Size())
    return false;
  const UInt32 num = Get32(p + 8);
  if (num > (size - 12) / 8)
    return false;
  
  for (UInt32 i = 0; i < num; i++)
  {
    // UInt32 type = Get32(p + i * 8 + 12);
    UInt32 offset = Get32(p + i * 8 + 12 + 4);
    if (size - offset < 8)
      return false;
    const Byte *p2 = (const Byte *)data + offset;
    const UInt32 magic = Get32(p2);
    const UInt32 len = Get32(p2 + 4);
    if (size - offset < len || len < 8)
      return false;

    #ifdef DMG_SHOW_RAW
    CExtraFile &extra = _extras.AddNew();
    extra.Name = "_blob_";
    extra.Data.CopyFrom(p2, len);
    #endif

    if (magic == 0xFADE0C02)
    {
      #ifdef DMG_SHOW_RAW
      extra.Name += "codedir";
      #endif
    
      if (len < 11 * 4)
        return false;
      UInt32 idOffset = Get32(p2 + 0x14);
      if (idOffset >= len)
        return false;
      UInt32 len2 = len - idOffset;
      if (len2 < (1 << 10))
        _name.SetFrom_CalcLen((const char *)(p2 + idOffset), len2);
    }
    #ifdef DMG_SHOW_RAW
    else if (magic == 0xFADE0C01)
      extra.Name += "requirements";
    else if (magic == 0xFADE0B01)
      extra.Name += "signed";
    else
    {
      char temp[16];
      ConvertUInt32ToHex8Digits(magic, temp);
      extra.Name += temp;
    }
    #endif
  }

  return true;
}


HRESULT CHandler::Open2(IInStream *stream)
{
  RINOK(stream->Seek(0, STREAM_SEEK_CUR, &_startPos));

  Byte buf[HEADER_SIZE];
  RINOK(ReadStream_FALSE(stream, buf, HEADER_SIZE));

  UInt64 headerPos;
  if (IsKoly(buf))
    headerPos = _startPos;
  else
  {
    RINOK(stream->Seek(0, STREAM_SEEK_END, &headerPos));
    if (headerPos < HEADER_SIZE)
      return S_FALSE;
    headerPos -= HEADER_SIZE;
    RINOK(stream->Seek(headerPos, STREAM_SEEK_SET, NULL));
    RINOK(ReadStream_FALSE(stream, buf, HEADER_SIZE));
    if (!IsKoly(buf))
      return S_FALSE;
  }

  // UInt32 flags = Get32(buf + 12);
  // UInt64 runningDataForkOffset = Get64(buf + 0x10);
  
  CForkPair dataForkPair, rsrcPair, xmlPair, blobPair;
  
  dataForkPair.Parse(buf + 0x18);
  rsrcPair.Parse(buf + 0x28);
  xmlPair.Parse(buf + 0xD8);
  blobPair.Parse(buf + 0x128);

  // UInt32 segmentNumber = Get32(buf + 0x38);
  // UInt32 segmentCount = Get32(buf + 0x3C);
  // Byte segmentGUID[16];
  // CChecksum dataForkChecksum;
  // dataForkChecksum.Parse(buf + 0x50);

  _startPos = 0;

  UInt64 top = 0;
  if (!dataForkPair.UpdateTop(headerPos, top)) return S_FALSE;
  if (!xmlPair.UpdateTop(headerPos, top)) return S_FALSE;
  if (!rsrcPair.UpdateTop(headerPos, top)) return S_FALSE;

  /* Some old dmg files contain garbage data in blobPair field.
     So we need to ignore such garbage case;
     And we still need to detect offset of start of archive for "parser" mode. */

  bool useBlob = blobPair.UpdateTop(headerPos, top);

  _startPos = 0;
  _phySize = headerPos + HEADER_SIZE;

  if (top != headerPos)
  {
    CForkPair xmlPair2 = xmlPair;
    const char *sz = "<?xml version";
    const unsigned len = (unsigned)strlen(sz);
    if (xmlPair2.Len > len)
      xmlPair2.Len = len;
    CByteBuffer buf2;
    if (ReadData(stream, xmlPair2, buf2) != S_OK
        || memcmp(buf2, sz, len) != 0)
    {
      _startPos = headerPos - top;
      _phySize = top + HEADER_SIZE;
    }
  }

  // Byte reserved[0x78]

  if (useBlob && blobPair.Len != 0)
  {
    #ifdef DMG_SHOW_RAW
    CExtraFile &extra = _extras.AddNew();
    extra.Name = "_blob.bin";
    CByteBuffer &blobBuf = extra.Data;
    #else
    CByteBuffer blobBuf;
    #endif
    RINOK(ReadData(stream, blobPair, blobBuf));
    if (!ParseBlob(blobBuf))
      _headersError = true;
  }


  CChecksum masterChecksum;
  masterChecksum.Parse(buf + 0x160);

  // UInt32 imageVariant = Get32(buf + 0x1E8);
  // UInt64 numSectors = Get64(buf + 0x1EC);
  // Byte reserved[0x12]

  const UInt32 RSRC_HEAD_SIZE = 0x100;

  // We don't know the size of the field "offset" in rsrc.
  // We suppose that it uses 24 bits. So we use Rsrc, only if the rsrcLen < (1 << 24).
  bool useRsrc = (rsrcPair.Len > RSRC_HEAD_SIZE && rsrcPair.Len < ((UInt32)1 << 24));
  // useRsrc = false;

  if (useRsrc)
  {
    #ifdef DMG_SHOW_RAW
    CExtraFile &extra = _extras.AddNew();
    extra.Name = "rsrc.bin";
    CByteBuffer &rsrcBuf = extra.Data;
    #else
    CByteBuffer rsrcBuf;
    #endif

    RINOK(ReadData(stream, rsrcPair, rsrcBuf));

    const Byte *p = rsrcBuf;
    UInt32 headSize = Get32(p + 0);
    UInt32 footerOffset = Get32(p + 4);
    UInt32 mainDataSize = Get32(p + 8);
    UInt32 footerSize = Get32(p + 12);
    if (headSize != RSRC_HEAD_SIZE
        || footerOffset >= rsrcPair.Len
        || mainDataSize >= rsrcPair.Len
        || footerOffset + footerSize != rsrcPair.Len
        || footerOffset != headSize + mainDataSize)
      return S_FALSE;
    if (footerSize < 16)
      return S_FALSE;
    if (memcmp(p, p + footerOffset, 16) != 0)
      return S_FALSE;

    p += footerOffset;

    if ((UInt32)Get16(p + 0x18) != 0x1C)
      return S_FALSE;
    const UInt32 namesOffset = Get16(p + 0x1A);
    if (namesOffset > footerSize)
      return S_FALSE;
    
    UInt32 numItems = (UInt32)Get16(p + 0x1C) + 1;
    if (numItems * 8 + 0x1E > namesOffset)
      return S_FALSE;
    
    for (UInt32 i = 0; i < numItems; i++)
    {
      const Byte *p2 = p + 0x1E + i * 8;
    
      const UInt32 typeId = Get32(p2);
      
      #ifndef DMG_SHOW_RAW
      if (typeId != 0x626C6B78) // blkx
        continue;
      #endif
      
      const UInt32 numFiles = (UInt32)Get16(p2 + 4) + 1;
      const UInt32 offs = Get16(p2 + 6);
      if (0x1C + offs + 12 * numFiles > namesOffset)
        return S_FALSE;

      for (UInt32 k = 0; k < numFiles; k++)
      {
        const Byte *p3 = p + 0x1C + offs + k * 12;
        // UInt32 id = Get16(p3);
        const UInt32 namePos = Get16(p3 + 2);
        // Byte attributes = p3[4]; // = 0x50 for blkx
        // we don't know how many bits we can use. So we use 24 bits only
        UInt32 blockOffset = Get32(p3 + 4);
        blockOffset &= (((UInt32)1 << 24) - 1);
        // UInt32 unknown2 = Get32(p3 + 8); // ???
        if (blockOffset + 4 >= mainDataSize)
          return S_FALSE;
        const Byte *pBlock = rsrcBuf + headSize + blockOffset;
        const UInt32 blockSize = Get32(pBlock);
        if (mainDataSize - (blockOffset + 4) < blockSize)
          return S_FALSE;
        
        AString name;
        
        if (namePos != 0xFFFF)
        {
          UInt32 namesBlockSize = footerSize - namesOffset;
          if (namePos >= namesBlockSize)
            return S_FALSE;
          const Byte *namePtr = p + namesOffset + namePos;
          UInt32 nameLen = *namePtr;
          if (namesBlockSize - namePos <= nameLen)
            return S_FALSE;
          for (UInt32 r = 1; r <= nameLen; r++)
          {
            Byte c = namePtr[r];
            if (c < 0x20 || c >= 0x80)
              break;
            name += (char)c;
          }
        }
        
        if (typeId == 0x626C6B78) // blkx
        {
          CFile &file = _files.AddNew();
          file.Name = name;
          RINOK(file.Parse(pBlock + 4, blockSize));
        }
        
        #ifdef DMG_SHOW_RAW
        {
          AString name2;

          name2.Add_UInt32(i);
          name2 += '_';

          {
            char temp[4 + 1] = { 0 };
            memcpy(temp, p2, 4);
            name2 += temp;
          }
          name2.Trim();
          name2 += '_';
          name2.Add_UInt32(k);
          
          if (!name.IsEmpty())
          {
            name2 += '_';
            name2 += name;
          }
          
          CExtraFile &extra = _extras.AddNew();
          extra.Name = name2;
          extra.Data.CopyFrom(pBlock + 4, blockSize);
        }
        #endif
      }
    }
  }
  else
  {
    if (xmlPair.Len >= kXmlSizeMax || xmlPair.Len == 0)
      return S_FALSE;
    size_t size = (size_t)xmlPair.Len;
    if (size != xmlPair.Len)
      return S_FALSE;

    RINOK(stream->Seek(_startPos + xmlPair.Offset, STREAM_SEEK_SET, NULL));
    
    CXml xml;
    {
      CObjArray<char> xmlStr(size + 1);
      RINOK(ReadStream_FALSE(stream, xmlStr, size));
      xmlStr[size] = 0;
      // if (strlen(xmlStr) != size) return S_FALSE;
      if (!xml.Parse(xmlStr))
        return S_FALSE;

      #ifdef DMG_SHOW_RAW
      CExtraFile &extra = _extras.AddNew();
      extra.Name = "a.xml";
      extra.Data.CopyFrom((const Byte *)(const char *)xmlStr, size);
      #endif
    }
    
    if (xml.Root.Name != "plist")
      return S_FALSE;
    
    int dictIndex = xml.Root.FindSubTag("dict");
    if (dictIndex < 0)
      return S_FALSE;
    
    const CXmlItem &dictItem = xml.Root.SubItems[dictIndex];
    int rfDictIndex = FindKeyPair(dictItem, "resource-fork", "dict");
    if (rfDictIndex < 0)
      return S_FALSE;
    
    const CXmlItem &rfDictItem = dictItem.SubItems[rfDictIndex];
    int arrIndex = FindKeyPair(rfDictItem, "blkx", "array");
    if (arrIndex < 0)
      return S_FALSE;
    
    const CXmlItem &arrItem = rfDictItem.SubItems[arrIndex];
    
    FOR_VECTOR (i, arrItem.SubItems)
    {
      const CXmlItem &item = arrItem.SubItems[i];
      if (!item.IsTagged("dict"))
        continue;
      
      CByteBuffer rawBuf;
      unsigned destLen = 0;
      {
        const AString *dataString = GetStringFromKeyPair(item, "Data", "data");
        if (!dataString)
          return S_FALSE;
        destLen = dataString->Len() / 4 * 3 + 4;
        rawBuf.Alloc(destLen);
        {
          const Byte *endPtr = Base64ToBin(rawBuf, *dataString);
          if (!endPtr)
            return S_FALSE;
          destLen = (unsigned)(endPtr - (const Byte *)rawBuf);
        }
        
        #ifdef DMG_SHOW_RAW
        CExtraFile &extra = _extras.AddNew();
        extra.Name.Add_UInt32(_files.Size());
        extra.Data.CopyFrom(rawBuf, destLen);
        #endif
      }
      CFile &file = _files.AddNew();
      {
        const AString *name = GetStringFromKeyPair(item, "Name", "string");
        if (!name || name->IsEmpty())
          name = GetStringFromKeyPair(item, "CFName", "string");
        if (name)
          file.Name = *name;
      }
      RINOK(file.Parse(rawBuf, destLen));
    }
  }

  if (masterChecksum.IsCrc32())
  {
    UInt32 crc = CRC_INIT_VAL;
    unsigned i;
    for (i = 0; i < _files.Size(); i++)
    {
      const CChecksum &cs = _files[i].Checksum;
      if ((cs.NumBits & 0x7) != 0)
        break;
      UInt32 len = cs.NumBits >> 3;
      if (len > kChecksumSize_Max)
        break;
      crc = CrcUpdate(crc, cs.Data, (size_t)len);
    }
    if (i == _files.Size())
      _masterCrcError = (CRC_GET_DIGEST(crc) != masterChecksum.GetCrc32());
  }

  return S_OK;
}

STDMETHODIMP CHandler::Open(IInStream *stream,
    const UInt64 * /* maxCheckStartPosition */,
    IArchiveOpenCallback * /* openArchiveCallback */)
{
  COM_TRY_BEGIN
  {
    Close();
    if (Open2(stream) != S_OK)
      return S_FALSE;
    _inStream = stream;
  }
  return S_OK;
  COM_TRY_END
}

STDMETHODIMP CHandler::Close()
{
  _phySize = 0;
  _inStream.Release();
  _files.Clear();
  _masterCrcError = false;
  _headersError = false;
  _name.Empty();
  #ifdef DMG_SHOW_RAW
  _extras.Clear();
  #endif
  return S_OK;
}

STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems)
{
  *numItems = _files.Size()
    #ifdef DMG_SHOW_RAW
    + _extras.Size()
    #endif
  ;
  return S_OK;
}

#define RAW_PREFIX "raw" STRING_PATH_SEPARATOR

STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)
{
  COM_TRY_BEGIN
  NWindows::NCOM::CPropVariant prop;
  
  #ifdef DMG_SHOW_RAW
  if (index >= _files.Size())
  {
    const CExtraFile &extra = _extras[index - _files.Size()];
    switch (propID)
    {
      case kpidPath:
        prop = (AString)RAW_PREFIX + extra.Name;
        break;
      case kpidSize:
      case kpidPackSize:
        prop = (UInt64)extra.Data.Size();
        break;
    }
  }
  else
  #endif
  {
    const CFile &item = _files[index];
    switch (propID)
    {
      case kpidSize:  prop = item.Size; break;
      case kpidPackSize:  prop = item.PackSize; break;
      case kpidCRC:
      {
        if (item.Checksum.IsCrc32() && item.FullFileChecksum)
          prop = item.Checksum.GetCrc32();
        break;
      }

      case kpidMethod:
      {
        CMethods m;
        m.Update(item);
        AString s;
        m.GetString(s);
        if (!s.IsEmpty())
          prop = s;
        break;
      }
      
      case kpidPath:
      {
        UString name;
        name.Add_UInt32(index);
        unsigned num = 10;
        unsigned numDigits;
        for (numDigits = 1; num < _files.Size(); numDigits++)
          num *= 10;
        while (name.Len() < numDigits)
          name.InsertAtFront(L'0');

        AString subName;
        int pos1 = item.Name.Find('(');
        if (pos1 >= 0)
        {
          pos1++;
          int pos2 = item.Name.Find(')', pos1);
          if (pos2 >= 0)
          {
            subName.SetFrom(item.Name.Ptr(pos1), pos2 - pos1);
            pos1 = subName.Find(':');
            if (pos1 >= 0)
              subName.DeleteFrom(pos1);
          }
        }
        subName.Trim();
        if (!subName.IsEmpty())
        {
          for (unsigned n = 0; n < kNumAppleNames; n++)
          {
            const CAppleName &appleName = k_Names[n];
            if (appleName.Ext)
            {
              if (subName == appleName.AppleName)
              {
                subName = appleName.Ext;
                break;
              }
            }
          }
          UString name2;
          ConvertUTF8ToUnicode(subName, name2);
          name += '.';
          name += name2;
        }
        else
        {
          UString name2;
          ConvertUTF8ToUnicode(item.Name, name2);
          if (!name2.IsEmpty())
            name += "_";
          name += name2;
        }
        prop = name;
        break;
      }
      
      case kpidComment:
      {
        UString name;
        ConvertUTF8ToUnicode(item.Name, name);
        prop = name;
        break;
      }
    }
  }
  prop.Detach(value);
  return S_OK;
  COM_TRY_END
}

class CAdcDecoder:
  public ICompressCoder,
  public CMyUnknownImp
{
  CLzOutWindow m_OutWindowStream;
  CInBuffer m_InStream;

  /*
  void ReleaseStreams()
  {
    m_OutWindowStream.ReleaseStream();
    m_InStream.ReleaseStream();
  }
  */

  class CCoderReleaser
  {
    CAdcDecoder *m_Coder;
  public:
    bool NeedFlush;
    CCoderReleaser(CAdcDecoder *coder): m_Coder(coder), NeedFlush(true) {}
    ~CCoderReleaser()
    {
      if (NeedFlush)
        m_Coder->m_OutWindowStream.Flush();
      // m_Coder->ReleaseStreams();
    }
  };
  friend class CCoderReleaser;

public:
  MY_UNKNOWN_IMP

  STDMETHOD(CodeReal)(ISequentialInStream *inStream,
      ISequentialOutStream *outStream, const UInt64 *inSize, const UInt64 *outSize,
      ICompressProgressInfo *progress);

  STDMETHOD(Code)(ISequentialInStream *inStream,
      ISequentialOutStream *outStream, const UInt64 *inSize, const UInt64 *outSize,
      ICompressProgressInfo *progress);
};

STDMETHODIMP CAdcDecoder::CodeReal(ISequentialInStream *inStream,
    ISequentialOutStream *outStream, const UInt64 *inSize, const UInt64 *outSize,
    ICompressProgressInfo *progress)
{
  if (!m_OutWindowStream.Create(1 << 18))
    return E_OUTOFMEMORY;
  if (!m_InStream.Create(1 << 18))
    return E_OUTOFMEMORY;

  m_OutWindowStream.SetStream(outStream);
  m_OutWindowStream.Init(false);
  m_InStream.SetStream(inStream);
  m_InStream.Init();
  
  CCoderReleaser coderReleaser(this);

  const UInt32 kStep = (1 << 20);
  UInt64 nextLimit = kStep;

  UInt64 pos = 0;
  while (pos < *outSize)
  {
    if (pos > nextLimit && progress)
    {
      UInt64 packSize = m_InStream.GetProcessedSize();
      RINOK(progress->SetRatioInfo(&packSize, &pos));
      nextLimit += kStep;
    }
    Byte b;
    if (!m_InStream.ReadByte(b))
      return S_FALSE;
    UInt64 rem = *outSize - pos;
    if (b & 0x80)
    {
      unsigned num = (b & 0x7F) + 1;
      if (num > rem)
        return S_FALSE;
      for (unsigned i = 0; i < num; i++)
      {
        if (!m_InStream.ReadByte(b))
          return S_FALSE;
        m_OutWindowStream.PutByte(b);
      }
      pos += num;
      continue;
    }
    Byte b1;
    if (!m_InStream.ReadByte(b1))
      return S_FALSE;

    UInt32 len, distance;

    if (b & 0x40)
    {
      len = ((UInt32)b & 0x3F) + 4;
      Byte b2;
      if (!m_InStream.ReadByte(b2))
        return S_FALSE;
      distance = ((UInt32)b1 << 8) + b2;
    }
    else
    {
      b &= 0x3F;
      len = ((UInt32)b >> 2) + 3;
      distance = (((UInt32)b & 3) << 8) + b1;
    }

    if (distance >= pos || len > rem)
      return S_FALSE;
    m_OutWindowStream.CopyBlock(distance, len);
    pos += len;
  }
  if (*inSize != m_InStream.GetProcessedSize())
    return S_FALSE;
  coderReleaser.NeedFlush = false;
  return m_OutWindowStream.Flush();
}

STDMETHODIMP CAdcDecoder::Code(ISequentialInStream *inStream,
    ISequentialOutStream *outStream, const UInt64 *inSize, const UInt64 *outSize,
    ICompressProgressInfo *progress)
{
  try { return CodeReal(inStream, outStream, inSize, outSize, progress);}
  catch(const CInBufferException &e) { return e.ErrorCode; }
  catch(const CLzOutWindowException &e) { return e.ErrorCode; }
  catch(...) { return S_FALSE; }
}







STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
    Int32 testMode, IArchiveExtractCallback *extractCallback)
{
  COM_TRY_BEGIN
  bool allFilesMode = (numItems == (UInt32)(Int32)-1);
  if (allFilesMode)
    numItems = _files.Size();
  if (numItems == 0)
    return S_OK;
  UInt64 totalSize = 0;
  UInt32 i;
  
  for (i = 0; i < numItems; i++)
  {
    UInt32 index = (allFilesMode ? i : indices[i]);
    #ifdef DMG_SHOW_RAW
    if (index >= _files.Size())
      totalSize += _extras[index - _files.Size()].Data.Size();
    else
    #endif
      totalSize += _files[index].Size;
  }
  extractCallback->SetTotal(totalSize);

  UInt64 currentPackTotal = 0;
  UInt64 currentUnpTotal = 0;
  UInt64 currentPackSize = 0;
  UInt64 currentUnpSize = 0;

  const UInt32 kZeroBufSize = (1 << 14);
  CByteBuffer zeroBuf(kZeroBufSize);
  memset(zeroBuf, 0, kZeroBufSize);
  
  NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder();
  CMyComPtr<ICompressCoder> copyCoder = copyCoderSpec;

  NCompress::NBZip2::CDecoder *bzip2CoderSpec = new NCompress::NBZip2::CDecoder();
  CMyComPtr<ICompressCoder> bzip2Coder = bzip2CoderSpec;

  NCompress::NZlib::CDecoder *zlibCoderSpec = new NCompress::NZlib::CDecoder();
  CMyComPtr<ICompressCoder> zlibCoder = zlibCoderSpec;

  CAdcDecoder *adcCoderSpec = new CAdcDecoder();
  CMyComPtr<ICompressCoder> adcCoder = adcCoderSpec;

  NCompress::NLzfse::CDecoder *lzfseCoderSpec = new NCompress::NLzfse::CDecoder();
  CMyComPtr<ICompressCoder> lzfseCoder = lzfseCoderSpec;

  CLocalProgress *lps = new CLocalProgress;
  CMyComPtr<ICompressProgressInfo> progress = lps;
  lps->Init(extractCallback, false);

  CLimitedSequentialInStream *streamSpec = new CLimitedSequentialInStream;
  CMyComPtr<ISequentialInStream> inStream(streamSpec);
  streamSpec->SetStream(_inStream);

  for (i = 0; i < numItems; i++, currentPackTotal += currentPackSize, currentUnpTotal += currentUnpSize)
  {
    lps->InSize = currentPackTotal;
    lps->OutSize = currentUnpTotal;
    currentPackSize = 0;
    currentUnpSize = 0;
    RINOK(lps->SetCur());
    CMyComPtr<ISequentialOutStream> realOutStream;
    Int32 askMode = testMode ?
        NExtract::NAskMode::kTest :
        NExtract::NAskMode::kExtract;
    UInt32 index = allFilesMode ? i : indices[i];
    RINOK(extractCallback->GetStream(index, &realOutStream, askMode));

    if (!testMode && !realOutStream)
      continue;
    RINOK(extractCallback->PrepareOperation(askMode));


    COutStreamWithCRC *outCrcStreamSpec = new COutStreamWithCRC;
    CMyComPtr<ISequentialOutStream> outCrcStream = outCrcStreamSpec;
    outCrcStreamSpec->SetStream(realOutStream);
    bool needCrc = false;
    outCrcStreamSpec->Init(needCrc);

    CLimitedSequentialOutStream *outStreamSpec = new CLimitedSequentialOutStream;
    CMyComPtr<ISequentialOutStream> outStream(outStreamSpec);
    outStreamSpec->SetStream(outCrcStream);
    
    realOutStream.Release();

    Int32 opRes = NExtract::NOperationResult::kOK;
    #ifdef DMG_SHOW_RAW
    if (index >= _files.Size())
    {
      const CByteBuffer &buf = _extras[index - _files.Size()].Data;
      outStreamSpec->Init(buf.Size());
      RINOK(WriteStream(outStream, buf, buf.Size()));
      currentPackSize = currentUnpSize = buf.Size();
    }
    else
    #endif
    {
      const CFile &item = _files[index];
      currentPackSize = item.PackSize;
      currentUnpSize = item.Size;

      needCrc = item.Checksum.IsCrc32();

      UInt64 unpPos = 0;
      UInt64 packPos = 0;
      {
        FOR_VECTOR (j, item.Blocks)
        {
          lps->InSize = currentPackTotal + packPos;
          lps->OutSize = currentUnpTotal + unpPos;
          RINOK(lps->SetCur());

          const CBlock &block = item.Blocks[j];
          if (!block.ThereAreDataInBlock())
            continue;

          packPos += block.PackSize;
          if (block.UnpPos != unpPos)
          {
            opRes = NExtract::NOperationResult::kDataError;
            break;
          }

          RINOK(_inStream->Seek(_startPos + item.StartPos + block.PackPos, STREAM_SEEK_SET, NULL));
          streamSpec->Init(block.PackSize);
          bool realMethod = true;
          outStreamSpec->Init(block.UnpSize);
          HRESULT res = S_OK;

          outCrcStreamSpec->EnableCalc(needCrc);

          switch (block.Type)
          {
            case METHOD_ZERO_0:
            case METHOD_ZERO_2:
              realMethod = false;
              if (block.PackSize != 0)
                opRes = NExtract::NOperationResult::kUnsupportedMethod;
              outCrcStreamSpec->EnableCalc(block.Type == METHOD_ZERO_0);
              break;

            case METHOD_COPY:
              if (block.UnpSize != block.PackSize)
              {
                opRes = NExtract::NOperationResult::kUnsupportedMethod;
                break;
              }
              res = copyCoder->Code(inStream, outStream, NULL, NULL, progress);
              break;
            
            case METHOD_ADC:
            {
              res = adcCoder->Code(inStream, outStream, &block.PackSize, &block.UnpSize, progress);
              break;
            }
            
            case METHOD_ZLIB:
            {
              res = zlibCoder->Code(inStream, outStream, NULL, NULL, progress);
              if (res == S_OK)
                if (zlibCoderSpec->GetInputProcessedSize() != block.PackSize)
                  opRes = NExtract::NOperationResult::kDataError;
              break;
            }

            case METHOD_BZIP2:
            {
              res = bzip2Coder->Code(inStream, outStream, NULL, NULL, progress);
              if (res == S_OK)
                if (bzip2CoderSpec->GetInputProcessedSize() != block.PackSize)
                  opRes = NExtract::NOperationResult::kDataError;
              break;
            }

            case METHOD_LZFSE:
            {
              res = lzfseCoder->Code(inStream, outStream, &block.PackSize, &block.UnpSize, progress);
              break;
            }
            
            default:
              opRes = NExtract::NOperationResult::kUnsupportedMethod;
              break;
          }

          if (res != S_OK)
          {
            if (res != S_FALSE)
              return res;
            if (opRes == NExtract::NOperationResult::kOK)
              opRes = NExtract::NOperationResult::kDataError;
          }
          
          unpPos += block.UnpSize;
          
          if (!outStreamSpec->IsFinishedOK())
          {
            if (realMethod && opRes == NExtract::NOperationResult::kOK)
              opRes = NExtract::NOperationResult::kDataError;

            while (outStreamSpec->GetRem() != 0)
            {
              UInt64 rem = outStreamSpec->GetRem();
              UInt32 size = (UInt32)MyMin(rem, (UInt64)kZeroBufSize);
              RINOK(WriteStream(outStream, zeroBuf, size));
            }
          }
        }
      }
  
      if (needCrc && opRes == NExtract::NOperationResult::kOK)
      {
        if (outCrcStreamSpec->GetCRC() != item.Checksum.GetCrc32())
          opRes = NExtract::NOperationResult::kCRCError;
      }
    }
    outStream.Release();
    RINOK(extractCallback->SetOperationResult(opRes));
  }

  return S_OK;
  COM_TRY_END
}

struct CChunk
{
  int BlockIndex;
  UInt64 AccessMark;
  CByteBuffer Buf;
};

class CInStream:
  public IInStream,
  public CMyUnknownImp
{
  UInt64 _virtPos;
  int _latestChunk;
  int _latestBlock;
  UInt64 _accessMark;
  CObjectVector<CChunk> _chunks;

  NCompress::NBZip2::CDecoder *bzip2CoderSpec;
  CMyComPtr<ICompressCoder> bzip2Coder;

  NCompress::NZlib::CDecoder *zlibCoderSpec;
  CMyComPtr<ICompressCoder> zlibCoder;

  CAdcDecoder *adcCoderSpec;
  CMyComPtr<ICompressCoder> adcCoder;

  NCompress::NLzfse::CDecoder *lzfseCoderSpec;
  CMyComPtr<ICompressCoder> lzfseCoder;

  CBufPtrSeqOutStream *outStreamSpec;
  CMyComPtr<ISequentialOutStream> outStream;

  CLimitedSequentialInStream *limitedStreamSpec;
  CMyComPtr<ISequentialInStream> inStream;

public:
  CMyComPtr<IInStream> Stream;
  UInt64 Size;
  const CFile *File;
  UInt64 _startPos;

  HRESULT InitAndSeek(UInt64 startPos)
  {
    _startPos = startPos;
    _virtPos = 0;
    _latestChunk = -1;
    _latestBlock = -1;
    _accessMark = 0;

    limitedStreamSpec = new CLimitedSequentialInStream;
    inStream = limitedStreamSpec;
    limitedStreamSpec->SetStream(Stream);

    outStreamSpec = new CBufPtrSeqOutStream;
    outStream = outStreamSpec;
    return S_OK;
  }

  MY_UNKNOWN_IMP1(IInStream)

  STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
  STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition);
};


unsigned FindBlock(const CRecordVector<CBlock> &blocks, UInt64 pos)
{
  unsigned left = 0, right = blocks.Size();
  for (;;)
  {
    unsigned mid = (left + right) / 2;
    if (mid == left)
      return left;
    if (pos < blocks[mid].UnpPos)
      right = mid;
    else
      left = mid;
  }
}

STDMETHODIMP CInStream::Read(void *data, UInt32 size, UInt32 *processedSize)
{
  COM_TRY_BEGIN

  if (processedSize)
    *processedSize = 0;
  if (size == 0)
    return S_OK;
  if (_virtPos >= Size)
    return S_OK; // (Size == _virtPos) ? S_OK: E_FAIL;
  {
    UInt64 rem = Size - _virtPos;
    if (size > rem)
      size = (UInt32)rem;
  }

  if (_latestBlock >= 0)
  {
    const CBlock &block = File->Blocks[_latestBlock];
    if (_virtPos < block.UnpPos || (_virtPos - block.UnpPos) >= block.UnpSize)
      _latestBlock = -1;
  }
  
  if (_latestBlock < 0)
  {
    _latestChunk = -1;
    unsigned blockIndex = FindBlock(File->Blocks, _virtPos);
    const CBlock &block = File->Blocks[blockIndex];
    
    if (!block.IsZeroMethod() && block.Type != METHOD_COPY)
    {
      unsigned i;
      for (i = 0; i < _chunks.Size(); i++)
        if (_chunks[i].BlockIndex == (int)blockIndex)
          break;
      
      if (i != _chunks.Size())
        _latestChunk = i;
      else
      {
        const unsigned kNumChunksMax = 128;
        unsigned chunkIndex;
      
        if (_chunks.Size() != kNumChunksMax)
          chunkIndex = _chunks.Add(CChunk());
        else
        {
          chunkIndex = 0;
          for (i = 0; i < _chunks.Size(); i++)
            if (_chunks[i].AccessMark < _chunks[chunkIndex].AccessMark)
              chunkIndex = i;
        }
        
        CChunk &chunk = _chunks[chunkIndex];
        chunk.BlockIndex = -1;
        chunk.AccessMark = 0;
        
        if (chunk.Buf.Size() < block.UnpSize)
        {
          chunk.Buf.Free();
          if (block.UnpSize > ((UInt32)1 << 31))
            return E_FAIL;
          chunk.Buf.Alloc((size_t)block.UnpSize);
        }
        
        outStreamSpec->Init(chunk.Buf, (size_t)block.UnpSize);
          
        RINOK(Stream->Seek(_startPos + File->StartPos + block.PackPos, STREAM_SEEK_SET, NULL));

        limitedStreamSpec->Init(block.PackSize);
        HRESULT res = S_OK;
        
        switch (block.Type)
        {
          case METHOD_COPY:
            if (block.PackSize != block.UnpSize)
              return E_FAIL;
            res = ReadStream_FAIL(inStream, chunk.Buf, (size_t)block.UnpSize);
            break;
            
          case METHOD_ADC:
            if (!adcCoder)
            {
              adcCoderSpec = new CAdcDecoder();
              adcCoder = adcCoderSpec;
            }
            res = adcCoder->Code(inStream, outStream, &block.PackSize, &block.UnpSize, NULL);
            break;
            
          case METHOD_ZLIB:
            if (!zlibCoder)
            {
              zlibCoderSpec = new NCompress::NZlib::CDecoder();
              zlibCoder = zlibCoderSpec;
            }
            res = zlibCoder->Code(inStream, outStream, NULL, NULL, NULL);
            if (res == S_OK && zlibCoderSpec->GetInputProcessedSize() != block.PackSize)
              res = S_FALSE;
            break;
            
          case METHOD_BZIP2:
            if (!bzip2Coder)
            {
              bzip2CoderSpec = new NCompress::NBZip2::CDecoder();
              bzip2Coder = bzip2CoderSpec;
            }
            res = bzip2Coder->Code(inStream, outStream, NULL, NULL, NULL);
            if (res == S_OK && bzip2CoderSpec->GetInputProcessedSize() != block.PackSize)
              res = S_FALSE;
            break;

          case METHOD_LZFSE:
            if (!lzfseCoder)
            {
              lzfseCoderSpec = new NCompress::NLzfse::CDecoder();
              lzfseCoder = lzfseCoderSpec;
            }
            res = lzfseCoder->Code(inStream, outStream, &block.PackSize, &block.UnpSize, NULL);
            break;
            
          default:
            return E_FAIL;
        }
        
        if (res != S_OK)
          return res;
        if (block.Type != METHOD_COPY && outStreamSpec->GetPos() != block.UnpSize)
          return E_FAIL;
        chunk.BlockIndex = blockIndex;
        _latestChunk = chunkIndex;
      }
      
      _chunks[_latestChunk].AccessMark = _accessMark++;
    }
  
    _latestBlock = blockIndex;
  }

  const CBlock &block = File->Blocks[_latestBlock];
  UInt64 offset = _virtPos - block.UnpPos;
  UInt64 rem = block.UnpSize - offset;
  if (size > rem)
    size = (UInt32)rem;
  
  HRESULT res = S_OK;
  
  if (block.Type == METHOD_COPY)
  {
    RINOK(Stream->Seek(_startPos + File->StartPos + block.PackPos + offset, STREAM_SEEK_SET, NULL));
    res = Stream->Read(data, size, &size);
  }
  else if (block.IsZeroMethod())
    memset(data, 0, size);
  else if (size != 0)
    memcpy(data, _chunks[_latestChunk].Buf + offset, size);
  
  _virtPos += size;
  if (processedSize)
    *processedSize = size;
  
  return res;
  COM_TRY_END
}
 
STDMETHODIMP CInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition)
{
  switch (seekOrigin)
  {
    case STREAM_SEEK_SET: break;
    case STREAM_SEEK_CUR: offset += _virtPos; break;
    case STREAM_SEEK_END: offset += Size; break;
    default: return STG_E_INVALIDFUNCTION;
  }
  if (offset < 0)
    return HRESULT_WIN32_ERROR_NEGATIVE_SEEK;
  _virtPos = offset;
  if (newPosition)
    *newPosition = offset;
  return S_OK;
}

STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream)
{
  COM_TRY_BEGIN
  
  #ifdef DMG_SHOW_RAW
  if (index >= (UInt32)_files.Size())
    return S_FALSE;
  #endif
  
  CInStream *spec = new CInStream;
  CMyComPtr<ISequentialInStream> specStream = spec;
  spec->File = &_files[index];
  const CFile &file = *spec->File;
  
  FOR_VECTOR (i, file.Blocks)
  {
    const CBlock &block = file.Blocks[i];
    switch (block.Type)
    {
      case METHOD_ZERO_0:
      case METHOD_ZERO_2:
      case METHOD_COPY:
      case METHOD_ADC:
      case METHOD_ZLIB:
      case METHOD_BZIP2:
      case METHOD_LZFSE:
      case METHOD_END:
        break;
      default:
        return S_FALSE;
    }
  }
  
  spec->Stream = _inStream;
  spec->Size = spec->File->Size;
  RINOK(spec->InitAndSeek(_startPos));
  *stream = specStream.Detach();
  return S_OK;
  
  COM_TRY_END
}

REGISTER_ARC_I(
  "Dmg", "dmg", 0, 0xE4,
  k_Signature,
  0,
  NArcInfoFlags::kBackwardOpen |
  NArcInfoFlags::kUseGlobalOffset,
  NULL)

}}