-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathps2mc.py
executable file
·1985 lines (1719 loc) · 53.4 KB
/
ps2mc.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
#
# ps2mc.py
#
# By Ross Ridge
# Public Domain
#
"""Manipulate PS2 memory card images."""
_SCCS_ID = "@(#) mymc ps2mc.py 1.11 22/01/15 01:17:07\n"
import sys
import array
import struct
from errno import EACCES, ENOENT, EEXIST, ENOTDIR, EISDIR, EROFS, ENOTEMPTY,\
ENOSPC, EIO, EBUSY, EINVAL
import fnmatch
import traceback
from round import *
from ps2mc_ecc import *
from ps2mc_dir import *
import ps2save
PS2MC_MAGIC = "Sony PS2 Memory Card Format "
PS2MC_FAT_ALLOCATED_BIT = 0x80000000
PS2MC_FAT_CHAIN_END = 0xFFFFFFFF
PS2MC_FAT_CHAIN_END_UNALLOC = 0x7FFFFFFF
PS2MC_FAT_CLUSTER_MASK = 0x7FFFFFFF
PS2MC_MAX_INDIRECT_FAT_CLUSTERS = 32
PS2MC_CLUSTER_SIZE = 1024
PS2MC_INDIRECT_FAT_OFFSET = 0x2000
PS2MC_STANDARD_PAGE_SIZE = 512
PS2MC_STANDARD_PAGES_PER_CARD = 16384
PS2MC_STANDARD_PAGES_PER_ERASE_BLOCK = 16
class error(Exception):
pass
class io_error(error, IOError):
def __init__(self, *args, **kwargs):
IOError.__init__(self, *args, **kwargs)
def __str__(self):
if getattr(self, "strerror", None) == None:
return str(self.args)
if getattr(self, "filename", None) != None:
return self.filename + ": " + self.strerror
return self.strerror
class path_not_found(io_error):
def __init__(self, filename):
io_error.__init__(self, ENOENT, "path not found", filename)
class file_not_found(io_error):
def __init__(self, filename):
io_error.__init__(self, ENOENT, "file not found", filename)
class dir_not_found(io_error):
def __init__(self, filename):
io_error.__init__(self, ENOENT, "directory not found",
filename)
class dir_index_not_found(io_error, IndexError):
def __init__(self, filename, index):
msg = "index (%d) past of end of directory" % index
io_error.__init__(self, ENOENT, msg, filename)
class corrupt(io_error):
def __init__(self, msg, f = None):
filename = None
if f != None:
filename = getattr(f, "name")
io_error.__init__(self, EIO, msg, filename)
class ecc_error(corrupt):
def __init__(self, msg, filename = None):
corrupt.__init__(self, msg, filename)
if sys.byteorder == "big":
def unpack_32bit_array(s):
a = array.array('I', s)
a.byteswap()
return a
def pack_32bit_array(a):
a = a[:]
a.byteswap()
return a.tostring()
else:
def unpack_32bit_array(s):
#if isinstance(s, str):
# a = array.array('L')
# a.fromstring(s)
# return a
return array.array('I', s)
def pack_32bit_array(a):
return a.tostring()
def unpack_superblock(s):
sb = struct.unpack("<28s12sHHHHLLLLLL8x128s128sbbxx", s)
sb = list(sb)
sb[12] = unpack_32bit_array(sb[12])
sb[13] = unpack_32bit_array(sb[13])
return sb
def pack_superblock(sb):
sb = list(sb)
sb[12] = pack_32bit_array(sb[12])
sb[13] = pack_32bit_array(sb[13])
return struct.pack("<28s12sHHHHLLLLLL8x128s128sbbxx", *sb)
unpack_fat = unpack_32bit_array
pack_fat = pack_32bit_array
def pathname_split(pathname):
if pathname == "":
return (None, False, False)
components = pathname.split("/")
return ([name
for name in components
if name != ""],
components[0] != "",
components[-1] == "")
class lru_cache(object):
def __init__(self, length):
self._lru_list = [[i - 1, None, None, i + 1]
for i in range(length + 1)]
self._index_map = {}
def dump(self):
lru_list = self._lru_list
i = 0
while i != len(self._lru_list):
print "%d: %s, " % (i, str(lru_list[i][1])),
i = lru_list[i][3]
print
print self._index_map
def _move_to_front(self, i):
lru_list = self._lru_list
first = lru_list[0]
i2 = first[3]
if i != i2:
elt = lru_list[i]
prev = lru_list[elt[0]]
next = lru_list[elt[3]]
prev[3] = elt[3]
next[0] = elt[0]
elt[0] = 0
elt[3] = i2
lru_list[i2][0] = i
first[3] = i
def add(self, key, value):
lru_list = self._lru_list
index_map = self._index_map
ret = None
if key in index_map:
i = index_map[key]
# print "add hit ", key, i
elt = lru_list[i]
else:
# print "add miss", key
i = lru_list[-1][0]
elt = lru_list[i]
old_key = elt[1]
if old_key != None:
del index_map[old_key]
ret = (old_key, elt[2])
index_map[key] = i
elt[1] = key
elt[2] = value
self._move_to_front(i)
return ret
def get(self, key, default = None):
i = self._index_map.get(key)
if i == None:
# print "get miss", key
return default
# print "get hit ", key, i
ret = self._lru_list[i][2]
self._move_to_front(i)
return ret
def items(self):
return [(elt[1], elt[2])
for elt in self._lru_list[1 : -1]
if elt[2] != None]
class fat_chain(object):
"""A class for accessing a file's FAT entries as a simple sequence."""
def __init__(self, lookup_fat, first):
self.lookup_fat = lookup_fat
self._first = first
self.offset = 0
self._prev = None
self._cur = first
def __getitem__(self, i):
# not iterable
offset = self.offset
if i == offset:
# print "@@@ fat_chain[] cur:", i, self._cur
return self._cur
elif i == offset - 1:
assert self._prev != None
# print "@@@ fat_chain[] prev:", i, self._prev
return self._prev
if i < offset:
if i == 0:
# print "@@@ fat_chain[] first", i, self._first
return self._first
offset = 0
prev = None
cur = self._first
else:
prev = self._prev
cur = self._cur
# print "@@@ fat_chain[] distance", i - offset
while offset != i:
next = self.lookup_fat(cur)
if next == PS2MC_FAT_CHAIN_END:
break;
if next & PS2MC_FAT_ALLOCATED_BIT:
next &= ~PS2MC_FAT_ALLOCATED_BIT
else:
# corrupt
next = PS2MC_FAT_CHAIN_END
break
offset += 1
prev = cur
cur = next
self.offset = offset
self._prev = prev
self._cur = cur
# print "@@@ offset, prev, cur:", offset, prev, cur
# print "@@@ fat_chain[]", i, next
return next
def __len__(self):
old_prev = self._prev
old_cur = self._cur
old_offset = self.offset
i = self.offset
while self[i] != PS2MC_FAT_CHAIN_END:
i += 1
self._prev = old_prev
self._cur = old_cur
self.offset = old_offset
return i
class ps2mc_file(object):
"""A file-like object for accessing a file in memory card image."""
def __init__(self, mc, dirloc, first_cluster, length, mode,
name = None):
# print "ps2mc_file.__init__", name, self
self.mc = mc
self.length = length
self.first_cluster = first_cluster
self.dirloc = dirloc
self.fat_chain = None
self._pos = 0
self.buffer = None
self.buffer_cluster = None
self.softspace = 0
if name == None:
self.name = "<ps2mc_file>"
else:
self.name = name
self.closed = False
if mode == None or len(mode) == 0:
mode = "rb"
self.mode = mode
self._append = False
self._write = False
if mode[0] == "a":
self._append = True
elif mode[0] != "w" or ("+" not in self.mode):
self._write = True
def _find_file_cluster(self, n):
if self.fat_chain == None:
self.fat_chain = self.mc.fat_chain(self.first_cluster)
return self.fat_chain[n]
def read_file_cluster(self, n):
if n == self.buffer_cluster:
return self.buffer
cluster = self._find_file_cluster(n)
# print "@@@ read_file_cluster", self.dirloc, n, cluster, repr(self.name)
if cluster == PS2MC_FAT_CHAIN_END:
return None
self.buffer = self.mc.read_allocatable_cluster(cluster)
self.buffer_cluster = n
return self.buffer
def _extend_file(self, n):
mc = self.mc
cluster = mc.allocate_cluster()
# print "@@@ extending file", n, cluster
if cluster == None:
return None
if n == 0:
self.first_cluster = cluster
self.fat_chain = None
# print "@@@ linking", self.dirloc, "->", cluster
mc.update_dirent(self.dirloc, self, cluster,
None, False)
else:
prev = self.fat_chain[n - 1]
# print "@@@ linking", prev, "->", cluster
mc.set_fat(prev, cluster | PS2MC_FAT_ALLOCATED_BIT)
return cluster
def write_file_cluster(self, n, buf):
mc = self.mc
cluster = self._find_file_cluster(n)
if cluster != PS2MC_FAT_CHAIN_END:
mc.write_allocatable_cluster(cluster, buf)
self.buffer = buf
self.buffer_cluster = n
return True
cluster_size = mc.cluster_size
file_cluster_end = div_round_up(self.length, cluster_size)
if (cluster < file_cluster_end
or len(self.fat_chain) != file_cluster_end):
raise corrupt, ("file length doesn't match cluster"
" chain length", mc.f)
for i in range(file_cluster_end, n):
cluster = self._extend_file(i)
if cluster == None:
if i != file_cluster_end:
self.length = (i - 1) * cluster_size
mc.update_dirent(self.dirloc, self,
None, self.length,
True)
return False
mc.write_allocatable_cluster(cluster,
["\0"] * cluster_size)
cluster = self._extend_file(n)
if cluster == None:
return False
mc.write_allocatable_cluster(cluster, buf)
self.buffer = buf
self.buffer_cluster = n
return True
def update_notify(self, first_cluster, length):
if self.first_cluster != first_cluster:
self.first_cluster = first_cluster
self.fat_chain = None
self.length = length
self.buffer = None
self.buffer_cluster = None
def read(self, size = None, eol = None):
if self.closed:
raise ValueError, "file is closed"
pos = self._pos
cluster_size = self.mc.cluster_size
if size == None:
size = self.length
size = max(min(self.length - pos, size), 0)
ret = ""
while size > 0:
off = pos % cluster_size
l = min(cluster_size - off, size)
buf = self.read_file_cluster(pos / cluster_size)
if buf == None:
break
if eol != None:
i = buf.find(eol, off, off + l)
if i != -1:
l = off - i + 1
size = l
pos += l
self._pos = pos
ret += buf[off : off + l]
size -= l
return ret
def write(self, out, _set_modified = True):
if self.closed:
raise ValueError, "file is closed"
cluster_size = self.mc.cluster_size
pos = self._pos
if self._append:
pos = self.length
elif not self._write:
raise io_error, (EACCES, "file not opened for writing",
self.name)
size = len(out)
# print "@@@ write", pos, size
i = 0
while size > 0:
cluster = pos / cluster_size
off = pos % cluster_size
l = min(cluster_size - off, size)
s = out[i : i + l]
pos += l
if l == cluster_size:
buf = s
else:
buf = self.read_file_cluster(cluster)
if buf == None:
buf = "\0" * cluster_size
buf = buf[:off] + s + buf[off + l:]
if not self.write_file_cluster(cluster, buf):
raise io_error, (ENOSPC,
"out of space on image",
self.name)
self._pos = pos
# print "@@@ pos", pos
new_length = None
if pos > self.length:
new_length = self.length = pos
self.mc.update_dirent(self.dirloc, self, None,
new_length, _set_modified)
i += l
size -= l
def close(self):
# print "ps2mc_file.close", self.name, self
if self.mc != None:
self.mc.notify_closed(self.dirloc, self)
self.mc = None
self.fat_chain = None
self.buffer = None
def next(self):
r = self.readline()
if r == "":
raise StopIteration
return r
def readline(self, size = None):
return self.read(size, "\n")
def readlines(self, sizehint):
return [line for line in self]
def seek(self, offset, whence = 0):
if self.closed:
raise ValueError, "file is closed"
if whence == 1:
base = self._pos
elif whence == 2:
base = self.length
else:
base = 0
pos = max(base + offset, 0)
self._pos = pos
def tell(self):
if self.closed:
raise ValueError, "file is closed"
return self._pos
def __enter__(self):
return
def __exit__(self, a, b, c):
self.close()
return
# def __del__(self):
# # print "ps2mc_file.__del__", self
# if self.mc != None:
# self.mc.notify_closed(self.dirloc, self)
# self.mc = None
# self.fat_chain = None
class ps2mc_directory(object):
"""A sequence and iterator object for directories."""
def __init__(self, mc, dirloc, first_cluster, length,
mode = "rb", name = None):
self.f = ps2mc_file(mc, dirloc, first_cluster,
length * PS2MC_DIRENT_LENGTH, mode, name)
def __iter__(self):
start = self.tell()
if start != 0:
start -= 1
self.seek(start)
self._iter_end = start
return self
def write_raw_ent(self, index, ent, set_modified):
# print "@@@ write_raw_ent", index
self.seek(index)
self.f.write(pack_dirent(ent),
_set_modified = set_modified)
def next(self):
# print "@@@ next", self.tell(), self.f.name
dirent = self.f.read(PS2MC_DIRENT_LENGTH)
if dirent == "":
if 0 == self._iter_end:
raise StopIteration
self.seek(0)
dirent = self.f.read(PS2MC_DIRENT_LENGTH)
elif self.tell() == self._iter_end:
raise StopIteration
return unpack_dirent(dirent)
def seek(self, offset, whence = 0):
self.f.seek(offset * PS2MC_DIRENT_LENGTH, whence)
def tell(self):
return self.f.tell() / PS2MC_DIRENT_LENGTH
def __len__(self):
return self.f.length / PS2MC_DIRENT_LENGTH
def __getitem__(self, index):
# print "@@@ getitem", index, self.f.name
self.seek(index)
dirent = self.f.read(PS2MC_DIRENT_LENGTH)
if len(dirent) != PS2MC_DIRENT_LENGTH:
raise dir_index_not_found(self.f.name, index)
return unpack_dirent(dirent)
def __setitem__(self, index, new_ent):
ent = self[index]
mode = ent[0]
if (mode & DF_EXISTS) == 0:
return
if new_ent[0] != None:
mode = ((new_ent[0] & ~(DF_FILE | DF_DIR | DF_EXISTS))
| (mode & (DF_FILE | DF_DIR | DF_EXISTS)))
ent[0] = mode
for i in [1, 3, 6, 7, 8]: # ???, created, modifed, attr
if new_ent[i] != None:
ent[i] = new_ent[i]
self.write_raw_ent(index, ent, False)
def close(self):
# print "ps2mc_directory.close", self
self.f.close()
self.f = None
def __del__(self):
# print "ps2mc_directory.__del__", self
if self.f != None:
self.f.close()
self.f = None
class _root_directory(ps2mc_directory):
"""Wrapper for the cached root directory object.
The close() method is disabled so the cached object can be reused."""
def __init__(self, mc, dirloc, first_cluster, length,
mode = "r+b", name = "/"):
ps2mc_directory.__init__(self, mc, dirloc, first_cluster,
length, mode, name)
def close(self):
pass
def real_close(self):
ps2mc_directory.close(self)
class ps2mc(object):
"""A PlayStation 2 memory card filesystem implementation.
The close() method must be called when the object is no longer needed,
otherwise cycles that can't be collected by the garbage collector
will remain."""
open_files = None
fat_cache = None
def _calculate_derived(self):
self.spare_size = div_round_up(self.page_size, 128) * 4
self.raw_page_size = self.page_size + self.spare_size
self.cluster_size = self.page_size * self.pages_per_cluster
self.entries_per_cluster = (self.page_size
* self.pages_per_cluster / 4)
limit = (min(self.good_block2, self.good_block1)
* self.pages_per_erase_block
/ self.pages_per_cluster
- self.allocatable_cluster_offset)
self.allocatable_cluster_limit = limit
def __init__(self, f, ignore_ecc = False, params = None):
self.open_files = {}
self.fat_cache = lru_cache(12)
self.alloc_cluster_cache = lru_cache(64)
self.modified = False
self.f = None
self.rootdir = None
f.seek(0)
s = f.read(0x154)
if len(s) != 0x154 or not s.startswith(PS2MC_MAGIC):
if (params == None):
raise corrupt, ("Not a PS2 memory card image",
f)
self.f = f
self.format(params)
else:
sb = unpack_superblock(s)
self.version = sb[1]
self.page_size = sb[2]
self.pages_per_cluster = sb[3]
self.pages_per_erase_block = sb[4]
self.clusters_per_card = sb[6]
self.allocatable_cluster_offset = sb[7]
self.allocatable_cluster_end = sb[8]
self.rootdir_fat_cluster = sb[9]
self.good_block1 = sb[10]
self.good_block2 = sb[11]
self.indirect_fat_cluster_list = sb[12]
self.bad_erase_block_list = sb[13]
self._calculate_derived()
self.f = f
self.ignore_ecc = False
try:
self.read_page(0)
self.ignore_ecc = ignore_ecc
except ecc_error:
# the error might be due the fact the file
# image doesn't contain ECC data
self.spare_size = 0
self.raw_page_size = self.page_size
ignore_ecc = True
# sanity check
root = self._directory(None, 0, 1)
dot = root[0]
dotdot = root[1]
root.close()
if (dot[8] != "." or dotdot[8] != ".."
or not mode_is_dir(dot[0]) or not mode_is_dir(dotdot[0])):
raise corrupt, "Root directory damaged."
self.fat_cursor = 0
self.curdir = (0, 0)
def write_superblock(self):
s = pack_superblock((PS2MC_MAGIC,
self.version,
self.page_size,
self.pages_per_cluster,
self.pages_per_erase_block,
0xFF00,
self.clusters_per_card,
self.allocatable_cluster_offset,
self.allocatable_cluster_end,
self.rootdir_fat_cluster,
self.good_block1,
self.good_block2,
self.indirect_fat_cluster_list,
self.bad_erase_block_list,
2,
0x2B))
s += "\x00" * (self.page_size - len(s))
self.write_page(0, s)
page = "\xFF" * self.raw_page_size
self.f.seek(self.good_block2 * self.pages_per_erase_block
* self.raw_page_size)
for i in range(self.pages_per_erase_block):
self.f.write(page)
self.modified = False
return
def format(self, params):
"""Create (format) a new memory card image."""
(with_ecc, page_size,
pages_per_erase_block, param_pages_per_card) = params
if pages_per_erase_block < 1:
raise error, ("invalid pages per erase block (%d)"
% page_size)
pages_per_card = round_down(param_pages_per_card,
pages_per_erase_block)
cluster_size = PS2MC_CLUSTER_SIZE
pages_per_cluster = cluster_size / page_size
clusters_per_erase_block = (pages_per_erase_block
/ pages_per_cluster)
erase_blocks_per_card = pages_per_card / pages_per_erase_block
clusters_per_card = pages_per_card / pages_per_cluster
epc = cluster_size / 4
if (page_size < PS2MC_DIRENT_LENGTH
or pages_per_cluster < 1
or pages_per_cluster * page_size != cluster_size):
raise error, "invalid page size (%d)" % page_size
good_block1 = erase_blocks_per_card - 1
good_block2 = erase_blocks_per_card - 2
first_ifc = div_round_up(PS2MC_INDIRECT_FAT_OFFSET,
cluster_size)
allocatable_clusters = clusters_per_card - (first_ifc + 2)
fat_clusters = div_round_up(allocatable_clusters, epc)
indirect_fat_clusters = div_round_up(fat_clusters, epc)
if indirect_fat_clusters > PS2MC_MAX_INDIRECT_FAT_CLUSTERS:
indirect_fat_clusters = PS2MC_MAX_INDIRECT_FAT_CLUSTERS
fat_clusters = indirect_fat_clusters * epc
allocatable_clusters = fat_clusters * epc
allocatable_cluster_offset = (first_ifc
+ indirect_fat_clusters
+ fat_clusters)
allocatable_cluster_end = (good_block2
* clusters_per_erase_block
- allocatable_cluster_offset)
if allocatable_cluster_end < 1:
raise error, ("memory card image too small"
" to be formatted")
ifc_list = unpack_fat("\0\0\0\0"
* PS2MC_MAX_INDIRECT_FAT_CLUSTERS)
for i in range(indirect_fat_clusters):
ifc_list[i] = first_ifc + i
self.version = "1.2.0.0"
self.page_size = page_size
self.pages_per_cluster = pages_per_cluster
self.pages_per_erase_block = pages_per_erase_block
self.clusters_per_card = clusters_per_card
self.allocatable_cluster_offset = allocatable_cluster_offset
self.allocatable_cluster_end = allocatable_clusters
self.rootdir_fat_cluster = 0
self.good_block1 = good_block1
self.good_block2 = good_block2
self.indirect_fat_cluster_list = ifc_list
bebl = "\xFF\xFF\xFF\xFF" * 32
self.bad_erase_block_list = unpack_32bit_array(bebl)
self._calculate_derived()
self.ignore_ecc = not with_ecc
erased = "\0" * page_size
if not with_ecc:
self.spare_size = 0
else:
ecc = "".join(["".join(map(chr, s))
for s in ecc_calculate_page(erased)])
erased += ecc + "\0" * (self.spare_size - len(ecc))
self.f.seek(0)
for page in range(pages_per_card):
self.f.write(erased)
self.modified = True
first_fat_cluster = first_ifc + indirect_fat_clusters
remainder = fat_clusters % epc
for i in range(indirect_fat_clusters):
base = first_fat_cluster + i * epc
buf = unpack_fat(range(base, base + epc))
if (i == indirect_fat_clusters - 1
and remainder != 0):
del buf[remainder:]
buf.fromlist([0xFFFFFFFF] * (epc - remainder))
self._write_fat_cluster(ifc_list[i], buf)
# go through the fat backwards for better cache usage
for i in range(allocatable_clusters - 1,
allocatable_cluster_end - 1, -1):
self.set_fat(i, PS2MC_FAT_CHAIN_END)
for i in range(allocatable_cluster_end - 1, 0, -1):
self.set_fat(i, PS2MC_FAT_CLUSTER_MASK)
self.set_fat(0, PS2MC_FAT_CHAIN_END)
self.allocatable_cluster_end = allocatable_cluster_end
now = tod_now()
s = pack_dirent((DF_RWX | DF_DIR | DF_0400 | DF_EXISTS,
0, 2, now,
0, 0, now, 0, "."))
s += "\0" * (cluster_size - len(s))
self.write_allocatable_cluster(0, s)
dir = self._directory((0, 0), 0, 2, "wb", "/")
dir.write_raw_ent(1, (DF_WRITE | DF_EXECUTE | DF_DIR | DF_0400
| DF_HIDDEN | DF_EXISTS,
0, 0, now,
0, 0, now, 0, ".."), False)
dir.close()
self.flush()
def read_page(self, n):
# print "@@@ page", n
f = self.f
f.seek(self.raw_page_size * n)
page = f.read(self.page_size)
if len(page) != self.page_size:
raise corrupt, ("attempted to read past EOF"
" (page %05X)" % n, f)
if self.ignore_ecc:
return page
spare = f.read(self.spare_size)
if len(spare) != self.spare_size:
raise corrupt, ("attempted to read past EOF"
" (page %05X)" % n, f)
(status, page, spare) = ecc_check_page(page, spare)
if status == ECC_CHECK_FAILED:
raise ecc_error, ("Unrecoverable ECC error (page %d)"
% n)
return page
def write_page(self, n, buf):
f = self.f
f.seek(self.raw_page_size * n)
self.modified = True
if len(buf) != self.page_size:
raise error, ("internal error: write_page:"
" %d != %d" % (len(buf), self.page_size))
f.write(buf)
if self.spare_size != 0:
a = array.array('B')
for s in ecc_calculate_page(buf):
a.fromlist(s)
a.tofile(f)
f.write("\0" * (self.spare_size - len(a)))
def read_cluster(self, n):
pages_per_cluster = self.pages_per_cluster
cluster_size = self.cluster_size
if self.spare_size == 0:
self.f.seek(cluster_size * n)
return self.f.read(cluster_size)
n *= pages_per_cluster
if pages_per_cluster == 2:
return self.read_page(n) + self.read_page(n + 1)
return "".join(map(self.read_page,
range(n, n + pages_per_cluster)))
def write_cluster(self, n, buf):
pages_per_cluster = self.pages_per_cluster
cluster_size = self.cluster_size
if self.spare_size == 0:
self.f.seek(cluster_size * n)
if len(buf) != cluster_size:
raise error, ("internal error: write_cluster:"
" %d != %d" % (len(buf),
cluster_size))
return self.f.write(buf)
n *= pages_per_cluster
pgsize = self.page_size
for i in range(pages_per_cluster):
self.write_page(n + i, buf[i * pgsize
: i * pgsize + pgsize])
def _add_fat_cluster_to_cache(self, n, fat, dirty):
old = self.fat_cache.add(n, [fat, dirty])
if old != None:
(n, [fat, dirty]) = old
if dirty:
self.write_cluster(n, pack_fat(fat))
def _read_fat_cluster(self, n):
v = self.fat_cache.get(n)
if v != None:
# print "@@@ fat hit", n
return v[0]
# print "@@@ fat miss", n
fat = unpack_fat(self.read_cluster(n))
self._add_fat_cluster_to_cache(n, fat, False)
return fat
def _write_fat_cluster(self, n, fat):
self._add_fat_cluster_to_cache(n, fat, True)
def flush_fat_cache(self):
if self.fat_cache == None:
return
for (n, v) in self.fat_cache.items():
[fat, dirty] = v
if dirty:
self.write_cluster(n, pack_fat(fat))
v[1] = False
def _add_alloc_cluster_to_cache(self, n, buf, dirty):
old = self.alloc_cluster_cache.add(n, [buf, dirty])
if old != None:
(n, [buf, dirty]) = old
if dirty:
n += self.allocatable_cluster_offset
self.write_cluster(n, buf)
def read_allocatable_cluster(self, n):
a = self.alloc_cluster_cache.get(n)
if a != None:
# print "@@@ cache hit", n
return a[0]
# print "@@@ cache miss", n
buf = self.read_cluster(n + self.allocatable_cluster_offset)
self._add_alloc_cluster_to_cache(n, buf, False)
return buf
def write_allocatable_cluster(self, n, buf):
self._add_alloc_cluster_to_cache(n, buf, True)
def flush_alloc_cluster_cache(self):
if self.alloc_cluster_cache == None:
return
for (n, a) in self.alloc_cluster_cache.items():
[buf, dirty] = a
if dirty:
n += self.allocatable_cluster_offset
self.write_cluster(n, buf)
a[1] = False
def read_fat_cluster(self, n):
indirect_offset = n % self.entries_per_cluster
dbl_offset = n / self.entries_per_cluster
indirect_cluster = self.indirect_fat_cluster_list[dbl_offset]
indirect_fat = self._read_fat_cluster(indirect_cluster)
cluster = indirect_fat[indirect_offset]
return (self._read_fat_cluster(cluster), cluster)
def read_fat(self, n):
if n < 0 or n >= self.allocatable_cluster_end:
raise io_error, (EIO,
"FAT cluster index out of range"
" (%d)" % n)
offset = n % self.entries_per_cluster
fat_cluster = n / self.entries_per_cluster
(fat, cluster) = self.read_fat_cluster(fat_cluster)
return (fat, offset, cluster)
def lookup_fat(self, n):
(fat, offset, cluster) = self.read_fat(n)
return fat[offset]
def set_fat(self, n, value):
(fat, offset, cluster) = self.read_fat(n)
fat[offset] = value
self._write_fat_cluster(cluster, fat)
def allocate_cluster(self):
epc = self.entries_per_cluster
allocatable_cluster_limit = self.allocatable_cluster_limit
end = div_round_up(allocatable_cluster_limit, epc)
remainder = allocatable_cluster_limit % epc
while self.fat_cursor < end:
(fat, cluster) = self.read_fat_cluster(self.fat_cursor)
if (self.fat_cursor == end - 1
and remainder != 0):
n = min(fat[:remainder])
else:
n = min(fat)
if (n & PS2MC_FAT_ALLOCATED_BIT) == 0:
offset = fat.index(n)
fat[offset] = PS2MC_FAT_CHAIN_END
self._write_fat_cluster(cluster, fat)
ret = self.fat_cursor * epc + offset
# print "@@@ allocated", ret
return ret
self.fat_cursor += 1
return None
def fat_chain(self, first_cluster):
return fat_chain(self.lookup_fat, first_cluster)
def file(self, dirloc, first_cluster, length, mode, name = None):
"""Create a new file-like object for a file."""
f = ps2mc_file(self, dirloc, first_cluster, length, mode, name)
if dirloc == None:
return
open_files = self.open_files