-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathFAT.py
1920 lines (1746 loc) · 76.7 KB
/
FAT.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: cp1252 -*-
# Utilities to manage a FAT12/16/32 file system
#
DEBUG=0
import sys, copy, os, struct, time, cStringIO, atexit
from datetime import datetime
from collections import OrderedDict
from zlib import crc32
import disk, utils
from debug import log
if DEBUG&4: import hexdump
FS_ENCODING = sys.getfilesystemencoding()
class FATException(Exception):
pass
class boot_fat32(object):
"FAT32 Boot Sector"
layout = { # { offset: (name, unpack string) }
0x00: ('chJumpInstruction', '3s'),
0x03: ('chOemID', '8s'),
0x0B: ('wBytesPerSector', '<H'),
0x0D: ('uchSectorsPerCluster', 'B'),
0x0E: ('wSectorsCount', '<H'), # reserved sectors (min 32?)
0x10: ('uchFATCopies', 'B'),
0x11: ('wMaxRootEntries', '<H'),
0x13: ('wTotalSectors', '<H'),
0x15: ('uchMediaDescriptor', 'B'),
0x16: ('wSectorsPerFAT', '<H'), # not used, see 24h instead
0x18: ('wSectorsPerTrack', '<H'),
0x1A: ('wHeads', '<H'),
0x1C: ('wHiddenSectors', '<H'),
0x1E: ('wTotalHiddenSectors', '<H'),
0x20: ('dwTotalLogicalSectors', '<I'),
0x24: ('dwSectorsPerFAT', '<I'),
0x28: ('wMirroringFlags', '<H'), # bits 0-3: active FAT, it bit 7 set; else: mirroring as usual
0x2A: ('wVersion', '<H'),
0x2C: ('dwRootCluster', '<I'), # usually 2
0x30: ('wFSISector', '<H'), # usually 1
0x32: ('wBootCopySector', '<H'), # 0x0000 or 0xFFFF if unused, usually 6
0x34: ('chReserved', '12s'),
0x40: ('chPhysDriveNumber', 'B'),
0x41: ('chFlags', 'B'),
0x42: ('chExtBootSignature', 'B'),
0x43: ('dwVolumeID', '<I'),
0x47: ('sVolumeLabel', '11s'),
0x52: ('sFSType', '8s'),
#~ 0x72: ('chBootstrapCode', '390s'),
0x1FE: ('wBootSignature', '<H') # 55 AA
} # Size = 0x200 (512 byte)
def __init__ (self, s=None, offset=0, stream=None):
self._i = 0
self._pos = offset # base offset
self._buf = s or bytearray(512) # normal boot sector size
self.stream = stream
self._kv = self.layout.copy()
self._vk = {} # { name: offset}
for k, v in self._kv.items():
self._vk[v[0]] = k
self.__init2__()
def __init2__(self):
if not self.wBytesPerSector: return
# Cluster size (bytes)
self.cluster = self.wBytesPerSector * self.uchSectorsPerCluster
# Offset of the 1st FAT copy
self.fatoffs = self.wSectorsCount * self.wBytesPerSector + self._pos
# Data area offset (=cluster #2)
self.dataoffs = self.fatoffs + self.uchFATCopies * self.dwSectorsPerFAT * self.wBytesPerSector + self._pos
# Number of clusters represented in this FAT (if valid buffer)
self.fatsize = self.dwTotalLogicalSectors/self.uchSectorsPerCluster
if self.stream:
self.fsinfo = fat32_fsinfo(stream=self.stream, offset=self.wFSISector*self.cluster)
else:
self.fsinfo = None
__getattr__ = utils.common_getattr
def __str__ (self):
return utils.class2str(self, "FAT32 Boot Sector @%x\n" % self._pos)
def pack(self):
"Update internal buffer"
for k, v in self._kv.items():
self._buf[k:k+struct.calcsize(v[1])] = struct.pack(v[1], getattr(self, v[0]))
self.__init2__()
return self._buf
def clusters(self):
"Return the number of clusters in the data area"
# Total sectors minus sectors preceding the data area
return (self.dwTotalLogicalSectors - (self.dataoffs/self.wBytesPerSector)) / self.uchSectorsPerCluster
def cl2offset(self, cluster):
"Return the real offset of a cluster"
return self.dataoffs + (cluster-2)*self.cluster
def root(self):
"Return the offset of the root directory"
return self.cl2offset(self.dwRootCluster)
def fat(self, fatcopy=0):
"Return the offset of a FAT table (the first by default)"
return self.fatoffs + fatcopy * self.dwSectorsPerFAT * self.wBytesPerSector
class fat32_fsinfo(object):
"FAT32 FSInfo Sector (usually sector 1)"
layout = { # { offset: (name, unpack string) }
0x00: ('sSignature1', '4s'), # RRaA
0x1E4: ('sSignature2', '4s'), # rrAa
0x1E8: ('dwFreeClusters', '<I'), # 0xFFFFFFFF if unused (may be incorrect)
0x1EC: ('dwNextFreeCluster', '<I'), # hint only (0xFFFFFFFF if unused)
0x1FE: ('wBootSignature', '<H') # 55 AA
} # Size = 0x200 (512 byte)
def __init__ (self, s=None, offset=0, stream=None):
self._i = 0
self._pos = offset # base offset
self._buf = s or bytearray(512) # normal FSInfo sector size
self.stream = stream
self._kv = self.layout.copy()
self._vk = {} # { name: offset}
for k, v in self._kv.items():
self._vk[v[0]] = k
__getattr__ = utils.common_getattr
def pack(self):
"Update internal buffer"
for k, v in self._kv.items():
self._buf[k:k+struct.calcsize(v[1])] = struct.pack(v[1], getattr(self, v[0]))
return self._buf
def __str__ (self):
return utils.class2str(self, "FAT32 FSInfo Sector @%x\n" % self._pos)
class boot_fat16(object):
"FAT12/16 Boot Sector"
layout = { # { offset: (name, unpack string) }
0x00: ('chJumpInstruction', '3s'),
0x03: ('chOemID', '8s'),
0x0B: ('wBytesPerSector', '<H'),
0x0D: ('uchSectorsPerCluster', 'B'),
0x0E: ('wSectorsCount', '<H'),
0x10: ('uchFATCopies', 'B'),
0x11: ('wMaxRootEntries', '<H'),
0x13: ('wTotalSectors', '<H'),
0x15: ('uchMediaDescriptor', 'B'),
0x16: ('wSectorsPerFAT', '<H'), #DWORD in FAT32
0x18: ('wSectorsPerTrack', '<H'),
0x1A: ('wHeads', '<H'),
0x1C: ('dwHiddenSectors', '<I'), # Here differs from FAT32
0x20: ('dwTotalLogicalSectors', '<I'),
0x24: ('chPhysDriveNumber', 'B'),
0x25: ('uchCurrentHead', 'B'),
0x26: ('uchSignature', 'B'), # 0x28 or 0x29
0x27: ('dwVolumeID', '<I'),
0x2B: ('sVolumeLabel', '11s'),
0x36: ('sFSType', '8s'),
0x1FE: ('wBootSignature', '<H') # 55 AA
} # Size = 0x200 (512 byte)
def __init__ (self, s=None, offset=0, stream=None):
self._i = 0
self._pos = offset # base offset
self._buf = s or bytearray(512) # normal boot sector size
self.stream = stream
self._kv = self.layout.copy()
self._vk = {} # { name: offset}
for k, v in self._kv.items():
self._vk[v[0]] = k
self.__init2__()
def __init2__(self):
if not self.wBytesPerSector: return
# Cluster size (bytes)
self.cluster = self.wBytesPerSector * self.uchSectorsPerCluster
# Offset of the 1st FAT copy
self.fatoffs = self.wSectorsCount * self.wBytesPerSector + self._pos
# Number of clusters represented in this FAT
# Here the DWORD field seems to be set only if WORD one is too small
self.fatsize = (self.dwTotalLogicalSectors or self.wTotalSectors)/self.uchSectorsPerCluster
# Offset of the fixed root directory table (immediately after the FATs)
self.rootoffs = self.fatoffs + self.uchFATCopies * self.wSectorsPerFAT * self.wBytesPerSector + self._pos
# Data area offset (=cluster #2)
self.dataoffs = self.rootoffs + (self.wMaxRootEntries*32)
# Set for compatibility with FAT32 code
self.dwRootCluster = 0
__getattr__ = utils.common_getattr
def __str__ (self):
return utils.class2str(self, "FAT12/16 Boot Sector @%x\n" % self._pos)
def pack(self):
"Update internal buffer"
for k, v in self._kv.items():
self._buf[k:k+struct.calcsize(v[1])] = struct.pack(v[1], getattr(self, v[0]))
self.__init2__()
return self._buf
def clusters(self):
"Return the number of clusters in the data area"
# Total sectors minus sectors preceding the data area
return ((self.dwTotalLogicalSectors or self.wTotalSectors) - (self.dataoffs/self.wBytesPerSector)) / self.uchSectorsPerCluster
def cl2offset(self, cluster):
"Return the real offset of a cluster"
return self.dataoffs + (cluster-2)*self.cluster
def root(self):
"Return the offset of the root directory"
return self.rootoffs
def fat(self, fatcopy=0):
"Return the offset of a FAT table (the first by default)"
return self.fatoffs + fatcopy * self.wSectorsPerFAT * self.wBytesPerSector
# NOTE: limit decoded dictionary size! Zero or {}.popitem()?
class FAT(object):
"Decodes a FAT (12, 16, 32 o EX) table on disk"
def __init__ (self, stream, offset, clusters, bitsize=32, exfat=0):
self.stream = stream
self.size = clusters # total clusters in the data area (max = 2^x - 11)
self.bits = bitsize # cluster slot bits (12, 16 or 32)
self.offset = offset # relative FAT offset (1st copy)
# CAVE! This accounts the 0-1 unused cluster index?
self.offset2 = offset + (((clusters*bitsize+7)/8)+511)/512*512 # relative FAT offset (2nd copy)
self.exfat = exfat # true if exFAT (aka FAT64)
self.reserved = 0x0FF7
self.bad = 0x0FF7
self.last = 0x0FFF
if bitsize == 32:
self.fat_slot_size = 4
self.fat_slot_fmt = '<I'
else:
self.fat_slot_size = 2
self.fat_slot_fmt = '<H'
if bitsize == 16:
self.reserved = 0xFFF7
self.bad = 0xFFF7
self.last = 0xFFFF
elif bitsize == 32:
self.reserved = 0x0FFFFFF7 # FAT32 uses 28 bits only
self.bad = 0x0FFFFFF7
self.last = 0x0FFFFFF8
if exfat: # EXFAT uses all 32 bits...
self.reserved = 0xFFFFFFF7
self.bad = 0xFFFFFFF7
self.last = 0xFFFFFFFF
# maximum cluster index effectively addressable
# clusters ranges from 2 to 2+n-1 clusters (zero based), so last valid index is n+1
self.real_last = min(self.reserved-1, self.size+2-1)
self.decoded = {} # {cluster index: cluster content}
self.last_free_alloc = 2 # last free cluster allocated (also set in FAT32 FSInfo)
self.free_clusters = None # tracks free clusters
# ordered (by disk offset) dictionary {first_cluster: run_length} mapping free space
self.free_clusters_map = None
self.map_free_space()
self.free_clusters_flag = 1
def __str__ (self):
return "%d-bit %sFAT table of %d clusters starting @%Xh\n" % (self.bits, ('','ex')[self.exfat], self.size, self.offset)
def __getitem__ (self, index):
"Retrieve the value stored in a given cluster index"
try:
assert 2 <= index <= self.real_last
except AssertionError:
if DEBUG&4: log("Attempt to read unexistant FAT index #%d", index)
#~ raise FATException("Attempt to read unexistant FAT index #%d" % index)
return self.last
slot = self.decoded.get(index)
if slot: return slot
pos = self.offset+(index*self.bits)/8
self.stream.seek(pos)
slot = struct.unpack(self.fat_slot_fmt, self.stream.read(self.fat_slot_size))[0]
#~ print "getitem", self.decoded
if self.bits == 12:
# Pick the 12 bits we want
if index % 2: # odd cluster
slot = slot >> 4
else:
slot = slot & 0x0FFF
self.decoded[index] = slot
if DEBUG&4: log("Got FAT1[0x%X]=0x%X @0x%X", index, slot, pos)
return slot
# Defer write on FAT#2 allowing undelete?
def __setitem__ (self, index, value):
"Set the value stored in a given cluster index"
try:
assert 2 <= index <= self.real_last
except AssertionError:
if DEBUG&4: log("Attempt to set invalid cluster index 0x%X with value 0x%X", index, value)
return
raise FATException("Attempt to set invalid cluster index 0x%X with value 0x%X" % (index, value))
try:
assert value <= self.real_last or value >= self.reserved
except AssertionError:
if DEBUG&4: log("Attempt to set invalid value 0x%X in cluster 0x%X", value, index)
return
raise FATException("Attempt to set invalid cluster index 0x%X with value 0x%X" % (index, value))
self.decoded[index] = value
dsp = (index*self.bits)/8
pos = self.offset+dsp
if self.bits == 12:
# Pick and set only the 12 bits we want
self.stream.seek(pos)
slot = struct.unpack(self.fat_slot_fmt, self.stream.read(self.fat_slot_size))[0]
if index % 2: # odd cluster
# Value's 12 bits moved to top ORed with original bottom 4 bits
#~ print "odd", hex(value), hex(slot), self.decoded
value = (value << 4) | (slot & 0xF)
#~ print hex(value), hex(slot)
else:
# Original top 4 bits ORed with value's 12 bits
#~ print "even", hex(value), hex(slot)
value = (slot & 0xF000) | value
#~ print hex(value), hex(slot)
if DEBUG&4: log("setting FAT1[0x%X]=0x%X @0x%X", index, value, pos)
self.stream.seek(pos)
value = struct.pack(self.fat_slot_fmt, value)
self.stream.write(value)
if self.exfat: return # exFAT has one FAT only (default)
pos = self.offset2+dsp
if DEBUG&4: log("setting FAT2[0x%X] @0x%X", index, pos)
self.stream.seek(pos)
self.stream.write(value)
def isvalid(self, index):
"Test if index is a valid cluster number in this FAT"
# Inline explicit test avoiding func call to speed-up
if (index >= 2 and index <= self.real_last) or self.islast(index) or self.isbad(index):
return 1
if DEBUG&4: log("invalid cluster index: %x", index)
return 0
def islast(self, index):
"Test if index is the last cluster in the chain"
return self.last <= index <= self.last+7 # *F8 ... *FF
def isbad(self, index):
"Test if index is a bad cluster"
return index == self.bad
def count(self, startcluster):
"Count the clusters in a chain. Returns a tuple (<total clusters>, <last cluster>)"
n = 1
while not (self.last <= self[startcluster] <= self.last+7): # islast
startcluster = self[startcluster]
n += 1
return (n, startcluster)
def count_to(self, startcluster, clusters):
"Finds the index of the n-th cluster in a chain"
while clusters and not (self.last <= self[startcluster] <= self.last+7): # islast
startcluster = self[startcluster]
clusters -= 1
return startcluster
def count_run(self, start, count=0):
"""Returns the count of the clusters in a contiguous run from 'start'
and the next cluster (or END CLUSTER mark), eventually limiting to the first 'count' clusters"""
#~ print "count_run(%Xh, %d)" % (start, count)
n = 1
while 1:
if self.last <= start <= self.last+7: # if end cluster
break
prev = start
start = self[start]
# If next LCN is not contig
if prev != start-1:
break
# If max run length reached
if count > 0:
if count-1 == 0:
break
else:
count -= 1
n += 1
return n, start
def findmaxrun(self):
"Find the greatest cluster run available. Returns a tuple (total_free_clusters, (run_start, clusters))"
t = 1,0
maxrun=(0,0)
n=0
while 1:
t = self.findfree(t[0]+1)
if t[0] < 0: break
if DEBUG&4: log("Found %d free clusters from #%d", t[1], t[0])
maxrun = max(t, maxrun, key=lambda x:x[1])
n += t[1]
t = (t[0]+t[1], t[1])
if DEBUG&4: log("Found the biggest run of %d clusters from #%d on %d total free clusters", maxrun[1], maxrun[0], n)
return n, maxrun
def map_free_space(self):
"Maps the free clusters in an ordered dictionary {start_cluster: run_length}"
if self.exfat: return
startpos = self.stream.tell()
self.free_clusters_map = {}
FREE_CLUSTERS=0
if self.bits < 32:
# FAT16 is max 130K...
PAGE = self.offset2 - self.offset - (2*self.bits)/8
else:
# FAT32 could reach ~1GB!
PAGE = 1<<20
END_OF_CLUSTERS = self.offset + (self.size*self.bits+7)/8 + (2*self.bits)/8
i = self.offset+(2*self.bits)/8 # address of cluster #2
self.stream.seek(i)
while i < END_OF_CLUSTERS:
s = self.stream.read(min(PAGE, END_OF_CLUSTERS-i)) # slurp full FAT, or 1M page if FAT32
if DEBUG&4: log("map_free_space: loaded FAT page of %d bytes @0x%X", len(s), i)
j=0
while j < len(s):
first_free = -1
run_length = -1
while j < len(s):
if self.bits == 32:
if s[j] != 0 or s[j+1] != 0 or s[j+2] != 0 or s[j+3] != 0:
j += 4
if run_length > 0: break
continue
elif self.bits == 16:
if s[j] != 0 or s[j+1] != 0:
j += 2
if run_length > 0: break
continue
elif self.bits == 12:
# Pick the 12 bits wanted
# 0 1 2
# AAAAAAAA AAAABBBB BBBBBBBB
if not j%3:
if s[j] != 0 or s[j+1]>>4 != 0:
j += 1
if run_length > 0: break
continue
elif j%3 == 1:
j+=1
continue # simply skips median byte
else: # j%3==2
if s[j] != 0 or s[j-1] & 0x0FFF != 0:
j += 1
if run_length > 0: break
continue
if first_free < 0:
first_free = (i-self.offset+j)*8/self.bits
if DEBUG&4: log("map_free_space: found run from %d", first_free)
run_length = 0
run_length += 1
j+=self.bits/8
if first_free < 0: continue
FREE_CLUSTERS+=run_length
self.free_clusters_map[first_free] = run_length
if DEBUG&4: log("map_free_space: appended run (%d, %d)", first_free, run_length)
i += len(s) # advance to next FAT page to examine
self.stream.seek(startpos)
self.free_clusters = FREE_CLUSTERS
if DEBUG&4: log("map_free_space: %d clusters free in %d runs", FREE_CLUSTERS, len(self.free_clusters_map))
return FREE_CLUSTERS, len(self.free_clusters_map)
def findfree(self, count=0):
"""Return index and length of the first free clusters run beginning from
'start' or (-1,0) in case of failure. If 'count' is given, limit the search
to that amount."""
if self.free_clusters_map == None:
self.map_free_space()
try:
i, n = self.free_clusters_map.popitem()
except KeyError:
return -1, -1
if DEBUG&4: log("got run of %d free clusters from #%x", n, i)
if n-count > 0:
self.free_clusters_map[i+count] = n-count # updates map
self.free_clusters-=min(n,count)
return i, min(n, count)
def map_compact(self, strategy=0):
"Compacts, eventually reordering, the free space runs map"
if not self.free_clusters_flag: return
#~ print "Map before:", sorted(self.free_clusters_map.iteritems())
map_changed = 0
while 1:
d=copy.copy(self.free_clusters_map)
for k,v in sorted(self.free_clusters_map.iteritems()):
while d.get(k+v): # while contig runs exist, merge
v1 = d.get(k+v)
if DEBUG&4: log("Compacting free_clusters_map: {%d:%d} -> {%d:%d}", k,v,k,v+v1)
d[k] = v+v1
del d[k+v]
#~ print "Compacted {%d:%d} -> {%d:%d}" %(k,v,k,v+v1)
#~ print sorted(d.iteritems())
v+=v1
if self.free_clusters_map != d:
self.free_clusters_map = d
map_changed = 1
continue
break
self.free_clusters_flag = 0
#~ if strategy == 1:
#~ self.free_clusters_map = OrderedDict(sorted(self.free_clusters_map.items(), key=lambda t: t[0])) # sort by disk offset
#~ elif strategy == 2:
#~ self.free_clusters_map = OrderedDict(sorted(self.free_clusters_map.items(), key=lambda t: t[1])) # sort by run size
if DEBUG&4: log("Free space map - %d run(s): %s", len(self.free_clusters_map), self.free_clusters_map)
#~ print "Map AFTER:", sorted(self.free_clusters_map.iteritems())
# TODO: split very large runs
# About 12% faster injecting a Python2 tree
def mark_run(self, start, count, clear=False):
"Mark a range of consecutive FAT clusters (optimized for FAT16/32)"
if not count: return
if DEBUG&4: log("mark_run(%Xh, %d, clear=%d)", start, count, clear)
if start<2 or start>self.real_last:
if DEBUG&4: log("attempt to mark invalid run, aborted!")
return
if self.bits == 12:
if clear == True:
self.free_clusters_flag = 1
self.free_clusters_map[start] = count
while count:
self[start] = (start+1, 0)[clear==True]
start+=1
count-=1
return
dsp = (start*self.bits)/8
pos = self.offset+dsp
self.stream.seek(pos)
if clear:
for i in xrange(start, start+count):
self.decoded[i] = 0
run = bytearray(count*(self.bits/8)*'\x00')
self.stream.write(run)
self.free_clusters_flag = 1
self.free_clusters_map[start] = count
if self.exfat: return # exFAT has one FAT only (default)
# updating FAT2, too!
self.stream.seek(self.offset2+dsp)
self.stream.write(run)
return
# consecutive values to set
L = xrange(start+1, start+1+count)
for i in L:
self.decoded[i-1] = i
self.decoded[start+count-1] = self.last
# converted in final LE WORD/DWORD array
L = map(lambda x: struct.pack(self.fat_slot_fmt, x), L)
L[-1] = struct.pack(self.fat_slot_fmt, self.last)
run = bytearray().join(L)
self.stream.write(run)
if self.exfat: return # exFAT has one FAT only (default)
# updating FAT2, too!
pos = self.offset2+dsp
self.stream.seek(pos)
self.stream.write(run)
def alloc(self, runs_map, count, params={}):
"""Allocates a set of free clusters, marking the FAT.
runs_map is the dictionary of previously allocated runs
count is the number of clusters to allocate
params is an optional dictionary of directives to tune the allocation (to be done).
Returns the last cluster or raise an exception in case of failure"""
self.map_compact()
if self.free_clusters < count:
if DEBUG&4: log("Couldn't allocate %d cluster(s), only %d free", count, self.free_clusters)
raise FATException("FATAL! Free clusters exhausted, couldn't allocate %d, only %d left!" % (count, self.free_clusters))
if DEBUG&4: log("Ok to allocate %d cluster(s), %d free", count, self.free_clusters)
last_run = None
while count:
if runs_map:
last_run = runs_map.items()[-1]
i, n = self.findfree(count)
self.mark_run(i, n) # marks the FAT
if last_run:
self[last_run[0]+last_run[1]-1] = i # link prev chain with last
if last_run and i == last_run[0]+last_run[1]: # if contiguous
runs_map[last_run[0]] = n+last_run[1]
else:
runs_map[i] = n
last = i + n - 1 # last cluster in new run
count -= n
self[last] = self.last
self.last_free_alloc = last
if DEBUG&4: log("New runs map: %s", runs_map)
return last
def free(self, start, runs=None):
"Free a clusters chain, one run at a time (except FAT12)"
if start < 2 or start > self.real_last:
if DEBUG&4: log("free: attempt to free from invalid cluster %Xh", start)
return
self.free_clusters_flag = 1
if runs:
for run in runs:
if DEBUG&4: log("free: directly zeroing run of %d clusters from %Xh", runs[run], run)
self.mark_run(run, runs[run], True)
if not self.exfat:
self.free_clusters += runs[run]
self.free_clusters_map[run] = runs[run]
return
while True:
length, next = self.count_run(start)
if DEBUG&4:
log("free: count_run returned %d, %Xh", length, next)
log("free: zeroing run of %d clusters from %Xh (next=%Xh)", length, start, next)
self.mark_run(start, length, True)
if not self.exfat:
self.free_clusters += length
self.free_clusters_map[start] = length
start = next
if self.last <= next <= self.last+7: break
class Chain(object):
"Opens a cluster chain or run like a plain file"
def __init__ (self, boot, fat, cluster, size=0, nofat=0, end=0):
self.isdirectory=False
self.stream = boot.stream
self.boot = boot
self.fat = fat
self.start = cluster # start cluster or zero if empty
self.end = end # end cluster
self.nofat = nofat # 0=uses FAT (fragmented)
self.size = (size+boot.cluster-1)/boot.cluster*boot.cluster
# Size in bytes of allocated cluster(s)
if self.start and (not nofat or not self.fat.exfat):
if not size or not end:
self.size, self.end = fat.count(cluster)
self.size *= boot.cluster
else:
self.size = (size+boot.cluster-1)/boot.cluster*boot.cluster
self.end = cluster + (size+boot.cluster-1)/boot.cluster
self.filesize = size or self.size # file size, if available, or chain size
self.pos = 0 # virtual stream linear pos
# Virtual Cluster Number (cluster index in this chain)
self.vcn = 0
# Virtual Cluster Offset (current offset in VCN)
self.vco = 0
self.lastvlcn = (0, cluster) # last cluster VCN & LCN
self.runs = OrderedDict() # RLE map of fragments
if self.start:
self._get_frags()
if DEBUG&4: log("Cluster chain of %d%sbytes (%d bytes) @LCN %Xh:LBA %Xh", self.filesize, (' ', ' contiguous ')[nofat], self.size, cluster, self.boot.cl2offset(cluster))
def __str__ (self):
return "Chain of %d (%d) bytes from LCN %Xh (LBA %Xh)" % (self.filesize, self.size, self.start, self.boot.cl2offset(self.start))
def _get_frags(self):
"Maps the cluster runs composing the chain"
start = self.start
if self.nofat:
self.runs[start] = self.size/self.boot.cluster
else:
while 1:
length, next = self.fat.count_run(start)
self.runs[start] = length
if next == self.fat.last or next==start+length-1: break
start = next
if DEBUG&4: log("Runs map for %s: %s", self, self.runs)
def _alloc(self, count):
"Allocates some clusters and updates the runs map. Returns last allocated LCN"
if self.fat.exfat:
self.end = self.boot.bitmap.alloc(self.runs, count)
else:
self.end = self.fat.alloc(self.runs, count)
if not self.start:
self.start = self.runs.keys()[0]
self.nofat = (len(self.runs)==1)
self.size += count * self.boot.cluster
return self.end
def maxrun4len(self, length):
"Returns the longest run of clusters, up to 'length' bytes, from current position"
if not self.runs:
self._get_frags()
n = (length+self.boot.cluster-1)/self.boot.cluster # contig clusters searched for
found = 0
items = self.runs.items()
for start, count in items:
# if current LCN is in run
if start <= self.lastvlcn[1] < start+count:
found=1
break
if not found:
raise FATException("FATAL! maxrun4len did NOT found current LCN!\n%s\n%s" % (self.runs, self.lastvlcn))
left = start+count-self.lastvlcn[1] # clusters to end of run
run = min(n, left)
maxchunk = run*self.boot.cluster
if n < left:
next = self.lastvlcn[1]+n
else:
i = items.index((start, count))
if i == len(items)-1:
next = self.fat.last
else:
next = items[i+1][0] # first of next run
# Updates VCN & next LCN
self.lastvlcn = (self.lastvlcn[0]+n, next)
if DEBUG&4:
log("Chain%08X: maxrun4len(%d) on %s, maxchunk of %d bytes, lastvlcn=%s", self.start, length, self.runs, maxchunk, self.lastvlcn)
return maxchunk
def tell(self): return self.pos
def realtell(self):
return self.boot.cl2offset(self.lastvlcn[1])+self.vco
def seek(self, offset, whence=0):
if whence == 1:
self.pos += offset
elif whence == 2:
if self.size:
self.pos = self.size + offset
else:
self.pos = offset
# allocate some clusters if needed (in write mode)
if self.pos > self.size:
if self.boot.stream.mode == 'r+b':
clusters = (self.pos+self.boot.cluster-1)/self.boot.cluster - self.size/self.boot.cluster
self._alloc(clusters)
if DEBUG&4: log("Chain%08X: allocated %d cluster(s) seeking %Xh", self.start, clusters, self.pos)
else:
self.pos = self.size
# Maps Virtual Cluster Number (chain cluster) to Logical Cluster Number (disk cluster)
self.vcn = self.pos / self.boot.cluster # n-th cluster chain
self.vco = self.pos % self.boot.cluster # offset in it
vcn = 0
for start, count in self.runs.items():
# if current VCN is in run
if vcn <= self.vcn < vcn+count:
lcn = start + self.vcn - vcn
#~ print "Chain%08X: mapped VCN %d to LCN %Xh (LBA %Xh)"%(self.start, self.vcn, lcn, self.boot.cl2offset(lcn))
if DEBUG&4:
log("Chain%08X: mapped VCN %d to LCN %Xh (%d), LBA %Xh", self.start, self.vcn, lcn, lcn, self.boot.cl2offset(lcn))
log("Chain%08X: seeking cluster offset %Xh (%d)", self.start, self.vco, self.vco)
self.stream.seek(self.boot.cl2offset(lcn)+self.vco)
self.lastvlcn = (self.vcn, lcn)
#~ print "Set lastvlcn", self.lastvlcn
return
vcn += count
if DEBUG&4: log("Chain%08X: reached chain's end seeking VCN %Xh", self.start, self.vcn)
def read(self, size=-1):
if DEBUG&4: log("Chain%08X: read(%d) called from offset %Xh (%d) of %d", self.start, size, self.pos, self.pos, self.filesize)
# If negative size, set it to file size
if size < 0:
size = self.filesize
# If requested size is greater than file size, limit to the latter
if self.pos + size > self.filesize:
size = self.filesize - self.pos
if size < 0: size = 0
if DEBUG&4: log("Chain%08X: adjusted size is %d", self.start, size)
buf = bytearray()
if not size:
if DEBUG&4: log("Chain%08X: returning empty buffer", self.start)
return buf
self.seek(self.pos) # coerce real stream to the right position!
if self.nofat: # contiguous clusters
buf += self.stream.read(size)
self.pos += size
if DEBUG&4: log("Chain%08X: read %d contiguous bytes @VCN %Xh [%X:%X]", self.start, len(buf), self.vcn, self.vco, self.vco+size)
return buf
while 1:
if not size: break
n = min(size, self.maxrun4len(size)-self.vco)
buf += self.stream.read(n)
size -= n
self.pos += n
if DEBUG&4: log("Chain%08X: read %d (%d) bytes @VCN %Xh [%X:%X]", self.start, n, len(buf), self.vcn, self.vco, self.vco+n)
self.seek(self.pos)
return buf
def write(self, s):
if not s: return
if DEBUG&4: log("Chain%08X: write(buf[:%d]) called from offset %Xh (%d), VCN %Xh(%d)[%Xh:]", self.start, len(s), self.pos, self.pos, self.vcn, self.vcn, self.vco)
new_allocated = 0
if self.pos + len(s) > self.size:
# Alloc more clusters from actual last one
# reqb=requested bytes, reqc=requested clusters
reqb = self.pos + len(s) - self.size
reqc = (reqb+self.boot.cluster-1)/self.boot.cluster
if DEBUG&4:
log("pos=%X(%d), len=%d, size=%d(%Xh)", self.pos, self.pos, len(s), self.size, self.size)
log("required %d byte(s) [%d cluster(s)] more to write", reqb, reqc)
self._alloc(reqc)
new_allocated = 1
# force lastvlcn update (needed on allocation)
self.seek(self.pos)
if self.nofat: # contiguous clusters
self.stream.write(s)
if DEBUG&4: log("Chain%08X: %d bytes fully written", self.start, len(s))
self.pos += len(s)
# file size is the top pos reached during write
self.filesize = max(self.filesize, self.pos)
return
size=len(s) # bytes to do
i=0 # pos in buffer
while 1:
if not size: break
n = min(size, self.maxrun4len(size)-self.vco) # max bytes to complete run
self.stream.write(s[i:i+n])
size-=n
i+=n
self.pos += n
if DEBUG&4: log("Chain%08X: written %d bytes (%d of %d) @VCN %d [%Xh:%Xh]", self.start, n, i, len(s), self.vcn, self.vco, self.vco+n)
self.seek(self.pos)
self.filesize = max(self.filesize, self.pos)
if new_allocated and (not self.fat.exfat or self.isdirectory):
# When allocating a directory table, it is strictly necessary that only the first byte in
# an empty slot (the first) is set to NULL
if self.pos < self.size:
if DEBUG&4: log("Chain%08X: blanking newly allocated cluster tip, %d bytes @0x%X", self.start, self.size-self.pos, self.pos)
self.stream.write(bytearray(self.size - self.pos))
def trunc(self):
"Truncates the clusters chain to the current one, freeing the rest"
x = self.pos/self.boot.cluster # last VCN (=actual) to set
n = (self.size+self.boot.cluster-1)/self.boot.cluster - x - 1 # number of clusters to free
if DEBUG&4: log("%s: truncating @VCN %d, freeing %d clusters", self, x, n)
if not n:
if DEBUG&4: log("nothing to truncate!")
return 1
#~ print "%s: truncating @VCN %d, freeing %d clusters. %d %d" % (self, x, n, self.pos, self.size)
#~ print "Start runs:\n", self.runs
# Updates chain and virtual stream sizes
self.size = (x+1)*self.boot.cluster
self.filesize = self.pos
while 1:
if not n: break
start, length = self.runs.popitem()
if n >= length:
#~ print "Zeroing %d from %d" % (length, start)
if self.fat.exfat:
self.boot.bitmap.free1(start, length)
else:
self.fat.mark_run(start, length, True)
if n == length and (not self.fat.exfat or len(self.runs) > 1):
k = self.runs.keys()[-1]
self.fat[k+self.runs[k]-1] = self.fat.last
n -= length
else:
#~ print "Zeroing %d from %d, last=%d" % (n, start+length-n, start+length-n-1)
if self.fat.exfat:
self.boot.bitmap.free1(start+length-n, n)
else:
self.fat.mark_run(start+length-n, n, True)
if len(self.runs) or not self.fat.exfat:
# Set new last cluster
self.fat[start+length-n-1] = self.fat.last
self.runs[start] = length-n
n=0
#~ print "Final runs:\n", self.runs
#~ for start, length in self.runs.items():
#~ for i in range(length):
#~ print "Cluster %d=%d"%(start+i, self.fat[start+i])
self.nofat = (len(self.runs)==1)
return 0
def frags(self):
if DEBUG&4:
log("Fragmentation of %s", self)
log("Detected %d fragments for %d clusters", len(self.runs), self.size/self.boot.cluster)
log("Fragmentation is %f", float(len(self.runs)-1) / float(self.size/self.boot.cluster))
return len(self.runs)
class FixedRoot(object):
"Handle the FAT12/16 fixed root table like a file"
def __init__ (self, boot, fat):
self.stream = boot.stream
self.boot = boot
self.fat = fat
self.start = boot.root()
self.size = 32*boot.wMaxRootEntries
self.pos = 0 # virtual stream linear pos
def __str__ (self):
return "Fixed root @%Xh" % self.start
def tell(self): return self.pos
def realtell(self):
return self.stream.tell()
def seek(self, offset, whence=0):
if whence == 1:
pos = self.pos + offset
elif whence == 2:
if self.size:
pos = self.size + offset
else:
pos = offset
if pos > self.size:
if DEBUG&4: log("Attempt to seek @%Xh past fixed root end @%Xh", pos, self.size)
return
self.pos = pos
if DEBUG&4: log("FixedRoot: seeking @%Xh (@%Xh)", pos, self.start+pos)
self.stream.seek(self.start+pos)
def read(self, size=-1):
if DEBUG&4: log("FixedRoot: read(%d) called from offset %Xh", size, self.pos)
self.seek(self.pos)
# If negative size, adjust
if size < 0:
size = 0
if self.size: size = self.size
# If requested size is greater than file size, limit to the latter
if self.size and self.pos + size > self.size:
size = self.size - self.pos
buf = bytearray()
if not size: return buf
buf += self.stream.read(size)
self.pos += size
return buf
def write(self, s):
if DEBUG&4: log("FixedRoot: writing %d bytes at offset %Xh", len(s), self.pos)
self.seek(self.pos)
if self.pos + len(s) > self.size:
return
self.stream.write(s)
self.pos += len(s)
self.seek(self.pos)
def trunc(self):
return 0
def frags(self):
pass
class Handle(object):
"Manage an open table slot"
def __init__ (self):
self.IsValid = False # determines whether update or not on disk
self.File = None # file contents
self.Entry = None # direntry slot
self.Dir = None #dirtable owning the handle
self.IsReadOnly = True # use this to prevent updating a Direntry on a read-only filesystem
#~ atexit.register(self.close) # forces close() on exit if user didn't call it
def __del__ (self):
self.close()
def update_time(self, i=0):
cdate, ctime = FATDirentry.GetDosDateTime()
if i == 0:
self.Entry.wADate = cdate
elif i == 1:
self.Entry.wMDate = cdate
self.Entry.wMTime = ctime
def tell(self):
return self.File.tell()
def seek(self, offset, whence=0):
self.File.seek(offset, whence)
self.Entry.dwFileSize = self.File.filesize
self.Dir._update_dirtable(self.Entry)
def read(self, size=-1):
self.update_time()
return self.File.read(size)
def write(self, s):
self.File.write(s)
self.update_time(1)
self.IsReadOnly = False
self.Entry.dwFileSize = self.File.filesize
self.Dir._update_dirtable(self.Entry)
# NOTE: FAT permits chains with more allocated clusters than those required by file size!
# Distinguish a ftruncate w/deallocation and update Chain.__init__ and Handle flushing accordingly!
def ftruncate(self, length, free=0):