~thestr4ng3r/mymcplus

ref: c08e07fd6ca3ede3a3530e2bf2ba59fcc9d8f91d mymcplus/mymcplus/ps2mc_ecc.py -rw-r--r-- 4.9 KiB
c08e07fdFlorian Märkl Version 3.0.3 1 year, 1 month ago
                                                                                
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
#
# This file is part of mymc+, based on mymc by Ross Ridge.
#
# mymc+ is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# mymc+ is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with mymc+.  If not, see <http://www.gnu.org/licenses/>.
#

"""
Routines for calculating the Hamming codes, a simple form of error
correcting codes (ECC), as used on PS2 memory cards.  
"""

import array

from .round import div_round_up

__ALL__ = ["ECC_CHECK_OK", "ECC_CHECK_CORRECTED", "ECC_CHECK_FAILED",
           "ecc_calculate", "ecc_check", "ecc_calculate_page", "ecc_check_page"]

ECC_CHECK_OK = 0
ECC_CHECK_CORRECTED = 1
ECC_CHECK_FAILED = 2


def _popcount(a):
    count = 0
    while a != 0:
        a &= a - 1
        count += 1
    return count


def _parityb(a):
    a = (a ^ (a >> 1))
    a = (a ^ (a >> 2))
    a = (a ^ (a >> 4))
    return a & 1


def _make_ecc_tables():
    parity_table = [_parityb(b) for b in range(256)]
    cpmasks = [0x55, 0x33, 0x0F, 0x00, 0xAA, 0xCC, 0xF0]

    column_parity_masks = [None] * 256
    for b in range(256):
        mask = 0
        for i in range(len(cpmasks)):
            mask |= parity_table[b & cpmasks[i]] << i
            column_parity_masks[b] = mask

    return parity_table, column_parity_masks


_parity_table, _column_parity_masks = _make_ecc_tables()


def _ecc_calculate(s):
    """Calculate the Hamming code for a 128 byte long string or byte array."""

    if not isinstance(s, array.array):
        a = array.array('B')
        a.fromstring(s)
        s = a
    column_parity = 0x77
    line_parity_0 = 0x7F
    line_parity_1 = 0x7F
    for i in range(len(s)):
        b = s[i]
        column_parity ^= _column_parity_masks[b]
        if _parity_table[b]:
            line_parity_0 ^= ~i
            line_parity_1 ^= i
    return [column_parity, line_parity_0 & 0x7F, line_parity_1]


def _ecc_check(s, ecc):
    """Detect and correct any single bit errors.
    
    The parameters "s" and "ecc", the data and expected Hamming code 
    repectively, must be modifiable sequences of integers and are
    updated with the corrected values if necessary."""

    computed = ecc_calculate(s)
    if computed == ecc:
        return ECC_CHECK_OK

    #print
    #_print_bin(0, s.tostring())
    #print "computed %02x %02x %02x" % tuple(computed)
    #print "actual %02x %02x %02x" % tuple(ecc)

    # ECC mismatch

    cp_diff = (computed[0] ^ ecc[0]) & 0x77
    lp0_diff = (computed[1] ^ ecc[1]) & 0x7F
    lp1_diff = (computed[2] ^ ecc[2]) & 0x7F
    lp_comp = lp0_diff ^ lp1_diff
    cp_comp = (cp_diff >> 4) ^ (cp_diff & 0x07)

    #print "%02x %02x %02x %02x %02x" % (cp_diff, lp0_diff, lp1_diff,
    #                    lp_comp, cp_comp)

    if lp_comp == 0x7F and cp_comp == 0x07:
        print("corrected 1")
        # correctable 1 bit error in data
        s[lp1_diff] ^= 1 << (cp_diff >> 4)
        return ECC_CHECK_CORRECTED
    if ((cp_diff == 0 and lp0_diff == 0 and lp1_diff == 0)
            or _popcount(lp_comp) + _popcount(cp_comp) == 1):
        print("corrected 2")
        # correctable 1 bit error in ECC
        # (and/or one of the unused bits was set)
        ecc[0] = computed[0]
        ecc[1] = computed[1]
        ecc[2] = computed[2]
        return ECC_CHECK_CORRECTED

    # uncorrectable error
    return ECC_CHECK_FAILED


def ecc_calculate_page(page):
    """Return a list of the ECC codes for a PS2 memory card page."""
    return [ecc_calculate(page[i * 128 : i * 128 + 128])
            for i in range(div_round_up(len(page), 128))]


def ecc_check_page(page, spare):
    """Check and correct any single bit errors in a PS2 memory card page."""

    failed = False
    corrected = False

    #chunks = [(array.array('B', page[i * 128 : i * 128 + 128]),
    #       map(ord, spare[i * 3 : i * 3 + 3]))
    #      for i in range(div_round_up(len(page), 128))]

    chunks = []
    for i in range(div_round_up(len(page), 128)):
        a = array.array('B')
        a.fromstring(page[i * 128 : i * 128 + 128])
        chunks.append((a, list(spare[i * 3 : i * 3 + 3])))

    r = [ecc_check(s, ecc)
         for (s, ecc) in chunks]
    ret = ECC_CHECK_OK
    if ECC_CHECK_CORRECTED in r:
        # rebuild sector and spare from the corrected versions
        page = b"".join([a[0].tostring() for a in chunks])
        spare = bytes([a[1][i]
                       for a in chunks
                       for i in range(3)])
        ret = ECC_CHECK_CORRECTED
    if ECC_CHECK_FAILED in r:
        ret = ECC_CHECK_FAILED
    return ret, page, spare


ecc_calculate = _ecc_calculate
ecc_check = _ecc_check