Debian Codegraph @

src/intel_hex.c

raw
1 /*
2 * dfu-programmer
3 *
4 * intel_hex.c
5 *
6 * This reads in a .hex file (Intel format), creates an array representing
7 * memory, populates the array with the data from the .hex file, and
8 * returns the array.
9 *
10 * This implementation is based completely on San Bergmans description
11 * of this file format, last updated on 23 August, 2005.
12 *
13 * http://www.sbprojects.com
14 * In the "Knowledge Base" section.
15 *
16 * $Id$
17 *
18 * This program is free software; you can redistribute it and/or modify
19 * it under the terms of the GNU General Public License as published by
20 * the Free Software Foundation; either version 2 of the License, or
21 * (at your option) any later version.
22 *
23 * This program is distributed in the hope that it will be useful,
24 * but WITHOUT ANY WARRANTY; without even the implied warranty of
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26 * GNU General Public License for more details.
27 *
28 * You should have received a copy of the GNU General Public License
29 * along with this program; if not, write to the Free Software
30 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
31 */
32
33 #define _GNU_SOURCE
34 #include <stdio.h>
35 #include <stdint.h>
36 #include <stdlib.h>
37 #include <string.h>
38
39 #include "intel_hex.h"
40 #include "util.h"
41
42 struct intel_record {
43 uint8_t count; // single byte count
44 uint8_t type; // single byte type
45 uint16_t address; // two byte address
46 uint8_t checksum; // single byte checksum
47 uint8_t data[256];
48 };
49
50 #define IHEX_COLS 16
51 #define IHEX_64KB_PAGE 0x10000
52
53
54 #define IHEX_DEBUG_THRESHOLD 50
55 #define IHEX_TRACE_THRESHOLD 55
56
57 #define DEBUG(...) dfu_debug( __FILE__, __FUNCTION__, __LINE__, \
58 IHEX_DEBUG_THRESHOLD, __VA_ARGS__ )
59 #define TRACE(...) dfu_debug( __FILE__, __FUNCTION__, __LINE__, \
60 IHEX_TRACE_THRESHOLD, __VA_ARGS__ )
61
62 // ________ P R O T O T Y P E S _______________________________
63 static int intel_validate_checksum( struct intel_record *record );
64 /* This walks over the record and ensures that the checksum is
65 * correct for the record.
66 *
67 * returns 0 if checksum validates, anything else on error
68 */
69
70 static int32_t ihex_make_line( struct intel_record *record, char *str );
71 /* provide record type a list of values, they are converted into a line and put at str
72 * values are 2 address bytes, the record type and any values. A checksum
73 * is added to the end and the line length is prepended.
74 */
75
76 static int32_t ihex_make_checksum( struct intel_record *record );
77 /* make a checksum using the values in record, place it in the record and
78 * return 0
79 */
80
81 static int32_t ihex_make_record_04_offset( uint32_t offset, char *str );
82 /* make an 04 record type offset, where the desired offset address is found by
83 * multiplying value by 0x1000 (or the 64kb page size). Therefore, the given
84 * offset value must be a clean multiple of 0x10000. the offset value
85 * is placed in the buffer at str
86 */
87
88 //static int32_t ihex_process_record( struct intel_record *record,
89 // const uint8_t job, uint32_t next_address );
90 /* call this function when a record needs to be processed (specify w/ job)
91 * and a new blank record needs to be created
92 */
93
94 static void ihex_clear_record( struct intel_record *record, uint32_t address );
95 /* wipes out a record (resets it to zero)
96 */
97
98
99 // ________ F U N C T I O N S _______________________________
100 static int intel_validate_checksum( struct intel_record *record ) {
101 int i = 0;
102 int checksum = 0;
103
104 checksum = record->count + record->type + record->checksum +
105 (record->address >> 8) + (0xff & record->address);
106
107 for( i = 0; i < record->count; i++ ) {
108 checksum += record->data[i];
109 }
110
111 return (0xff & checksum);
112 }
113
114 static int intel_validate_line( struct intel_record *record ) {
115 /* Validate the checksum */
116 if( 0 != intel_validate_checksum(record) ) {
117 DEBUG( "Checksum error.\n" );
118 return -1;
119 }
120
121 /* Validate the type */
122 switch( record->type ) {
123 /* Intel 1 format, for up to 64K length (types 0, 1) */
124 case 0: /* data record */
125 /* Nothing to do. */
126 break;
127
128 case 1: /* EOF record */
129 if( 0 != record->count ) {
130 DEBUG( "EOF record error.\n" );
131 return -2;
132 }
133 break;
134
135 /* Intel 2 format, when 20 bit addresses are needed (types 2, 3, 4) */
136 case 2: /* extended address record */
137 if( (0 != record->address)
138 || (2 != record->count)
139 || (record->data[1] != (0xf8 & record->data[1])) )
140 {
141 DEBUG( "Intel2 Format Error.\n" );
142 return -3;
143 }
144 break;
145
146 case 3: /* start address record */
147 /* just ignore these records (could verify addr == 0) */
148 break;
149
150 case 4: /* extended linear address record */
151 if( (0 != record->address) || (2 != record->count) ) {
152 DEBUG( "Extended Linear Address Record Format Error" );
153 return -4;
154 }
155 break;
156
157 case 5: /* start linear address record */
158 if( (0 != record->address) || (4 != record->count) ) {
159 return -6;
160 }
161 break;
162
163 default:
164 fprintf( stderr, "Unsupported type. %d\n", record->type );
165 /* Type 5 and other types are unsupported. */
166 return -5;
167 }
168
169 return 0;
170 }
171
172 static int intel_read_data( FILE *fp, struct intel_record *record ) {
173 int i;
174 int c;
175 int status;
176 char buffer[10];
177 int addr_upper;
178 int addr_lower;
179 int count;
180 int type;
181 int data;
182 int checksum;
183
184 // cSpell:ignore bbaaaarr
185 /* read in the ':bbaaaarr'
186 * bb - byte count
187 * aaaa - the address in memory
188 * rr - record type
189 */
190
191 if( NULL == fgets(buffer, 10, fp) ) return -1;
192 status = sscanf( buffer, ":%02x%02x%02x%02x", &count,
193 &addr_upper, &addr_lower, &type );
194 if( 4 != status ) return -2;
195
196 record->count = (uint8_t) count;
197 record->address = (uint16_t) (addr_upper << 8 | addr_lower);
198 record->type = (uint8_t) type;
199
200 /* Read the data */
201 for( i = 0; i < record->count; i++ ) {
202 if( NULL == fgets(buffer, 3, fp) ) return -3;
203 if( 1 != sscanf(buffer, "%02x", &data) ) return -4;
204
205 record->data[i] = (uint8_t) (0xff & data);
206 }
207
208 /* Read the checksum */
209 if( NULL == fgets(buffer, 3, fp) ) return -5;
210 if( 1 != sscanf(buffer, "%02x", &checksum) ) return -6;
211
212 /* Chomp the [\r]\n */
213 c = fgetc( fp );
214 if( '\r' == c ) {
215 c = fgetc( fp );
216 }
217 if( '\n' != c ) {
218 DEBUG( "Error: end of line != \\n.\n" ); return -7;
219 }
220 record->checksum = (uint8_t) checksum;
221
222 return 0;
223 }
224
225 static void intel_invalid_addr_warning(uint32_t line_count, uint32_t address,
226 uint32_t target_offset, size_t total_size) {
227 DEBUG("Valid address region from 0x%X to 0x%X.\n",
228 target_offset, target_offset + total_size - 1);
229 fprintf( stderr,
230 "WARNING (line %u): 0x%02x address outside valid region,\n",
231 line_count, address);
232 fprintf( stderr,
233 " suppressing additional address error messages.\n" );
234 }
235
236 int32_t intel_process_data( intel_buffer_out_t *bout, char value,
237 uint32_t target_offset, uint32_t address) {
238 /* NOTE : there are some hex program files that contain data in the user
239 * page, which is outside of 'valid' memory. In this situation, the hex
240 * file is processed and used as normal with a warning message containing
241 * the first line with an invalid address.
242 */
243 uint32_t raddress; // relative address = address - target offset
244 // cSpell:ignore raddress
245
246 // The Atmel flash page starts at address 0x8000 0000, we need to ignore
247 // stm32 flash page starts at 0x0800 0000
248 // that bit
249 target_offset &= 0x7fffffff;
250 address &= 0x7fffffff;
251
252 if( (address < target_offset) ||
253 (address > target_offset + bout->info.total_size - 1) ) {
254 DEBUG( "Address 0x%X is outside valid range 0x%X to 0x%X.\n",
255 address, target_offset,
256 target_offset + bout->info.total_size - 1 );
257 return -1;
258 } else {
259 raddress = address - target_offset;
260 // address >= target_offset so unsigned '-' is OK
261 bout->data[raddress] = (uint16_t) (0xff & value);
262 // update data limits
263 if( raddress < bout->info.data_start ) {
264 bout->info.data_start = raddress;
265 }
266 if( raddress > bout->info.data_end ) {
267 bout->info.data_end = raddress;
268 }
269 }
270 return 0;
271 }
272
273 int32_t intel_hex_to_buffer( char *filename, intel_buffer_out_t *bout,
274 uint32_t target_offset, bool quiet ) {
275 FILE *fp = NULL;
276 struct intel_record record;
277 // unsigned int count, type, checksum, address; char data[256]
278 uint32_t address = 0; // line address for intel_hex
279 uint32_t address_offset = 0;// offset address from intel_hex
280 uint32_t line_count = 1; // used for debugging hex file
281 int32_t invalid_address_count = 0; // used for error checking
282 int32_t retval; // return value
283 int i = 0;
284
285 if ( (0 >= bout->info.total_size) ) {
286 DEBUG( "Must provide valid memory size in bout.\n" );
287 retval = -1;
288 goto error;
289 }
290
291 if (NULL == filename) {
292 if( !quiet ) fprintf( stderr, "Invalid filename.\n" );
293 retval = -2;
294 goto error;
295 }
296
297 if( 0 == strcmp("STDIN", filename) ) {
298 fp = stdin;
299 } else {
300 fp = fopen( filename, "r" );
301 if( NULL == fp ) {
302 if( !quiet ) fprintf( stderr, "Error opening %s\n", filename );
303 retval = -3;
304 goto error;
305 }
306 }
307
308 // iterate through ihex file and assign values to memory and user
309 do {
310 // read the data
311 if( 0 != intel_read_data(fp, &record) ) {
312 if( !quiet )
313 fprintf( stderr, "Error reading line %u.\n", line_count );
314 retval = -4;
315 goto error;
316 } else if ( 0 != intel_validate_line( &record ) ) {
317 if( !quiet )
318 fprintf( stderr, "Error: Line %u does not validate.\n", line_count );
319 retval = -5;
320 goto error;
321 } else
322 line_count++;
323
324 // process the data
325 switch( record.type ) {
326 case 0:
327 for( address = address_offset + ((uint32_t) record.address),
328 i = 0; i < record.count; i++, address++ ) {
329 if ( 0 != intel_process_data(bout, record.data[i],
330 target_offset, address) ) {
331 // address was invalid
332 if ( !invalid_address_count ) {
333 intel_invalid_addr_warning(line_count, address,
334 target_offset, bout->info.total_size );
335 }
336 invalid_address_count++;
337 }
338 }
339 break;
340 case 2: // 0x1238 -> 0x00012380
341 address_offset = (((uint32_t) record.data[0]) << 12) |
342 ((uint32_t) record.data[1]) << 4;
343 address_offset = (0x7fffffff & address_offset);
344 DEBUG( "Address offset set to 0x%x.\n", address_offset );
345 break;
346 case 4: // 0x1234 -> 0x12340000
347 address_offset = (((uint32_t) record.data[0]) << 24) |
348 ((uint32_t) record.data[1]) << 16;
349 address_offset = (0x7fffffff & address_offset);
350 DEBUG( "Address offset set to 0x%x.\n", address_offset );
351 break;
352 case 5: // 0x12345678 -> 0x12345678
353 address_offset = (((uint32_t) record.data[0]) << 24) |
354 (((uint32_t) record.data[1]) << 16) |
355 (((uint32_t) record.data[2]) << 8) |
356 ((uint32_t) record.data[3]);
357 /* Note: In AVR32 memory map, FLASH starts at 0x80000000, but
358 * the ISP places this memory at 0. The hex file will use
359 * 0x8..., so mask off that bit. */
360 address_offset = (0x7fffffff & address_offset);
361 DEBUG( "Address offset set to 0x%x.\n", address_offset );
362 break;
363 }
364 } while( (1 != record.type) );
365
366 if ( invalid_address_count ) {
367 if( !quiet )
368 fprintf( stderr, "Total of 0x%X bytes in invalid addressed.\n",
369 invalid_address_count );
370 }
371
372 retval = invalid_address_count;
373
374 error:
375 if( NULL != fp ) {
376 fclose( fp );
377 fp = NULL;
378 }
379
380 if( retval & !quiet ) {
381 fprintf( stderr, "See --debug=%u or greater for more information.\n",
382 IHEX_DEBUG_THRESHOLD + 1 );
383 }
384
385 return retval;
386 }
387
388 // ___ CONVERT TO INTEL HEX __________________________
389 static void ihex_clear_record( struct intel_record *record, uint32_t address ) {
390 record->count = 0;
391 record->address = ((uint16_t) (address % 0xffff));
392 record->type = 0;
393 record->data[0] = 0;
394 record->checksum = 0;
395 }
396
397 static int32_t ihex_make_checksum( struct intel_record *record ) {
398 uint16_t sum = 0;
399 uint8_t i;
400 sum += record->count;
401 sum += record->type;
402 sum += (record->address & 0xff) + (0xff & (record->address >> 8));
403 for( i = 0; i < record->count; i++ ) {
404 sum += record->data[i];
405 }
406 record->checksum = ((uint8_t) (0xff & (0x100 - (0xff & sum))));
407 return 0;
408 }
409
410 static int32_t ihex_make_line( struct intel_record *record, char *str ) {
411 uint8_t i;
412 if( record->type > 5 ) {
413 DEBUG( "Record type 0x%X unknown.\n", record->type );
414 return -1;
415 } else if( record->count > IHEX_COLS ) {
416 DEBUG( "Each line must have no more than 16 values.\n" );
417 return -1;
418 }
419
420 if( record->count == 0 ) {
421 // if there is no data set the string to empty, return
422 *str = 0;
423 return 0;
424 }
425
426 ihex_make_checksum(record); // make the checksum
427
428 sprintf( str, ":%02X%04X%02X", // ':bbaaaarr'
429 record->count, record->address, record->type );
430
431 for ( i = 0; i < record->count; i++ ) {
432 sprintf( str + 9 + 2*i, "%02X", record->data[i] );
433 }
434 sprintf( str + 9 + 2*i, "%02X", record->checksum );
435
436 return 0;
437 }
438
439 static int32_t ihex_make_record_04_offset( uint32_t offset, char *str ) {
440 struct intel_record record;
441 if ( offset & 0xffff ) {
442 DEBUG( "ihex 04 type offset must be divisible by 0x%X, not 0x%X.\n",
443 0x10000, offset );
444 return -1;
445 }
446 record.type = 4;
447 record.count = 2;
448 record.address = 0;
449 record.data[0] = (uint8_t) (0xff & (offset >> 24));
450 record.data[1] = (uint8_t) (0xff & (offset >> 16));
451 return ihex_make_line( &record, str );
452 }
453
454 //static int32_t ihex_process_record( struct intel_record *record,
455 // const uint8_t job, uint32_t next_address ) {
456 // char line[80];
457 // if( record->count ) {
458 // if( 0 != ihex_make_line(record, line) ) {
459 // DEBUG( "Error making a line.\n" );
460 // return -2;
461 // } else {
462 // ihex_clear_record( record, next_address );
463 // }
464 // if( job==0 ) {
465 // fprintf( stdout, "%s\n", line );
466 // }
467 // }
468 // return 0;
469 //}
470
471 int32_t intel_hex_from_buffer( intel_buffer_in_t *buin,
472 bool force_full, uint32_t target_offset ) {
473 char line[80];
474 uint32_t offset_address = 0; // offset address written to a previous line
475 uint32_t address = 0; // relative offset from previously set addr
476 uint32_t i = buin->info.data_start;
477 uint16_t i_scan;
478 struct intel_record record;
479
480 ihex_clear_record( &record, i + target_offset );
481
482 // target_offset = 0x8000 0000 or 0x8080 0000
483 // use buin->info.data_start to buin->info.data_stop as range
484 // if target offset > page size, use process 04
485 // reasons to complete current line:
486 // last value, next page blank, last page value, #cols reached
487
488 for( i = buin->info.data_start; i <= buin->info.data_end; i++ ) {
489 address = i + target_offset;
490 if( i % buin->info.page_size == 0 && !(force_full) ) {
491 /* you are at the start of a memory page, if force_full is not set
492 * then check if there is any data on the page, if there is none,
493 * then write current line and increment to the next page
494 */
495 for( i_scan = 0; i_scan < buin->info.page_size; i_scan++ ) {
496 if( buin->data[i + i_scan] != 0xFF )
497 break;
498 }
499 if( i_scan == buin->info.page_size ) {
500 // no data found: write current, jump to next page
501 if( 0 != ihex_make_line(&record, line) ) {
502 DEBUG( "Error making a line.\n" );
503 return -2;
504 } else {
505 if( *line )
506 fprintf( stdout, "%s\n", line );
507 ihex_clear_record( &record, address + i_scan - offset_address );
508 }
509 i += buin->info.page_size - 1;
510 continue;
511 }
512 }
513 if( address - offset_address >= 0x10000 ) {
514 offset_address = (address / IHEX_64KB_PAGE) * IHEX_64KB_PAGE;
515 // complete the line, before adding this next point
516
517 if( 0 != ihex_make_line(&record, line) ) {
518 DEBUG( "Error making a line.\n" );
519 return -2;
520 } else {
521 if( *line )
522 fprintf( stdout, "%s\n", line );
523 ihex_clear_record( &record, address - offset_address );
524 }
525
526 // reset offset address
527 if( 0 != ihex_make_record_04_offset(offset_address, line) ) {
528 DEBUG( "Error making a class 4 offset.\n" );
529 return -2;
530 } else {
531 if( *line )
532 fprintf( stdout, "%s\n", line );
533 }
534 }
535 if( record.count == IHEX_COLS ) {
536 if( 0 != ihex_make_line(&record, line) ) {
537 DEBUG( "Error making a line.\n" );
538 return -2;
539 } else {
540 if( *line )
541 fprintf( stdout, "%s\n", line );
542 ihex_clear_record( &record, address - offset_address );
543 }
544 }
545 record.data[ record.count ] = buin->data[i];
546 record.count ++;
547 }
548 if( record.count ) {
549 if( 0 != ihex_make_line(&record, line) ) {
550 DEBUG( "Error making a line.\n" );
551 return -2;
552 } else {
553 if( *line )
554 fprintf( stdout, "%s\n", line );
555 ihex_clear_record( &record, address - offset_address );
556 }
557 }
558 fprintf( stdout, ":00000001FF\n" );
559
560 return 0;
561 }
562
563 int32_t intel_init_buffer_out( intel_buffer_out_t *bout,
564 size_t total_size, size_t page_size ) {
565 uint32_t i;
566 if ( !total_size || !page_size ) {
567 DEBUG("What are you thinking... size must be > 0.\n");
568 return -1;
569 }
570
571 bout->info.total_size = total_size;
572 bout->info.page_size = page_size;
573 bout->info.data_start = UINT32_MAX; // invalid data start
574 bout->info.data_end = 0;
575 bout->info.valid_start = 0;
576 bout->info.valid_end = total_size - 1;
577 bout->info.block_start = 0;
578 bout->info.block_end = 0;
579 // allocate the memory
580 bout->data = (uint16_t *) malloc( total_size * sizeof(uint16_t) );
581 if( NULL == bout->data ) {
582 DEBUG( "ERROR allocating 0x%X bytes of memory.\n",
583 total_size * sizeof(uint16_t));
584 return -2;
585 }
586
587 // initialize buffer to 0xFFFF (invalid / unassigned data)
588 for( i = 0; i < total_size; i++ ) {
589 bout->data[i] = UINT16_MAX;
590 }
591 return 0;
592 }
593
594 int32_t intel_init_buffer_in( intel_buffer_in_t *buin,
595 size_t total_size, size_t page_size ) {
596 // TODO : is there a way to combine this and above? maybe typecast to an
597 // in or out buffer from a char pointer?
598 buin->info.total_size = total_size;
599 buin->info.page_size = page_size;
600 buin->info.data_start = 0;
601 buin->info.data_end = total_size - 1;
602 buin->info.valid_start = 0;
603 buin->info.valid_end = total_size - 1;
604 buin->info.block_start = 0;
605 buin->info.block_end = 0;
606
607 buin->data = (uint8_t *) malloc( total_size );
608 if( NULL == buin->data ) {
609 DEBUG( "ERROR allocating 0x%X bytes of memory.\n", total_size );
610 return -2;
611 }
612
613 // initialize buffer to 0xFF (blank / unassigned data)
614 memset( buin->data, UINT8_MAX, total_size );
615
616 return 0;
617 }
618
619 int32_t intel_validate_buffer( intel_buffer_in_t *buin,
620 intel_buffer_out_t *bout,
621 bool quiet) {
622 int32_t i;
623 int32_t invalid_data_region = 0;
624 int32_t invalid_outside_data_region = 0;
625
626 DEBUG( "Validating image from byte 0x%X to 0x%X.\n",
627 bout->info.valid_start, bout->info.valid_end );
628
629 if( !quiet ) fprintf( stderr, "Validating... " );
630 for( i = bout->info.valid_start; i <= bout->info.valid_end; i++ ) {
631 if( bout->data[i] <= UINT8_MAX ) {
632 // Memory should have been programmed here
633 if( ((uint8_t) bout->data[i]) != buin->data[i] ) {
634 if ( !invalid_data_region ) {
635 if( !quiet ) fprintf( stderr, "ERROR\n" );
636 DEBUG( "Image did not validate at byte: 0x%X of 0x%X.\n", i,
637 bout->info.valid_end - bout->info.valid_start + 1 );
638 DEBUG( "Wanted 0x%02x but read 0x%02x.\n",
639 0xff & bout->data[i], buin->data[i] );
640 DEBUG( "suppressing additional warnings.\n");
641 }
642 invalid_data_region++;
643 }
644 } else {
645 // Memory should be blank here
646 if( 0xff != buin->data[i] ) {
647 if ( !invalid_data_region ) {
648 DEBUG( "Outside program region: byte 0x%X expected 0xFF.\n", i);
649 DEBUG( "but read 0x%02X. suppressing additional warnings.\n",
650 buin->data[i] );
651 }
652 invalid_outside_data_region++;
653 }
654 }
655 }
656
657 if( !quiet ) {
658 if ( 0 == invalid_data_region + invalid_outside_data_region ) {
659 fprintf( stderr, "Success\n" );
660 } else {
661 fprintf( stderr,
662 "%d invalid bytes in program region, %d outside region.\n",
663 invalid_data_region, invalid_outside_data_region );
664 }
665 }
666
667 return invalid_data_region ?
668 -1 * invalid_data_region : invalid_outside_data_region;
669 }
670
671 int32_t intel_flash_prep_buffer( intel_buffer_out_t *bout ) {
672 uint16_t *page;
673 int32_t i;
674
675 TRACE( "%s( %p )\n", __FUNCTION__, bout );
676
677 // increment pointer by page_size * sizeof(int16) until page_start >= end
678 for( page = bout->data;
679 page < &bout->data[bout->info.valid_end];
680 page = &page[bout->info.page_size] ) {
681 // check if there is valid data on this page
682 for( i = 0; i < bout->info.page_size; i++ ) {
683 if( page[i] <= UINT8_MAX )
684 break;
685 }
686
687 if( bout->info.page_size != i ) {
688 /* There was valid data in the block & we need to make
689 * sure there is no unassigned data. */
690 for( i = 0; i < bout->info.page_size; i++ ) {
691 if( page[i] > UINT8_MAX )
692 page[i] = 0xff; // 0xff is blank
693 }
694 }
695 }
696 return 0;
697 }