-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathhex.c
456 lines (388 loc) · 14.7 KB
/
hex.c
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
/****************************************************************************
File : hex.c
Description : Code for dealing with Intel hex files.
History : 2009-02-19 Phillip Burgess
* Initial implementation
2009-12-26 Thomas Fischl, Dominik Fisch (www.FundF.net)
* Ported mmap functions to windows
License : Copyright (C) 2009 Phillip Burgess
Copyright (C) 2009 Thomas Fischl, Dominik Fisch (www.FundF.net)
This file is part of 'mphidflash' program.
'mphidflash' 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.
'mphidflash' 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 'mphidflash' source code. If not,
see <http://www.gnu.org/licenses/>.
****************************************************************************/
#include <stdio.h>
#include <ctype.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#ifndef WIN
#include <sys/mman.h>
#else
#include <windows.h>
#endif
#include <sys/stat.h>
#include "mpcanflash.h"
static char *hexFileData = NULL; /* Memory-mapped hex file data */
static char *hexPlusOne; /* Saves a lot of "+1" math */
static int hexFd; /* Open hex file descriptor */
static size_t hexFileSize; /* Save for use by munmap() */
static unsigned char hexBuf[8]; /* Data read/written to CAN */
extern unsigned char *usbBuf; /* In usb code */
unsigned char bytesPerAddress = 1; /* Bytes in flash per address */
static char Flushed= 1; /* Do we need to flush buffer? */
/****************************************************************************
Function : hexSetBytesPerAddress
Description : Sets given byte width
Parameters : unsigned char Bytes per address
Returns : Nothing (void)
****************************************************************************/
void hexSetBytesPerAddress(unsigned char bytes)
{
bytesPerAddress = bytes;
}
/****************************************************************************
Function : hexOpen
Description : Open and memory-map an Intel hex file.
Parameters : char* Filename (must be non-NULL).
Returns : ErrorCode ERR_NONE Success
ERR_HEX_OPEN File not found or no read permission
ERR_HEX_STAT fstat() call failed for some reason
ERR_HEX_MMAP Memory-mapping failed
****************************************************************************/
ErrorCode hexOpen(char * const filename)
{
ErrorCode status = ERR_HEX_OPEN;
if((hexFd = open(filename,O_RDONLY)) >= 0) {
struct stat filestat;
status = ERR_HEX_STAT;
if(!fstat(hexFd,&filestat)) {
status = ERR_HEX_MMAP;
hexFileSize = filestat.st_size;
#ifndef WIN
if((hexFileData = mmap(0,hexFileSize,PROT_READ,
MAP_FILE | MAP_SHARED,hexFd,0)) != (void *)(-1)) {
hexPlusOne = &hexFileData[1];
return ERR_NONE;
}
#else
HANDLE handle;
handle = CreateFileMapping((HANDLE)_get_osfhandle(hexFd), NULL, PAGE_WRITECOPY, 0, 0, NULL);
if (handle != NULL) {
hexFileData = MapViewOfFile(handle, FILE_MAP_COPY, 0, 0, hexFileSize);
hexPlusOne = &hexFileData[1];
CloseHandle(handle);
return ERR_NONE;
}
#endif
/* Else clean up and return error code */
hexFileData = NULL;
}
(void)close(hexFd);
}
return status;
}
/* check memory address & length are in a programmable memory area, as reported by device's Bootloader */
static int verifyBlockProgrammable( unsigned int *addr, char *len )
{
int i, isA, isL, MA, ML;
for ( i = 0; i < devQuery.memBlocks; i++ )
{
// only look at programmable memory blocks
if ( !devQuery.mem[ i ].Type )
continue;
// calc if first or last address is in this block
MA = devQuery.mem[ i ].Address;
ML = devQuery.mem[ i ].Length;
isA = ( *addr >= MA ) && ( *addr < MA + ML );
isL = ( *addr + *len > MA ) && ( *addr + *len <= MA + ML );
// loop if neithe
if ( !isA && !isL )
continue;
// both addresses is fine
if ( isA && isL )
return 0;
// if only start address we adjust length to end of block
if ( isA )
*len = ( MA + ML ) - *addr;
// if only last address we adjust start to start of block
if ( isL ) {
*len = ( *addr + *len ) - MA;
*addr = MA;
}
return 0;
}
return 1;
}
/****************************************************************************
Function : atoh (inline pseudo-function)
Description : Converts two adjacent ASCII characters (representing an 8-bit
hexadecimal value) to a numeric value.
Parameters : int Index (within global hex array) to start of
input string; must contain at least two chars.
Returns : unsigned char Numeric result; 0 to 255.
Notes : Range checking of input characters is somewhat slovenly;
all input is assumed to be in the '0' to '9' and 'A' to 'F'
range. But if any such shenanigans were to occur, the line
checksum will likely catch it.
****************************************************************************/
#define atoh(pos) \
((((hexFileData[pos] <= '9') ? (hexFileData[pos] - '0') : \
(0x0a + toupper(hexFileData[pos]) - 'A')) << 4) | \
( (hexPlusOne [pos] <= '9') ? (hexPlusOne [pos] - '0') : \
(0x0a + toupper(hexPlusOne [pos]) - 'A') ))
/****************************************************************************
Function : issueBlock
Description : Send data over USB bus to device.
Parameters : unsigned int Destination address on PIC device.
char Byte count (max 56).
char Verify vs. write.
Returns : ErrorCode ERR_NONE on success, or error code as returned
from usbWrite();
****************************************************************************/
static ErrorCode issueBlock(
unsigned int addr,
char len,
char verify)
{
ErrorCode status;
#ifdef DEBUG
(void)printf("Address: %08x Len %d\n",addr,len);
#else
(void)putchar('.'); fflush(stdout);
#endif
// check device memory blocks are programmable
if ( verifyBlockProgrammable( &addr, &len ) ) {
#ifdef DEBUG
printf( "Skip data on address %04x with length %d\n", addr, len );
#endif
return ERR_NONE;
}
// length must be even
if ( len & 1 ) {
#ifdef DEBUG
printf( "Add one byte to data on address %04x with length %d\n", addr, len );
#endif
hexBuf[ (int)(len++) ] = 0xff;
}
//////////////////////////////////////////////////// KVN
int tmp = len;
if (tmp)
while (tmp != 8)
hexBuf[tmp++] = 0xFF;
/////////////////////////////////////////////////////
/* Short data packets need flushing */
if (!verify && len == 0 && !Flushed) {
DEBUGMSG("Completing");
usbBuf[0] = PROGRAM_COMPLETE;
status = usbWrite(1,0);
Flushed= 1;
return status;
}
bufWrite32(usbBuf,1,addr / bytesPerAddress);
usbBuf[5] = len;
if(verify) {
DEBUGMSG("Verifying");
usbBuf[0] = GET_DATA;
if(ERR_NONE == (status = usbWrite(6,1))) {
#ifdef DEBUG
int i;
//if(memcmp(&usbBuf[64 - len],hexBuf,len)) {
if(memcmp(&usbBuf[8],hexBuf,len)) {
(void)puts("Verify FAIL\nExpected:");
(void)printf("NA NA NA NA NA NA NA NA - ");
//for(i=0;i<(56-len);i++) (void)printf("NA ");
for(i=0;i<len;i++)
(void)printf("%02x ",hexBuf[i]);
(void)putchar('\n'); fflush(stdout);
for(i=8;i<16;i++)
(void)printf("%02x ",usbBuf[i]);
(void)putchar('\n'); fflush(stdout);
return ERR_VERIFY;
} else {
(void)puts("Verify OK");
return ERR_NONE;
}
#else
//return (memcmp(&usbBuf[64 - len],hexBuf,len) ?
return (memcmp(&usbBuf[8],hexBuf,len) ?
ERR_VERIFY : ERR_NONE);
#endif
}
} else {
DEBUGMSG("Writing");
usbBuf[0] = PROGRAM_DEVICE;
/* Regardless of actual byte count, data packet is always
64 bytes. Following the header, the bootloader wants the
data portion 'right justified' within packet. Odd. */
//memcpy(&usbBuf[64 - len],hexBuf,len);
//memcpy(&usbBuf[8],hexBuf,len); // KVN
memcpy(&usbBuf[8],hexBuf,8); // KVN
//if((ERR_NONE == (status = usbWrite(64,0))) && (len < 56))
if((ERR_NONE == (status = usbWrite(64,0))) && (len < 8)) // KVN`
{
/* Short data packets need flushing */
DEBUGMSG("Completing");
usbBuf[0] = PROGRAM_COMPLETE;
status = usbWrite(1,0);
}
// flag if external code may need to flush before next write
//Flushed= (len < 56);
Flushed = (len < 8); // KVN
}
#ifdef DEBUG
if(status != ERR_NONE) (void)puts("ERROR");
#endif
return status;
}
/****************************************************************************
Function : hexWrite
Description : Writes (and optionally verifies) currently-open hex file to
device.
Parameters : char Verify (1) vs. write (0).
Returns : ErrorCode ERR_NONE on success, else various other values as
defined in mphidflash.h.
Notes : USB device and hex file are both assumed already open and
valid; no checks performed here.
****************************************************************************/
ErrorCode hexWrite(const char verify)
{
char *ptr,pass;
ErrorCode status;
int checksum,i,end,offset;
short bufLen;
unsigned int len,type,addrHi,addrLo,addr32,addrSave;
for(pass=0;pass<=verify;pass++) {
offset = 0; /* Start at beginning of hex file */
bufLen = 0; /* Hex buffer initially empty */
addrHi = 0; /* Initial address high bits */
addrSave = 0; /* PIC start addr for hex buffer contents */
addr32 = 0;
if(pass) (void)printf("\nVerifying:");
for(;;) { /* Each line in file */
/* Line start contains length, 16-bit address and type */
if(3 != sscanf(&hexFileData[offset],":%02x%04x%02x",
&len,&addrLo,&type)) return ERR_HEX_SYNTAX;
/* Position of %02x checksum at end of line */
end = offset + 9 + len * 2;
/* Verify checksum on first (write) pass */
if(!pass) {
for(checksum = 0,i = offset + 1;i < end;
checksum = (checksum + (0x100 - atoh(i))) & 0xff,i += 2);
if(atoh(end) != checksum) return ERR_HEX_CHECKSUM;
}
/* Process different hex record types. Using if/else rather
than a switch in order to better handle EOF cases (allows
simple 'break' rather than goto or other nasties). */
if(0 == type) { /* Data record */
/* If new record address is not contiguous with prior record,
issue accumulated hex data (if any) and start anew. */
if((addrHi + addrLo) != addr32) {
// flush previous write
if(!Flushed && ERR_NONE != (status = issueBlock(addrSave,0,pass)))
return status;
addr32 = addrHi + addrLo;
if(bufLen) {
if(ERR_NONE != (status = issueBlock(addrSave,bufLen,pass)))
return status;
bufLen = 0;
}
addrSave = addr32;
}
/* Parse bytes from line into hexBuf */
for(i = offset + 9;i < end;i += 2) {
hexBuf[bufLen++] = atoh(i); /* Add to hex buffer */
/* If buffer is full, issue block and start anew */
if(sizeof(hexBuf) == bufLen) {
if(ERR_NONE != (status = issueBlock(addrSave,bufLen,pass)))
return status;
bufLen = 0;
}
/* Increment address, wraparound as per hexfile spec */
if(0xffffffff == addr32) {
/* Wraparound. If any hex data, issue and start anew. */
if(bufLen) {
if(ERR_NONE !=
(status = issueBlock(addrSave,bufLen,pass)))
return status;
bufLen = 0;
}
addr32 = 0;
} else {
addr32++;
}
/* If issueBlock() used, save new address for next block */
if(!bufLen) addrSave = addr32;
}
} else if(1 == type) { /* EOF record */
break;
} else if(4 == type) { /* Extended linear address record */
if(1 != sscanf(&hexFileData[offset+9],"%04x",&addrHi))
return ERR_HEX_SYNTAX;
addrHi <<= 16;
addr32 = addrHi;
/* Assume this means a noncontiguous address jump; issue block
and start anew. The prior noncontiguous address code should
already have this covered, but in the freak case of an
extended address record with no subsequent data, make sure
the last of the data is issued. */
// flush previous write
if(!Flushed && ERR_NONE != (status = issueBlock(addrSave,0,pass)))
return status;
if(bufLen) {
if(ERR_NONE != (status = issueBlock(addrSave,bufLen,pass)))
return status;
bufLen = 0;
}
addrSave = addr32;
} else if(5 == type) { /* Start address */
/* Ignore */
} else { /* Unsupported record type */
return ERR_HEX_RECORD;
}
/* Advance to start of next line (skip CR/LF/etc.), unless EOF */
if(NULL == (ptr = strchr(&hexFileData[end+2],':'))) break;
offset = ptr - hexFileData;
}
/* At end of file, issue any residual data (counters reset at top) */
if(bufLen &&
(ERR_NONE != (status = issueBlock(addrSave,bufLen,pass))))
return status;
/* Make sure last data is flushed */
if(!pass && !Flushed)
if(ERR_NONE != (status = issueBlock(addrSave,0,pass)))
return status;
//return issueBlock(addrSave,0,pass); // modified by KVN
#ifdef DEBUG
(void)printf("PASS %d of %d COMPLETE\n",pass,verify);
#endif
}
return ERR_NONE;
}
/****************************************************************************
Function : hexClose
Description : Unmaps and closes previously-opened hex file.
Parameters : None (void)
Returns : Nothing (void)
Notes : File is assumed to have already been successfully opened
by the time this function is called; no checks performed here.
****************************************************************************/
void hexClose(void)
{
#ifndef WIN
(void)munmap(hexFileData,hexFileSize);
#else
UnmapViewOfFile(hexFileData);
#endif
hexFileData = NULL;
(void)close(hexFd);
}