-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathuvirtuallayer_ole_helpers.pas
1348 lines (1258 loc) · 41.8 KB
/
uvirtuallayer_ole_helpers.pas
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
{
uvirtuallayer_ole_helpers.pas
Part of "uvirtuallayer_ole".
Supports most of the logic of Indirect FAT and Double Indirect FAT accesses for
OLE files.
Presented as an unit to hide the class and definitions when using OLE virtual
layer. This class is not intented to general use, only by TVirtualLayer_OLE.
AUTHORS: José Mejuto Porral
}
unit uvirtuallayer_ole_helpers;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, uvirtuallayer_ole_types;
type
TFATCacheItem=record
Sector: SECT;
Cache: PSECT;
Dirty: Boolean;
end;
TFATStreamContext=record
FATFirstIndex: SizeUint;
FATIndex: SizeUint;
Position: int64;
Size: int64;
Dirty: Boolean;
AccessMode: WORD;
MiniStream: TMemoryStream;
end;
TWCBFOpenStream=record
Handle: SID;
Context: TFATStreamContext;
end;
{ TMaskFile }
TMaskFile=class
private
protected
FMask: UTF8String;
public
function Matches(const AFileName: UTF8String): Boolean;
Constructor Create(const AMask: UTF8String);
end;
{ TFATIndirect }
TFATIndirect=class
private
procedure InitializeMiniDataStream();
protected
FDirtyMedia: Boolean;
FFATCache: TFATCacheItem;
FMiscSectorBuffer: PBYTE;
FStream: TStream;
FHeader: TWCBFStructuredStorageHeader;
FSectorSize: SizeUint;
FEntriesShort: SizeUint;
FDIFArray: array of PSECT;
FFATEntriesPerSect: SizeUint;
FNeedEndianChange: Boolean;
FHeaderLength: SizeUint;
procedure FlushCaches();
function iLEToN(const AValue: DWORD): DWORD;
function iNToLE(const AValue: DWORD): DWORD;
procedure iDIFFATLEToN(var ADIF: PSECT);
procedure iDIFFATNToLE(var ADIF: PSECT);
procedure iHeaderLEToN(var AHeader: TWCBFStructuredStorageHeader);
procedure iHeaderNToLE(var AHeader: TWCBFStructuredStorageHeader);
function ComposeFATEntry(const ADIF,AFATInDIF,AOffSetInFAT: SECT): SECT; inline;
procedure DecomposeFATEntry(const AFATEntry: SECT; out DIF,FATInDIF,OffsetInFAT: SECT); inline;
function WriteToMiniFAT(var AContext: TFATStreamContext; const AStream: TStream): DWORD;
function ReadFromMiniFAT(const AContext: TFATStreamContext; const AStream: TStream): DWORD;
procedure ReadSector(const ASector: SECT; const ABuffer: Pointer); inline;
procedure WriteSector(const ASector: SECT; const ABuffer: Pointer); inline;
procedure ReadFATSector(const ASector: SECT);
procedure WriteFATSector(const ASector: SECT;const ABuffer: PSECT); overload;
procedure WriteFATSector(const ASector: SECT); overload;
function IsReservedValue(const ASectorValue: SECT): Boolean;inline;
function LoadDIFArray(): Boolean;
function UnloadDIFArray(): Boolean;
function SectorAbsolute(const ASector: SECT): int64; inline;
function FindFreeFAT(const ABuffer: PSECT; const AStartIndex: SizeUint): SizeUint;
function AllocateNewSector(const AStartingFATIndex: SECT; const ALinkFrom: SECT;const ALinkTo: SECT=SECT_ENDOFCHAIN): SizeUInt;
function GetStreamSizeInSectors(const AContext: TFATStreamContext): int64;
function GetFATOffsetForPosition(const APosition: int64): SizeUint; inline;
function GetFATRemainForPosition(const APosition: int64): SizeUint; inline;
function ReadFATEntryValue(const AFATEntryIndex: SizeUint): SECT; inline;
procedure WriteFATEntryValue(const AFATEntryIndex: SizeUint;const ALinkTo: SECT); inline;
procedure ResynchronizePosition(var AContext: TFATStreamContext);
procedure ResynchronizePositionWithAllocation(var AContext: TFATStreamContext);
function FollowFATLinkage(const AStartFATEntryIndex: SizeUint; const ABytes: int64): SECT;
procedure Format(var AHeader: TWCBFStructuredStorageHeader); virtual;
public
DirectoryContext: TFATStreamContext;
MiniFATContext: TFATStreamContext;
MiniFATDataContext: TFATStreamContext;
property DirtyMedia: Boolean read FDirtyMedia write FDirtyMedia;
property HeaderLength: SizeUint read FHeaderLength;
function OpenStream(const AFirstFATSector: DWORD; const ASize: int64; const AAccessMode: WORD): TFATStreamContext;
procedure CloseStream(var AContext: TFATStreamContext);
function ReadData(var AContext: TFATStreamContext; const ABuffer: PBYTE; const ASize: SizeInt): SizeInt;
function WriteData(var AContext: TFATStreamContext; const ABuffer: PBYTE; const ASize: SizeInt): SizeInt;
function StreamSeekPosition(var AContext: TFATStreamContext; const AOffset: int64; const AOrigin: TSeekOrigin): int64;
procedure ResetMiniFATLinkage(const AStartFATEntryIndex: SizeUint; const ANewFATValue: SECT);
procedure ResetFATLinkage(const AStartFATEntryIndex: SizeUint; const ANewFATValue: SECT);
function IsSizeInMiniFAT(const ASize: int64): Boolean;
function Initialize(const ACreate: Boolean=false): Boolean;
Constructor Create(const AOLEStream: TStream);
Destructor Destroy; override;
end;
implementation
function MatchesMask(What, Mask: string): boolean; forward;
procedure TFATIndirect.InitializeMiniDataStream();
var
RootDir: TWCBFStructuredStorageDirectoryEntry;
begin
//Read the SID 0, RootEntry, or R or whichever name it uses.
RootDir._cb:=0;
FillByte(RootDir,sizeof(RootDir),0);
StreamSeekPosition(DirectoryContext,0,soBeginning);
ReadData(DirectoryContext,@RootDir,SizeOf(RootDir));
StreamSeekPosition(DirectoryContext,0,soBeginning);
MiniFATDataContext.FATFirstIndex:=RootDir._sectStart;
MiniFATDataContext.FATIndex:=RootDir._sectStart;
MiniFATDataContext.Size:=RootDir._ulSize;
MiniFATDataContext.MiniStream:=nil;
end;
procedure TFATIndirect.FlushCaches();
begin
if FFATCache.Dirty then begin
WriteSector(FFATCache.Sector,FFATCache.Cache);
FFATCache.Dirty:=false;
end;
end;
function TFATIndirect.iLEToN(const AValue: DWORD): DWORD;
begin
if FNeedEndianChange then begin
Result:=LEToN(AValue);
end else begin
Result:=AValue;
end;
end;
function TFATIndirect.iNToLE(const AValue: DWORD): DWORD;
begin
if FNeedEndianChange then begin
Result:=NToLE(AValue);
end else begin
Result:=AValue;
end;
end;
procedure TFATIndirect.iDIFFATLEToN(var ADIF: PSECT);
var
j: SizeUint;
begin
if not FNeedEndianChange then Exit;
for j := 0 to FFATEntriesPerSect-1 do begin
ADIF[j]:=LEToN(ADIF[j]);
end;
end;
procedure TFATIndirect.iDIFFATNToLE(var ADIF: PSECT);
var
j: SizeUint;
begin
if not FNeedEndianChange then Exit;
for j := 0 to FFATEntriesPerSect-1 do begin
ADIF[j]:=NToLE(ADIF[j]);
end;
end;
procedure TFATIndirect.iHeaderLEToN(var AHeader: TWCBFStructuredStorageHeader);
var
j: SizeUint;
begin
if Not FNeedEndianChange then exit;
AHeader._uMinorVersion:=iLEToN(FHeader._uMinorVersion);
AHeader._uDllVersion:=iLEToN(FHeader._uDllVersion);
AHeader._uSectorShift:=iLEToN(FHeader._uSectorShift);
AHeader._uMiniSectorShift:=iLEToN(FHeader._uMiniSectorShift);
AHeader._csectFat:=iLEToN(FHeader._csectFat);
AHeader._sectDirStart:=iLEToN(FHeader._sectDirStart);
AHeader._ulMiniSectorCutoff:=iLEToN(FHeader._ulMiniSectorCutoff);
AHeader._sectMiniFatStart:=iLEToN(FHeader._sectMiniFatStart);
AHeader._csectMiniFat:=iLEToN(FHeader._csectMiniFat);
AHeader._sectDifStart:=iLEToN(FHeader._sectDifStart);
AHeader._csectDif:=iLEToN(FHeader._csectDif);
for j := Low(AHeader._sectFat) to High(AHeader._sectFat) do begin
AHeader._sectFat[j]:=iLEToN(AHeader._sectFat[j]);
end;
end;
procedure TFATIndirect.iHeaderNToLE(var AHeader: TWCBFStructuredStorageHeader);
var
j: SizeUint;
begin
if Not FNeedEndianChange then exit;
AHeader._uMinorVersion:=iNToLE(FHeader._uMinorVersion);
AHeader._uDllVersion:=iNToLE(FHeader._uDllVersion);
AHeader._uSectorShift:=iNToLE(FHeader._uSectorShift);
AHeader._uMiniSectorShift:=iNToLE(FHeader._uMiniSectorShift);
AHeader._csectFat:=iNToLE(FHeader._csectFat);
AHeader._sectDirStart:=iNToLE(FHeader._sectDirStart);
AHeader._ulMiniSectorCutoff:=iNToLE(FHeader._ulMiniSectorCutoff);
AHeader._sectMiniFatStart:=iNToLE(FHeader._sectMiniFatStart);
AHeader._csectMiniFat:=iNToLE(FHeader._csectMiniFat);
AHeader._sectDifStart:=iNToLE(FHeader._sectDifStart);
AHeader._csectDif:=iNToLE(FHeader._csectDif);
for j := Low(AHeader._sectFat) to High(AHeader._sectFat) do begin
AHeader._sectFat[j]:=iNToLE(AHeader._sectFat[j]);
end;
end;
function TFATIndirect.ComposeFATEntry(const ADIF, AFATInDIF, AOffSetInFAT: SECT
): SECT;
begin
if ADIF=0 then begin
Result:=AFATInDIF*FFATEntriesPerSect+AOffSetInFAT;
end else begin
Result:=FEntriesShort+
int64((ADIF-1))*((FFATEntriesPerSect-1)*FFATEntriesPerSect)+
int64(AFATInDIF)*FFATEntriesPerSect+
AOffSetInFAT;
end;
end;
procedure TFATIndirect.DecomposeFATEntry(const AFATEntry: SECT; out DIF,
FATInDIF, OffsetInFAT: SECT);
var
TmpEntry: SECT;
begin
if AFATEntry<FEntriesShort then begin
DIF:=0;
FATInDIF:=AFATEntry div FFATEntriesPerSect;
OffsetInFAT:=AFATEntry mod FFATEntriesPerSect;
end else begin
TmpEntry:=AFATEntry-FEntriesShort;
DIF:=TmpEntry div ((FFATEntriesPerSect-1)*FFATEntriesPerSect);
TmpEntry:=TmpEntry-DIF*((FFATEntriesPerSect-1)*FFATEntriesPerSect);
FATInDIF:=TmpEntry div FFATEntriesPerSect;
OffsetInFAT:=TmpEntry mod FFATEntriesPerSect;
DIF:=DIF+1; //+1 the removed by substract FEntriesShort
end;
end;
procedure TFATIndirect.ResetMiniFATLinkage(const AStartFATEntryIndex: SizeUint;
const ANewFATValue: SECT);
var
NextFAT: SECT;
MiniFATBuffer: PSECT;
Index,IndexLimit: SECT;
begin
MiniFATBuffer:=nil;
GetMem(MiniFATBuffer,MiniFATContext.Size);
MiniFATContext.Position:=0;
ReadData(MiniFATContext,PBYTE(MiniFATBuffer),MiniFATContext.Size);
Index:=0;
IndexLimit:=MiniFATContext.Size div BYTES_PER_FAT_ENTRY;
NextFAT:=AStartFATEntryIndex;
while not IsReservedValue(NextFAT) do begin
Index:=MiniFATBuffer[NextFAT];
if Index>=IndexLimit Then begin
Raise Exception.Create('MiniFAT internal structure damaged');
end;
MiniFATBuffer[NextFAT]:=ANewFATValue;
NextFAT:=Index;
end;
StreamSeekPosition(MiniFATContext,0,soBeginning);
WriteData(MiniFATContext,PBYTE(MiniFATBuffer),IndexLimit*BYTES_PER_FAT_ENTRY);
Freemem(MiniFATBuffer);
end;
function TFATIndirect.WriteToMiniFAT(var AContext: TFATStreamContext;
const AStream: TStream): DWORD;
var
MiniSectorSize: DWORD;
MiniEntries: DWORD;
FATArray: array of SECT;
k: SizeUint;
OldPos: int64;
function FindFreeMiniFATArray(const AEntries: DWORD): SECT;
var
Pending: DWORD;
MiniFATBuffer: PSECT;
Index,IndexLimit: SECT;
FATEntries: SizeUint;
j: integer;
begin
Pending:=AEntries;
SetLength(FATArray,0);
MiniFATBuffer:=nil;
GetMem(MiniFATBuffer,MiniFATContext.Size);
MiniFATContext.Position:=0;
ReadData(MiniFATContext,PBYTE(MiniFATBuffer),MiniFATContext.Size);
FATEntries:=0;
Index:=0;
IndexLimit:=MiniFATContext.Size div BYTES_PER_FAT_ENTRY;
while Pending>0 do begin
while (Pending>0) and (Index<IndexLimit) do begin
if MiniFATBuffer[Index]=SECT_FREESECT then begin
SetLength(FATArray,FATEntries+1);
FATArray[FATEntries]:=Index;
if Index>=FHeader._csectMiniFat then begin
FHeader._csectMiniFat:=Index+1;
end;
inc(FATEntries);
dec(Pending);
end;
Inc(Index);
end;
if (Pending>0) then begin
//Allocate a new FAT sector...
MiniFATBuffer:=ReAllocMem(MiniFATBuffer,(IndexLimit+FFATEntriesPerSect)*BYTES_PER_FAT_ENTRY);
IndexLimit:=IndexLimit+FFATEntriesPerSect;
for j := Index to IndexLimit-1 do begin
MiniFATBuffer[j]:=SECT_FREESECT;
end;
end;
end;
//Link the sectors....
for j := 0 to High(FATArray)-1 do begin
MiniFATBuffer[FATArray[j]]:=FATArray[j+1];
end;
//And mark the end
MiniFATBuffer[FATArray[High(FATArray)]]:=SECT_ENDOFCHAIN;
StreamSeekPosition(MiniFATContext,0,soBeginning);
WriteData(MiniFATContext,PBYTE(MiniFATBuffer),IndexLimit*BYTES_PER_FAT_ENTRY);
Freemem(MiniFATBuffer);
Result:=FATArray[0];
end;
begin
if AStream.Size=0 then begin
Result:=0;
Exit;
end;
MiniSectorSize:= 1 shl FHeader._uMiniSectorShift;
OldPos:=AStream.Position;
AStream.Position:=0;
MiniEntries:=AContext.Size div MiniSectorSize;
if AContext.Size mod MiniSectorSize>0 then begin
inc(MiniEntries);
end;
FindFreeMiniFATArray(MiniEntries);
for k := 0 to MiniEntries-1 do begin
StreamSeekPosition(MiniFATDataContext,int64(FATArray[k])*MiniSectorSize,soBeginning);
AStream.Read(FMiscSectorBuffer^,MiniSectorSize);
WriteData(MiniFATDataContext,FMiscSectorBuffer,MiniSectorSize);
end;
AContext.FATFirstIndex:=FATArray[0];
AContext.FATIndex:=SECT_FREESECT;
AStream.Position:=OldPos;
end;
function TFATIndirect.ReadFromMiniFAT(const AContext: TFATStreamContext;
const AStream: TStream): DWORD;
var
NextSector: SECT;
MiniSectorSize: DWORD;
ReadBytes,ThisRead: SizeUInt;
EffectiveRead: SizeUint;
begin
If AContext.Size=0 then begin
Result:=0;
Exit;
end;
MiniSectorSize:= 1 shl FHeader._uMiniSectorShift;
AStream.Position:=0;
AStream.Size:=0;
ReadBytes:=AContext.Size;
NextSector:=AContext.FATFirstIndex;
while not IsReservedValue(NextSector) and (ReadBytes>0) do begin
StreamSeekPosition(MiniFATDataContext,Int64(NextSector)*MiniSectorSize,soBeginning);
if ReadBytes>MiniSectorSize then begin
ThisRead:=MiniSectorSize;
end else begin
ThisRead:=ReadBytes;
end;
EffectiveRead:=ReadData(MiniFATDataContext,FMiscSectorBuffer,ThisRead);
AStream.Write(FMiscSectorBuffer^,EffectiveRead);
StreamSeekPosition(MiniFATContext,int64(NextSector)*BYTES_PER_FAT_ENTRY,soBeginning);
ReadData(MiniFATContext,@NextSector,BYTES_PER_FAT_ENTRY);
Dec(ReadBytes,EffectiveRead);
if ThisRead<>EffectiveRead then exit;
end;
AStream.Size:=AContext.Size-ReadBytes;
Result:=AStream.Size;
end;
procedure TFATIndirect.ReadSector(const ASector: SECT; const ABuffer: Pointer);
begin
FStream.Position:=int64(ASector) * FSectorSize + FHeaderLength;
FStream.ReadBuffer(PBYTE(ABuffer)^,FSectorSize);
end;
procedure TFATIndirect.WriteSector(const ASector: SECT; const ABuffer: Pointer);
begin
FStream.Position:=int64(ASector) * FSectorSize + FHeaderLength;
FStream.WriteBuffer(PBYTE(ABuffer)^,FSectorSize);
FDirtyMedia:=true;
end;
procedure TFATIndirect.ReadFATSector(const ASector: SECT);
begin
if ASector=FFATCache.Sector then exit;
if (FFATCache.Dirty) Then begin
//Write the dirty cached FAT sector
iDIFFATNToLE(FFATCache.Cache);
WriteSector(FFATCache.Sector,FFATCache.Cache);
end;
FFATCache.Sector:=ASector;
FFATCache.Dirty:=false;
ReadSector(ASector,FFATCache.Cache);
iDIFFATLEToN(FFATCache.Cache);
end;
procedure TFATIndirect.WriteFATSector(const ASector: SECT; const ABuffer: PSECT
);
begin
if ASector<>FFATCache.Sector then begin
if FFATCache.Dirty then begin
//Write the dirty cached FAT sector
if FHeader._csectFat<(FFATCache.Sector div FFATEntriesPerSect)+1 then begin
FHeader._csectFat:=(FFATCache.Sector div FFATEntriesPerSect)+1;
end;
iDIFFATNToLE(FFATCache.Cache);
WriteSector(FFATCache.Sector,FFATCache.Cache);
end;
end;
move(PBYTE(ABuffer)^,PBYTE(FFATCache.Cache)^,FSectorSize);
FFATCache.Sector:=ASector;
FFATCache.Dirty:=true;
end;
procedure TFATIndirect.WriteFATSector(const ASector: SECT);
begin
if ASector=FFATCache.Sector then begin
FFATCache.Dirty:=true;
end else begin
if FHeader._csectFat<(FFATCache.Sector div FFATEntriesPerSect)+1 then begin
FHeader._csectFat:=(FFATCache.Sector div FFATEntriesPerSect)+1;
end;
iDIFFATNToLE(FFATCache.Cache);
//Writes the data
WriteSector(FFATCache.Sector,FFATCache.Cache);
FFATCache.Dirty:=false;
end;
end;
function TFATIndirect.IsReservedValue(const ASectorValue: SECT): Boolean;
inline;
begin
if ASectorValue>=$FFFFFFF0 then
Result:=true
else
Result:=false;
end;
function TFATIndirect.LoadDIFArray(): Boolean;
var
NextDIF: SECT;
Index: SizeUint;
begin
SetLength(FDIFArray,1);
//The first DIF is an special one...
FDIFArray[0]:=PSECT(@FHeader._sectFat[0]);
NextDIF:=FHeader._sectDifStart;
Index:=0;
while not IsReservedValue(NextDIF) do begin
Inc(Index);
SetLength(FDIFArray,Index+1);
GetMem(FDIFArray[Index],FSectorSize);
ReadSector(NextDIF,FDIFArray[Index]);
iDIFFATLEToN(FDIFArray[Index]);
NextDIF:=FDIFArray[Index][FFATEntriesPerSect-1];
end;
Result:=true;
end;
function TFATIndirect.UnloadDIFArray(): Boolean;
var
NextDIF: SECT;
NextDIFC: SECT;
Index: SizeUint;
begin
if Length(FDIFArray)=0 then begin
//Nothing to be freed.
Result:=true;
exit;
end;
//The first DIF is an special one and do not need to be
//written as it is written with the header updates.
FDIFArray[0]:=PSECT(@FHeader._sectFat[0]);
//It is in memory in machine endian format.
NextDIF:=FHeader._sectDifStart;
Index:=0;
while not IsReservedValue(NextDIF) do begin
Inc(Index);
NextDIFC:=FDIFArray[Index][FFATEntriesPerSect-1];
if FDirtyMedia then begin
iDIFFATNToLE(FDIFArray[Index]);
WriteSector(NextDIF,FDIFArray[Index]);
end;
FreeMem(FDIFArray[Index]);
NextDIF:=NextDIFC;
end;
SetLength(FDIFArray,0);
Result:=true;
end;
function TFATIndirect.SectorAbsolute(const ASector: SECT): int64;
begin
Result:=int64(ASector)*FSectorSize+FHeaderLength;
end;
function TFATIndirect.FindFreeFAT(const ABuffer: PSECT; const AStartIndex: SizeUint): SizeUInt;
var
j: SizeUint;
begin
Result:=SECT_FREESECT;
for j := AStartIndex to FFATEntriesPerSect-1 do begin
if ABuffer[j]=SECT_FREESECT then begin
Result:=j;
break;
end;
end;
end;
function TFATIndirect.AllocateNewSector(const AStartingFATIndex: SECT;
const ALinkFrom: SECT; const ALinkTo: SECT): SizeUInt;
var
j: SizeUint;
Sector: SECT;
DIFEntries: SECT;
DIFIndex,FATInDIF,OffsetInFAT: SECT;
Index: SizeUint;
DIFData: PSECT;
procedure CreateEmptyFATSector(const ASector: SECT);
var
Buffer: PBYTE;
begin
inc(FHeader._csectFat); //increment the FAT sector counter
Buffer:=nil;
GetMem(Buffer,FSectorSize);
FillByte(Buffer^,FSectorSize,$FF);
WriteFATSector(ASector,PSECT(Buffer));
FreeMem(Buffer);
end;
begin
//DIF sectors points to FAT sectors where the allocation happends.
//The first DIF sector is an special one with 109 entries (fixed),
//without next DIF sector link and it is allocated in the header.
//------------
DecomposeFATEntry(AStartingFATIndex+1,DIFIndex,FATInDIF,OffsetInFAT);
if (AStartingFATIndex>0) and (SizeInt(DIFIndex)<=High(FDIFArray)) then begin
//Due speed reasons, check next sector and all the sectors
//in the same FAT, this improves linear write & read.
//DIF is the special header one ?
if DIFIndex=0 then begin
DIFEntries:=0;
end else begin
DIFEntries:=FSectorSize div BYTES_PER_FAT_ENTRY;
end;
DIFData:=FDIFArray[DIFIndex];
for j := 0 to 0 do begin
Sector:=DIFData[FATInDIF];
if Sector=SECT_FREESECT then begin
//Create a new FAT sector just here
Sector:=ComposeFATEntry(DIFIndex,FATInDIF,0);
CreateEmptyFATSector(Sector);
DIFData[FATInDIF]:=Sector;
WriteFATEntryValue(Sector,SECT_FATSECT);
end;
ReadFATSector(Sector);
if FFATCache.Cache[OffsetInFAT]=SECT_FREESECT then begin
//Found sector as Free sector...
FFATCache.Cache[OffsetInFAT]:=ALinkTo;
WriteFATSector(Sector);
Result:=ComposeFATEntry(DIFIndex,FATInDIF,OffsetInFAT);
end else begin
//Not found, so try the complete FAT sector
Index:=FindFreeFAT(FFATCache.Cache,0);
if Index<>SECT_FREESECT then begin
//Found sector as free sector
FFATCache.Cache[Index]:=ALinkTo;
WriteFATSector(Sector);
Result:=ComposeFATEntry(DIFIndex,FATInDIF,Index);
end else begin
Result:=SECT_FREESECT;
end;
end;
if Result<>SECT_FREESECT then begin
//Write the changes
if ALinkFrom<>SECT_FREESECT then begin
WriteFATEntryValue(ALinkFrom,Result);
end;
end else begin
Result:=AllocateNewSector(0,ALinkFrom,ALinkTo);
end;
end;
if Result<>SECT_FREESECT then exit;
end;
for DIFIndex := 0 to High(FDIFArray) do begin
if DIFIndex=0 then begin
DIFEntries:=Length(FHeader._sectFat);
end else begin
DIFEntries:=(FSectorSize div BYTES_PER_FAT_ENTRY)-1;
end;
FATInDIF:=0;
OffsetInFAT:=0;
DIFData:=FDIFArray[DIFIndex];
for FATInDIF := 0 to DIFEntries-1 do begin
Sector:=DIFData[FATInDIF];
if Sector=SECT_FREESECT then begin
//Create a new FAT sector just here
Sector:=ComposeFATEntry(DIFIndex,FATInDIF,0);
CreateEmptyFATSector(Sector);
DIFData[FATInDIF]:=Sector;
WriteFATEntryValue(Sector,SECT_FATSECT);
end;
ReadFATSector(Sector);
for OffsetInFAT := 0 to FFATEntriesPerSect-1 do begin
if FFATCache.Cache[OffsetInFAT]=SECT_FREESECT then begin
//Found sector as Free sector...
FFATCache.Cache[OffsetInFAT]:=ALinkTo;
WriteFATSector(Sector);
Result:=ComposeFATEntry(DIFIndex,FATInDIF,OffsetInFAT);
if Result<>SECT_FREESECT then begin
//Write the changes
if ALinkFrom<>SECT_FREESECT then begin
WriteFATEntryValue(ALinkFrom,Result);
end;
Exit;
end;
end;
end;
end;
end;
//There is no empty space in current FAT so, add a new DIF
DIFIndex:=High(FDIFArray)+1;
FATInDIF:=0;
OffsetInFAT:=0;
Sector:=ComposeFATEntry(DIFIndex,FATInDIF,OffsetInFAT);
if DIFIndex=1 then begin
FHeader._sectDifStart:=Sector
end;
//Empty free sector
GetMem(DIFData,FSectorSize); //This memblock will be freed by UnloadDIF
FillByte(PBYTE(DIFData)^,FSectorSize,$FF);
//With ENDOFCHAIN marker
DIFData[FFATEntriesPerSect-1]:=SECT_ENDOFCHAIN;
//Link in the previous DIF sector
FDIFArray[High(FDIFArray)][FFATEntriesPerSect-1]:=Sector;
//Update memory block
SetLength(FDIFArray,DIFIndex+1);
FDIFArray[DIFIndex]:=DIFData;
FDirtyMedia:=true; //Forces a rewrite of DIF sectors when destroying the class.
inc(FHeader._csectDif); //Increments the DIF counter.
//Create a new FAT sector just here
CreateEmptyFATSector(Sector+1);
DIFData[FATInDIF]:=Sector+1;
WriteFATEntryValue(Sector,SECT_DIFSECT);
WriteFATEntryValue(Sector+1,SECT_FATSECT);
Result:=AllocateNewSector(Sector+1,ALinkFrom,ALinkTo);
end;
function TFATIndirect.GetStreamSizeInSectors(const AContext: TFATStreamContext
): int64;
var
Sector,LastSector: SECT;
begin
Result:=0;
LastSector:=AContext.FATFirstIndex;
while (LastSector<$FFFFFFF0) do begin
Sector:=LastSector;
LastSector:=ReadFATEntryValue(Sector);
inc(Result);
end;
end;
function TFATIndirect.GetFATOffsetForPosition(const APosition: int64
): SizeUint;
begin
Result:=APosition mod FSectorSize;
end;
function TFATIndirect.GetFATRemainForPosition(const APosition: int64
): SizeUint;
begin
Result:=FSectorSize -(APosition mod FSectorSize);
end;
function TFATIndirect.ReadData(var AContext: TFATStreamContext;
const ABuffer: PBYTE; const ASize: SizeInt): SizeInt;
var
Position: int64;
FAT,NextFAT: SECT;
CanRead: SizeUint;
RemainData: int64;
TargetBuffer: PBYTE;
EffectiveRead: int64;
begin
if ASize<1 then begin
Result:=0;
Exit;
end;
if AContext.AccessMode=fmOpenWrite then begin
if (@AContext<>@DirectoryContext) and
(@AContext<>@MiniFATContext) and
(@AContext<>@MiniFATDataContext) then begin
Raise EStreamError.Create('Stream can not be read, open for write only');
end;
end;
if AContext.Position>=AContext.Size Then begin
//EOF condition, can not read nothing.
Result:=0;
Exit;
end;
if Assigned(AContext.MiniStream) then begin
if AContext.Size<FHeader._ulMiniSectorCutoff then begin
//Read it from MiniFAT
AContext.MiniStream.Position:=AContext.Position;
Result:=AContext.MiniStream.Read(ABuffer^,ASize);
AContext.Position:=AContext.MiniStream.Position;
Exit;
end;
end;
if AContext.FATIndex=SECT_FREESECT then begin
ResynchronizePosition(AContext);
end;
If AContext.FATIndex=SECT_FREESECT then begin
Result:=0;
Exit;
end;
Position:=AContext.Position;
if Position+ASize>AContext.Size then begin
RemainData:=AContext.Size-Position;
end else begin
RemainData:=ASize;
end;
TargetBuffer:=ABuffer;
while RemainData>0 do begin
FAT:=AContext.FATIndex;
CanRead:=GetFATRemainForPosition(Position);
if CanRead>RemainData then begin
CanRead:=RemainData;
end;
if CanRead+AContext.Position>=AContext.Size then begin
CanRead:=AContext.Size-AContext.Position;
end;
if IsReservedValue(FAT) then begin
if FAT<>SECT_ENDOFCHAIN then begin
Raise Exception.Create('Damaged stream');
end;
end;
if CanRead>0 then begin
FStream.Position:=SectorAbsolute(FAT)+GetFATOffsetForPosition(Position);
EffectiveRead:=FStream.Read(TargetBuffer^,CanRead);
dec(RemainData,EffectiveRead);
inc(Position,EffectiveRead);
inc(TargetBuffer,EffectiveRead);
if (EffectiveRead<>CanRead) Then begin
AContext.FATIndex:=SECT_FREESECT;
Result:=ASize-RemainData;
Exit;
end;
end;
AContext.Position:=Position;
if GetFATRemainForPosition(Position)=FSectorSize then begin
//The stream is in sector boundary
NextFAT:=ReadFATEntryValue(FAT);
if NextFAT<>SECT_ENDOFCHAIN then begin
AContext.FATIndex:=NextFAT;
end else begin
AContext.FATIndex:=SECT_FREESECT; //Force resynchronization
Result:=ASize-RemainData;
Exit;
end;
end;
end;
Result:=ASize;
end;
function TFATIndirect.WriteData(var AContext: TFATStreamContext;
const ABuffer: PBYTE; const ASize: SizeInt): SizeInt;
var
Position: int64;
FAT,NextFAT: SECT;
CanWrite: SizeUint;
RemainData: int64;
SourceBuffer: PBYTE;
EffectiveWrite: int64;
procedure MoveMiniStreamToRegularStream();
var
ContextBackup: TFATStreamContext;
begin
ContextBackup:=AContext;
AContext.MiniStream:=nil;
//Delete here the mini stream if needed.
if not IsReservedValue(AContext.FATFirstIndex) then begin
ResetMiniFATLinkage(AContext.FATFirstIndex,SECT_FREESECT);
end;
AContext.FATFirstIndex:=SECT_ENDOFCHAIN;
AContext.FATIndex:=SECT_ENDOFCHAIN;
AContext.Size:=0;
AContext.Position:=0;
WriteData(AContext,ContextBackup.MiniStream.Memory,ContextBackup.MiniStream.Size);
ContextBackup.MiniStream.Free;
end;
begin
if ASize<1 then begin
Result:=0;
Exit;
end;
if AContext.AccessMode=fmOpenRead then begin
Raise EStreamError.Create('Stream can not be written, open for read only');
end;
AContext.Dirty:=true;
if Assigned(AContext.MiniStream) then begin
//It could be a MiniFAT stream.
if AContext.Size+ASize>=FHeader._ulMiniSectorCutoff then begin
//Jump to regular FAT allocation
MoveMiniStreamToRegularStream();
end else begin
//Write in the MiniFAT cache
AContext.MiniStream.Position:=AContext.Position;
Result:=AContext.MiniStream.Write(ABuffer^,ASize);
AContext.Position:=AContext.MiniStream.Position;
AContext.Size:=AContext.MiniStream.Size;
Exit;
end;
end;
if (AContext.FATIndex=SECT_FREESECT) then begin
ResynchronizePositionWithAllocation(AContext);
end;
Position:=AContext.Position;
RemainData:=ASize;
SourceBuffer:=ABuffer;
while RemainData>0 do begin
FAT:=AContext.FATIndex;
CanWrite:=GetFATRemainForPosition(Position);
if CanWrite>RemainData then begin
CanWrite:=RemainData;
end;
if IsReservedValue(FAT) then begin
if FAT<>SECT_ENDOFCHAIN then begin
Raise Exception.Create('Damaged stream');
end;
FAT:=AllocateNewSector(0,SECT_FREESECT,SECT_ENDOFCHAIN);
AContext.FATIndex:=FAT;
AContext.FATFirstIndex:=FAT;
end;
if CanWrite>0 then begin
FStream.Position:=SectorAbsolute(FAT)+GetFATOffsetForPosition(Position);
EffectiveWrite:=FStream.Write(SourceBuffer^,CanWrite);
dec(RemainData,EffectiveWrite);
inc(Position,EffectiveWrite);
inc(SourceBuffer,EffectiveWrite);
if (EffectiveWrite<>CanWrite) Then begin
AContext.FATIndex:=SECT_FREESECT;
Result:=ASize-RemainData;
Exit;
end;
end;
AContext.Position:=Position;
if AContext.Position>AContext.Size then begin
//The file is growing...
AContext.Size:=AContext.Position;
end;
//--------------
if GetFATRemainForPosition(Position)=FSectorSize then begin
if FAT<>SECT_ENDOFCHAIN then begin
NextFAT:=ReadFATEntryValue(FAT);
end;
if NextFAT<>SECT_ENDOFCHAIN then begin
AContext.FATIndex:=NextFAT;
end else begin
//Add a new FAT allocation.
NextFAT:=AllocateNewSector(FAT,FAT,SECT_ENDOFCHAIN);
if NextFAT=SECT_FREESECT then begin
//Failed to allocate new sector, Media full ?
AContext.FATIndex:=SECT_FREESECT; //Force resyncronization
Result:=ASize-RemainData;
Exit;
end;
WriteFATEntryValue(FAT,NextFAT);
AContext.FATIndex:=NextFAT;
NextFAT:=SECT_ENDOFCHAIN;
end;
end;
end;
Result:=ASize;
end;
function TFATIndirect.StreamSeekPosition(var AContext: TFATStreamContext;
const AOffset: int64; const AOrigin: TSeekOrigin): int64;
begin
Case AOrigin of
soBeginning: begin
AContext.FATIndex:=SECT_FREESECT; //Resets FAT seek
AContext.Position:=AOffset;
end;
soEnd: begin
AContext.FATIndex:=SECT_FREESECT;
if AContext.Size<AOffset then begin
Raise EStreamError.Create('Trying to move to before beginning of stream.');
end;
AContext.Position:=AContext.Size+AOffset;
end;
soCurrent: begin
AContext.FATIndex:=SECT_FREESECT;
if AContext.Position+AOffset<0 then begin
Raise EStreamError.Create('Trying to move to before beginning of stream.');
end;
AContext.Position:=AContext.Position+AOffset;
end;
else
Raise Exception.Create('Invalid Seek mode');
end;
Result:=AContext.Position;
end;
function TFATIndirect.Initialize(const ACreate: Boolean): Boolean;
var
RootEntry: TWCBFStructuredStorageDirectoryEntry;
begin
Result:=true;
if ACreate then begin
FillByte(FHeader,SizeOf(FHeader),0);
FHeader._abSig:=OLE_SIGTATURE;
//FHeader._clid:=ALL ZEROS, as set by FillByte
FHeader._uMinorVersion:=$003E;
FHeader._uDllVersion:=$0003;
FHeader._uByteOrder:=NToLE($FFFE);
FHeader._uSectorShift:=9;
FHeader._uMiniSectorShift:=6;
//Some reserved, must be zero..., Reserved, Reserved1 and Reserved2.
FHeader._csectFat:=0;
FHeader._sectDirStart:=SECT_ENDOFCHAIN;
//FHeader._signature:=0; //Transaction not used.
FHeader._ulMiniSectorCutoff:=4096; //This is customizable
FHeader._sectMiniFatStart:=SECT_ENDOFCHAIN;
FHeader._csectMiniFat:=0;
FHeader._sectDifStart:=SECT_ENDOFCHAIN;
FHeader._csectDif:=0;
Format(FHeader);
FStream.Position:=0;
FillByte(FHeader._sectFat[0],Sizeof(FHeader._sectFat),$FF);
FStream.Write(FHeader,Sizeof(FHeader));
end else begin
FStream.Position:=0;
if FStream.Size<SizeOf(FHeader) then begin
Result:=false;
Exit;
end;
if FStream.Read(FHeader,Sizeof(FHeader))<>Sizeof(FHeader) then begin
Result:=false;
end;
end;
if NToLE(FHeader._uByteOrder)=$FFFE then begin
//Does not need to perform any endian change, the file endianess
//matches the current machine endianess. This means big endian file
//in big endian machine or little endian file in little endian machine.
FNeedEndianChange:=false;
end else begin
FNeedEndianChange:=true;
end;
iHeaderLEToN(FHeader);
//Check some structured details to detect file structure as expected
if not CompareMem(@FHeader._abSig[0],@OLE_SIGTATURE[0],sizeof(OLE_SIGTATURE)) then begin
Result:=false;
Exit;
end;
//----------------------