3 * Wolfgang Denk, DENX Software Engineering, wd@denx.de.
5 * SPDX-License-Identifier: GPL-2.0+
11 static int hex1_bin (char c);
12 static int hex2_bin (char *s);
14 int srec_decode (char *input, int *count, ulong *addr, char *data)
17 int v; /* conversion buffer */
18 int srec_type; /* S-Record type */
19 unsigned char chksum; /* buffer for checksum */
23 /* skip anything before 'S', and the 'S' itself.
24 * Return error if not found
27 for (; *input; ++input) {
28 if (*input == 'S') { /* skip 'S' */
33 if (*input == '\0') { /* no more data? */
37 v = *input++; /* record type */
39 if ((*count = hex2_bin(input)) < 0) {
40 return (SREC_E_NOSREC);
46 switch (v) { /* record type */
48 case '0': /* start record */
49 srec_type = SREC_START; /* 2 byte addr field */
50 *count -= 3; /* - checksum and addr */
53 srec_type = SREC_DATA2; /* 2 byte addr field */
54 *count -= 3; /* - checksum and addr */
57 srec_type = SREC_DATA3; /* 3 byte addr field */
58 *count -= 4; /* - checksum and addr */
60 case '3': /* data record with a */
61 srec_type = SREC_DATA4; /* 4 byte addr field */
62 *count -= 5; /* - checksum and addr */
65 case '5': /* count record, addr field contains */
66 srec_type = SREC_COUNT; /* a 2 byte record counter */
67 *count = 0; /* no data */
69 /*** case '6' -- not used ***/
70 case '7': /* end record with a */
71 srec_type = SREC_END4; /* 4 byte addr field */
72 *count -= 5; /* - checksum and addr */
74 case '8': /* end record with a */
75 srec_type = SREC_END3; /* 3 byte addr field */
76 *count -= 4; /* - checksum and addr */
78 case '9': /* end record with a */
79 srec_type = SREC_END2; /* 2 byte addr field */
80 *count -= 3; /* - checksum and addr */
83 return (SREC_E_BADTYPE);
86 /* read address field */
90 case '3': /* 4 byte addr field */
92 if ((v = hex2_bin(input)) < 0) {
93 return (SREC_E_NOSREC);
99 case '2': /* 3 byte addr field */
101 if ((v = hex2_bin(input)) < 0) {
102 return (SREC_E_NOSREC);
109 case '0': /* 2 byte addr field */
113 if ((v = hex2_bin(input)) < 0) {
114 return (SREC_E_NOSREC);
121 if ((v = hex2_bin(input)) < 0) {
122 return (SREC_E_NOSREC);
131 return (SREC_E_BADTYPE);
134 /* convert data and calculate checksum */
135 for (i=0; i < *count; ++i) {
136 if ((v = hex2_bin(input)) < 0) {
137 return (SREC_E_NOSREC);
144 /* read anc check checksum */
145 if ((v = hex2_bin(input)) < 0) {
146 return (SREC_E_NOSREC);
149 if ((unsigned char)v != (unsigned char)~chksum) {
150 return (SREC_E_BADCHKS);
156 static int hex1_bin (char c)
158 if (c >= '0' && c <= '9')
160 if (c >= 'a' && c <= 'f')
161 return (c + 10 - 'a');
162 if (c >= 'A' && c <= 'F')
163 return (c + 10 - 'A');
167 static int hex2_bin (char *s)
171 if ((i = hex1_bin(*s++)) < 0) {
174 if ((j = hex1_bin(*s)) < 0) {