xref: /openbsd/gnu/usr.bin/binutils/bfd/ihex.c (revision 7b36286a)
1 /* BFD back-end for Intel Hex objects.
2    Copyright 1995, 1996, 1998, 1999, 2000, 2001, 2002, 2003
3    Free Software Foundation, Inc.
4    Written by Ian Lance Taylor of Cygnus Support <ian@cygnus.com>.
5 
6    This file is part of BFD, the Binary File Descriptor library.
7 
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2 of the License, or
11    (at your option) any later version.
12 
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17 
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
21 
22 /* This is what Intel Hex files look like:
23 
24 1. INTEL FORMATS
25 
26 A. Intel 1
27 
28    16-bit address-field format, for files 64k bytes in length or less.
29 
30    DATA RECORD
31    Byte 1	Header = colon(:)
32    2..3		The number of data bytes in hex notation
33    4..5		High byte of the record load address
34    6..7		Low byte of the record load address
35    8..9		Record type, must be "00"
36    10..x	Data bytes in hex notation:
37 	x = (number of bytes - 1) * 2 + 11
38    x+1..x+2	Checksum in hex notation
39    x+3..x+4	Carriage return, line feed
40 
41    END RECORD
42    Byte 1	Header = colon (:)
43    2..3		The byte count, must be "00"
44    4..7		Transfer-address (usually "0000")
45 		the jump-to address, execution start address
46    8..9		Record type, must be "01"
47    10..11	Checksum, in hex notation
48    12..13	Carriage return, line feed
49 
50 B. INTEL 2
51 
52    MCS-86 format, using a 20-bit address for files larger than 64K bytes.
53 
54    DATA RECORD
55    Byte 1	Header = colon (:)
56    2..3		The byte count of this record, hex notation
57    4..5		High byte of the record load address
58    6..7		Low byte of the record load address
59    8..9		Record type, must be "00"
60    10..x	The data bytes in hex notation:
61 	x = (number of data bytes - 1) * 2 + 11
62    x+1..x+2	Checksum in hex notation
63    x+3..x+4	Carriage return, line feed
64 
65    EXTENDED ADDRESS RECORD
66    Byte 1	Header = colon(:)
67    2..3		The byte count, must be "02"
68    4..7		Load address, must be "0000"
69    8..9		Record type, must be "02"
70    10..11	High byte of the offset address
71    12..13	Low byte of the offset address
72    14..15	Checksum in hex notation
73    16..17	Carriage return, line feed
74 
75    The checksums are the two's complement of the 8-bit sum
76    without carry of the byte count, offset address, and the
77    record type.
78 
79    START ADDRESS RECORD
80    Byte 1	Header = colon (:)
81    2..3		The byte count, must be "04"
82    4..7		Load address, must be "0000"
83    8..9		Record type, must be "03"
84    10..13	8086 CS value
85    14..17	8086 IP value
86    18..19	Checksum in hex notation
87    20..21	Carriage return, line feed
88 
89 Another document reports these additional types:
90 
91    EXTENDED LINEAR ADDRESS RECORD
92    Byte 1	Header = colon (:)
93    2..3		The byte count, must be "02"
94    4..7		Load address, must be "0000"
95    8..9		Record type, must be "04"
96    10..13	Upper 16 bits of address of subsequent records
97    14..15	Checksum in hex notation
98    16..17	Carriage return, line feed
99 
100    START LINEAR ADDRESS RECORD
101    Byte 1	Header = colon (:)
102    2..3		The byte count, must be "02"
103    4..7		Load address, must be "0000"
104    8..9		Record type, must be "05"
105    10..13	Upper 16 bits of start address
106    14..15	Checksum in hex notation
107    16..17	Carriage return, line feed
108 
109 The MRI compiler uses this, which is a repeat of type 5:
110 
111   EXTENDED START RECORD
112    Byte 1	Header = colon (:)
113    2..3		The byte count, must be "04"
114    4..7		Load address, must be "0000"
115    8..9		Record type, must be "05"
116    10..13	Upper 16 bits of start address
117    14..17	Lower 16 bits of start address
118    18..19	Checksum in hex notation
119    20..21	Carriage return, line feed
120 */
121 
122 #include "bfd.h"
123 #include "sysdep.h"
124 #include "libbfd.h"
125 #include "libiberty.h"
126 #include "safe-ctype.h"
127 
128 static void ihex_init
129   PARAMS ((void));
130 static bfd_boolean ihex_mkobject
131   PARAMS ((bfd *));
132 static INLINE int ihex_get_byte
133   PARAMS ((bfd *, bfd_boolean *));
134 static void ihex_bad_byte
135   PARAMS ((bfd *, unsigned int, int, bfd_boolean));
136 static bfd_boolean ihex_scan
137   PARAMS ((bfd *));
138 static const bfd_target *ihex_object_p
139   PARAMS ((bfd *));
140 static bfd_boolean ihex_read_section
141   PARAMS ((bfd *, asection *, bfd_byte *));
142 static bfd_boolean ihex_get_section_contents
143   PARAMS ((bfd *, asection *, PTR, file_ptr, bfd_size_type));
144 static bfd_boolean ihex_set_section_contents
145   PARAMS ((bfd *, asection *, const PTR, file_ptr, bfd_size_type));
146 static bfd_boolean ihex_write_record
147   PARAMS ((bfd *, size_t, unsigned int, unsigned int, bfd_byte *));
148 static bfd_boolean ihex_write_object_contents
149   PARAMS ((bfd *));
150 static bfd_boolean ihex_set_arch_mach
151   PARAMS ((bfd *, enum bfd_architecture, unsigned long));
152 static int ihex_sizeof_headers
153   PARAMS ((bfd *, bfd_boolean));
154 
155 /* The number of bytes we put on one line during output.  */
156 
157 #define CHUNK 16
158 
159 /* Macros for converting between hex and binary.  */
160 
161 #define NIBBLE(x)    (hex_value (x))
162 #define HEX2(buffer) ((NIBBLE ((buffer)[0]) << 4) + NIBBLE ((buffer)[1]))
163 #define HEX4(buffer) ((HEX2 (buffer) << 8) + HEX2 ((buffer) + 2))
164 #define ISHEX(x)     (hex_p (x))
165 
166 /* When we write out an ihex value, the values can not be output as
167    they are seen.  Instead, we hold them in memory in this structure.  */
168 
169 struct ihex_data_list
170 {
171   struct ihex_data_list *next;
172   bfd_byte *data;
173   bfd_vma where;
174   bfd_size_type size;
175 };
176 
177 /* The ihex tdata information.  */
178 
179 struct ihex_data_struct
180 {
181   struct ihex_data_list *head;
182   struct ihex_data_list *tail;
183 };
184 
185 /* Initialize by filling in the hex conversion array.  */
186 
187 static void
188 ihex_init ()
189 {
190   static bfd_boolean inited;
191 
192   if (! inited)
193     {
194       inited = TRUE;
195       hex_init ();
196     }
197 }
198 
199 /* Create an ihex object.  */
200 
201 static bfd_boolean
202 ihex_mkobject (abfd)
203      bfd *abfd;
204 {
205   struct ihex_data_struct *tdata;
206   bfd_size_type amt = sizeof (struct ihex_data_struct);
207 
208   tdata = (struct ihex_data_struct *) bfd_alloc (abfd, amt);
209   if (tdata == NULL)
210     return FALSE;
211 
212   abfd->tdata.ihex_data = tdata;
213   tdata->head = NULL;
214   tdata->tail = NULL;
215   return TRUE;
216 }
217 
218 /* Read a byte from a BFD.  Set *ERRORPTR if an error occurred.
219    Return EOF on error or end of file.  */
220 
221 static INLINE int
222 ihex_get_byte (abfd, errorptr)
223      bfd *abfd;
224      bfd_boolean *errorptr;
225 {
226   bfd_byte c;
227 
228   if (bfd_bread (&c, (bfd_size_type) 1, abfd) != 1)
229     {
230       if (bfd_get_error () != bfd_error_file_truncated)
231 	*errorptr = TRUE;
232       return EOF;
233     }
234 
235   return (int) (c & 0xff);
236 }
237 
238 /* Report a problem in an Intel Hex file.  */
239 
240 static void
241 ihex_bad_byte (abfd, lineno, c, error)
242      bfd *abfd;
243      unsigned int lineno;
244      int c;
245      bfd_boolean error;
246 {
247   if (c == EOF)
248     {
249       if (! error)
250 	bfd_set_error (bfd_error_file_truncated);
251     }
252   else
253     {
254       char buf[10];
255 
256       if (! ISPRINT (c))
257 	sprintf (buf, "\\%03o", (unsigned int) c);
258       else
259 	{
260 	  buf[0] = c;
261 	  buf[1] = '\0';
262 	}
263       (*_bfd_error_handler)
264 	(_("%s:%d: unexpected character `%s' in Intel Hex file\n"),
265 	 bfd_archive_filename (abfd), lineno, buf);
266       bfd_set_error (bfd_error_bad_value);
267     }
268 }
269 
270 /* Read an Intel hex file and turn it into sections.  We create a new
271    section for each contiguous set of bytes.  */
272 
273 static bfd_boolean
274 ihex_scan (abfd)
275      bfd *abfd;
276 {
277   bfd_vma segbase;
278   bfd_vma extbase;
279   asection *sec;
280   unsigned int lineno;
281   bfd_boolean error;
282   bfd_byte *buf = NULL;
283   size_t bufsize;
284   int c;
285 
286   if (bfd_seek (abfd, (file_ptr) 0, SEEK_SET) != 0)
287     goto error_return;
288 
289   abfd->start_address = 0;
290 
291   segbase = 0;
292   extbase = 0;
293   sec = NULL;
294   lineno = 1;
295   error = FALSE;
296   bufsize = 0;
297 
298   while ((c = ihex_get_byte (abfd, &error)) != EOF)
299     {
300       if (c == '\r')
301 	continue;
302       else if (c == '\n')
303 	{
304 	  ++lineno;
305 	  continue;
306 	}
307       else if (c != ':')
308 	{
309 	  ihex_bad_byte (abfd, lineno, c, error);
310 	  goto error_return;
311 	}
312       else
313 	{
314 	  file_ptr pos;
315 	  char hdr[8];
316 	  unsigned int i;
317 	  unsigned int len;
318 	  bfd_vma addr;
319 	  unsigned int type;
320 	  unsigned int chars;
321 	  unsigned int chksum;
322 
323 	  /* This is a data record.  */
324 	  pos = bfd_tell (abfd) - 1;
325 
326 	  /* Read the header bytes.  */
327 	  if (bfd_bread (hdr, (bfd_size_type) 8, abfd) != 8)
328 	    goto error_return;
329 
330 	  for (i = 0; i < 8; i++)
331 	    {
332 	      if (! ISHEX (hdr[i]))
333 		{
334 		  ihex_bad_byte (abfd, lineno, hdr[i], error);
335 		  goto error_return;
336 		}
337 	    }
338 
339 	  len = HEX2 (hdr);
340 	  addr = HEX4 (hdr + 2);
341 	  type = HEX2 (hdr + 6);
342 
343 	  /* Read the data bytes.  */
344 	  chars = len * 2 + 2;
345 	  if (chars >= bufsize)
346 	    {
347 	      buf = (bfd_byte *) bfd_realloc (buf, (bfd_size_type) chars);
348 	      if (buf == NULL)
349 		goto error_return;
350 	      bufsize = chars;
351 	    }
352 
353 	  if (bfd_bread (buf, (bfd_size_type) chars, abfd) != chars)
354 	    goto error_return;
355 
356 	  for (i = 0; i < chars; i++)
357 	    {
358 	      if (! ISHEX (buf[i]))
359 		{
360 		  ihex_bad_byte (abfd, lineno, hdr[i], error);
361 		  goto error_return;
362 		}
363 	    }
364 
365 	  /* Check the checksum.  */
366 	  chksum = len + addr + (addr >> 8) + type;
367 	  for (i = 0; i < len; i++)
368 	    chksum += HEX2 (buf + 2 * i);
369 	  if (((- chksum) & 0xff) != (unsigned int) HEX2 (buf + 2 * i))
370 	    {
371 	      (*_bfd_error_handler)
372 		(_("%s:%u: bad checksum in Intel Hex file (expected %u, found %u)"),
373 		 bfd_archive_filename (abfd), lineno,
374 		 (- chksum) & 0xff, (unsigned int) HEX2 (buf + 2 * i));
375 	      bfd_set_error (bfd_error_bad_value);
376 	      goto error_return;
377 	    }
378 
379 	  switch (type)
380 	    {
381 	    case 0:
382 	      /* This is a data record.  */
383 	      if (sec != NULL
384 		  && sec->vma + sec->_raw_size == extbase + segbase + addr)
385 		{
386 		  /* This data goes at the end of the section we are
387                      currently building.  */
388 		  sec->_raw_size += len;
389 		}
390 	      else if (len > 0)
391 		{
392 		  char secbuf[20];
393 		  char *secname;
394 		  bfd_size_type amt;
395 
396 		  sprintf (secbuf, ".sec%d", bfd_count_sections (abfd) + 1);
397 		  amt = strlen (secbuf) + 1;
398 		  secname = (char *) bfd_alloc (abfd, amt);
399 		  if (secname == NULL)
400 		    goto error_return;
401 		  strcpy (secname, secbuf);
402 		  sec = bfd_make_section (abfd, secname);
403 		  if (sec == NULL)
404 		    goto error_return;
405 		  sec->flags = SEC_HAS_CONTENTS | SEC_LOAD | SEC_ALLOC;
406 		  sec->vma = extbase + segbase + addr;
407 		  sec->lma = extbase + segbase + addr;
408 		  sec->_raw_size = len;
409 		  sec->filepos = pos;
410 		}
411 	      break;
412 
413 	    case 1:
414 	      /* An end record.  */
415 	      if (abfd->start_address == 0)
416 		abfd->start_address = addr;
417 	      if (buf != NULL)
418 		free (buf);
419 	      return TRUE;
420 
421 	    case 2:
422 	      /* An extended address record.  */
423 	      if (len != 2)
424 		{
425 		  (*_bfd_error_handler)
426 		    (_("%s:%u: bad extended address record length in Intel Hex file"),
427 		     bfd_archive_filename (abfd), lineno);
428 		  bfd_set_error (bfd_error_bad_value);
429 		  goto error_return;
430 		}
431 
432 	      segbase = HEX4 (buf) << 4;
433 
434 	      sec = NULL;
435 
436 	      break;
437 
438 	    case 3:
439 	      /* An extended start address record.  */
440 	      if (len != 4)
441 		{
442 		  (*_bfd_error_handler)
443 		    (_("%s:%u: bad extended start address length in Intel Hex file"),
444 		     bfd_archive_filename (abfd), lineno);
445 		  bfd_set_error (bfd_error_bad_value);
446 		  goto error_return;
447 		}
448 
449 	      abfd->start_address += (HEX4 (buf) << 4) + HEX4 (buf + 4);
450 
451 	      sec = NULL;
452 
453 	      break;
454 
455 	    case 4:
456 	      /* An extended linear address record.  */
457 	      if (len != 2)
458 		{
459 		  (*_bfd_error_handler)
460 		    (_("%s:%u: bad extended linear address record length in Intel Hex file"),
461 		     bfd_archive_filename (abfd), lineno);
462 		  bfd_set_error (bfd_error_bad_value);
463 		  goto error_return;
464 		}
465 
466 	      extbase = HEX4 (buf) << 16;
467 
468 	      sec = NULL;
469 
470 	      break;
471 
472 	    case 5:
473 	      /* An extended linear start address record.  */
474 	      if (len != 2 && len != 4)
475 		{
476 		  (*_bfd_error_handler)
477 		    (_("%s:%u: bad extended linear start address length in Intel Hex file"),
478 		     bfd_archive_filename (abfd), lineno);
479 		  bfd_set_error (bfd_error_bad_value);
480 		  goto error_return;
481 		}
482 
483 	      if (len == 2)
484 		abfd->start_address += HEX4 (buf) << 16;
485 	      else
486 		abfd->start_address = (HEX4 (buf) << 16) + HEX4 (buf + 4);
487 
488 	      sec = NULL;
489 
490 	      break;
491 
492 	    default:
493 	      (*_bfd_error_handler)
494 		(_("%s:%u: unrecognized ihex type %u in Intel Hex file\n"),
495 		 bfd_archive_filename (abfd), lineno, type);
496 	      bfd_set_error (bfd_error_bad_value);
497 	      goto error_return;
498 	    }
499 	}
500     }
501 
502   if (error)
503     goto error_return;
504 
505   if (buf != NULL)
506     free (buf);
507 
508   return TRUE;
509 
510  error_return:
511   if (buf != NULL)
512     free (buf);
513   return FALSE;
514 }
515 
516 /* Try to recognize an Intel Hex file.  */
517 
518 static const bfd_target *
519 ihex_object_p (abfd)
520      bfd *abfd;
521 {
522   PTR tdata_save;
523   bfd_byte b[9];
524   unsigned int i;
525   unsigned int type;
526 
527   ihex_init ();
528 
529   if (bfd_seek (abfd, (file_ptr) 0, SEEK_SET) != 0)
530     return NULL;
531   if (bfd_bread (b, (bfd_size_type) 9, abfd) != 9)
532     {
533       if (bfd_get_error () == bfd_error_file_truncated)
534 	bfd_set_error (bfd_error_wrong_format);
535       return NULL;
536     }
537 
538   if (b[0] != ':')
539     {
540       bfd_set_error (bfd_error_wrong_format);
541       return NULL;
542     }
543 
544   for (i = 1; i < 9; i++)
545     {
546       if (! ISHEX (b[i]))
547 	{
548 	  bfd_set_error (bfd_error_wrong_format);
549 	  return NULL;
550 	}
551     }
552 
553   type = HEX2 (b + 7);
554   if (type > 5)
555     {
556       bfd_set_error (bfd_error_wrong_format);
557       return NULL;
558     }
559 
560   /* OK, it looks like it really is an Intel Hex file.  */
561   tdata_save = abfd->tdata.any;
562   if (! ihex_mkobject (abfd) || ! ihex_scan (abfd))
563     {
564       if (abfd->tdata.any != tdata_save && abfd->tdata.any != NULL)
565 	bfd_release (abfd, abfd->tdata.any);
566       abfd->tdata.any = tdata_save;
567       return NULL;
568     }
569 
570   return abfd->xvec;
571 }
572 
573 /* Read the contents of a section in an Intel Hex file.  */
574 
575 static bfd_boolean
576 ihex_read_section (abfd, section, contents)
577      bfd *abfd;
578      asection *section;
579      bfd_byte *contents;
580 {
581   int c;
582   bfd_byte *p;
583   bfd_byte *buf = NULL;
584   size_t bufsize;
585   bfd_boolean error;
586 
587   if (bfd_seek (abfd, section->filepos, SEEK_SET) != 0)
588     goto error_return;
589 
590   p = contents;
591   bufsize = 0;
592   error = FALSE;
593   while ((c = ihex_get_byte (abfd, &error)) != EOF)
594     {
595       char hdr[8];
596       unsigned int len;
597       bfd_vma addr;
598       unsigned int type;
599       unsigned int i;
600 
601       if (c == '\r' || c == '\n')
602 	continue;
603 
604       /* This is called after ihex_scan has succeeded, so we ought to
605          know the exact format.  */
606       BFD_ASSERT (c == ':');
607 
608       if (bfd_bread (hdr, (bfd_size_type) 8, abfd) != 8)
609 	goto error_return;
610 
611       len = HEX2 (hdr);
612       addr = HEX4 (hdr + 2);
613       type = HEX2 (hdr + 6);
614 
615       /* We should only see type 0 records here.  */
616       if (type != 0)
617 	{
618 	  (*_bfd_error_handler)
619 	    (_("%s: internal error in ihex_read_section"),
620 	     bfd_archive_filename (abfd));
621 	  bfd_set_error (bfd_error_bad_value);
622 	  goto error_return;
623 	}
624 
625       if (len * 2 > bufsize)
626 	{
627 	  buf = (bfd_byte *) bfd_realloc (buf, (bfd_size_type) len * 2);
628 	  if (buf == NULL)
629 	    goto error_return;
630 	  bufsize = len * 2;
631 	}
632 
633       if (bfd_bread (buf, (bfd_size_type) len * 2, abfd) != len * 2)
634 	goto error_return;
635 
636       for (i = 0; i < len; i++)
637 	*p++ = HEX2 (buf + 2 * i);
638       if ((bfd_size_type) (p - contents) >= section->_raw_size)
639 	{
640 	  /* We've read everything in the section.  */
641 	  if (buf != NULL)
642 	    free (buf);
643 	  return TRUE;
644 	}
645 
646       /* Skip the checksum.  */
647       if (bfd_bread (buf, (bfd_size_type) 2, abfd) != 2)
648 	goto error_return;
649     }
650 
651   if ((bfd_size_type) (p - contents) < section->_raw_size)
652     {
653       (*_bfd_error_handler)
654 	(_("%s: bad section length in ihex_read_section"),
655 	 bfd_archive_filename (abfd));
656       bfd_set_error (bfd_error_bad_value);
657       goto error_return;
658     }
659 
660   if (buf != NULL)
661     free (buf);
662 
663   return TRUE;
664 
665  error_return:
666   if (buf != NULL)
667     free (buf);
668   return FALSE;
669 }
670 
671 /* Get the contents of a section in an Intel Hex file.  */
672 
673 static bfd_boolean
674 ihex_get_section_contents (abfd, section, location, offset, count)
675      bfd *abfd;
676      asection *section;
677      PTR location;
678      file_ptr offset;
679      bfd_size_type count;
680 {
681   if (section->used_by_bfd == NULL)
682     {
683       section->used_by_bfd = bfd_alloc (abfd, section->_raw_size);
684       if (section->used_by_bfd == NULL)
685 	return FALSE;
686       if (! ihex_read_section (abfd, section, section->used_by_bfd))
687 	return FALSE;
688     }
689 
690   memcpy (location, (bfd_byte *) section->used_by_bfd + offset,
691 	  (size_t) count);
692 
693   return TRUE;
694 }
695 
696 /* Set the contents of a section in an Intel Hex file.  */
697 
698 static bfd_boolean
699 ihex_set_section_contents (abfd, section, location, offset, count)
700      bfd *abfd;
701      asection *section;
702      const PTR location;
703      file_ptr offset;
704      bfd_size_type count;
705 {
706   struct ihex_data_list *n;
707   bfd_byte *data;
708   struct ihex_data_struct *tdata;
709   bfd_size_type amt;
710 
711   if (count == 0
712       || (section->flags & SEC_ALLOC) == 0
713       || (section->flags & SEC_LOAD) == 0)
714     return TRUE;
715 
716   amt = sizeof (struct ihex_data_list);
717   n = (struct ihex_data_list *) bfd_alloc (abfd, amt);
718   if (n == NULL)
719     return FALSE;
720 
721   data = (bfd_byte *) bfd_alloc (abfd, count);
722   if (data == NULL)
723     return FALSE;
724   memcpy (data, location, (size_t) count);
725 
726   n->data = data;
727   n->where = section->lma + offset;
728   n->size = count;
729 
730   /* Sort the records by address.  Optimize for the common case of
731      adding a record to the end of the list.  */
732   tdata = abfd->tdata.ihex_data;
733   if (tdata->tail != NULL
734       && n->where >= tdata->tail->where)
735     {
736       tdata->tail->next = n;
737       n->next = NULL;
738       tdata->tail = n;
739     }
740   else
741     {
742       register struct ihex_data_list **pp;
743 
744       for (pp = &tdata->head;
745 	   *pp != NULL && (*pp)->where < n->where;
746 	   pp = &(*pp)->next)
747 	;
748       n->next = *pp;
749       *pp = n;
750       if (n->next == NULL)
751 	tdata->tail = n;
752     }
753 
754   return TRUE;
755 }
756 
757 /* Write a record out to an Intel Hex file.  */
758 
759 static bfd_boolean
760 ihex_write_record (abfd, count, addr, type, data)
761      bfd *abfd;
762      size_t count;
763      unsigned int addr;
764      unsigned int type;
765      bfd_byte *data;
766 {
767   static const char digs[] = "0123456789ABCDEF";
768   char buf[9 + CHUNK * 2 + 4];
769   char *p;
770   unsigned int chksum;
771   unsigned int i;
772   size_t total;
773 
774 #define TOHEX(buf, v) \
775   ((buf)[0] = digs[((v) >> 4) & 0xf], (buf)[1] = digs[(v) & 0xf])
776 
777   buf[0] = ':';
778   TOHEX (buf + 1, count);
779   TOHEX (buf + 3, (addr >> 8) & 0xff);
780   TOHEX (buf + 5, addr & 0xff);
781   TOHEX (buf + 7, type);
782 
783   chksum = count + addr + (addr >> 8) + type;
784 
785   for (i = 0, p = buf + 9; i < count; i++, p += 2, data++)
786     {
787       TOHEX (p, *data);
788       chksum += *data;
789     }
790 
791   TOHEX (p, (- chksum) & 0xff);
792   p[2] = '\r';
793   p[3] = '\n';
794 
795   total = 9 + count * 2 + 4;
796   if (bfd_bwrite (buf, (bfd_size_type) total, abfd) != total)
797     return FALSE;
798 
799   return TRUE;
800 }
801 
802 /* Write out an Intel Hex file.  */
803 
804 static bfd_boolean
805 ihex_write_object_contents (abfd)
806      bfd *abfd;
807 {
808   bfd_vma segbase;
809   bfd_vma extbase;
810   struct ihex_data_list *l;
811 
812   segbase = 0;
813   extbase = 0;
814   for (l = abfd->tdata.ihex_data->head; l != NULL; l = l->next)
815     {
816       bfd_vma where;
817       bfd_byte *p;
818       bfd_size_type count;
819 
820       where = l->where;
821       p = l->data;
822       count = l->size;
823       while (count > 0)
824 	{
825 	  size_t now;
826 	  unsigned int rec_addr;
827 
828 	  now = count;
829 	  if (count > CHUNK)
830 	    now = CHUNK;
831 
832 	  if (where > segbase + extbase + 0xffff)
833 	    {
834 	      bfd_byte addr[2];
835 
836 	      /* We need a new base address.  */
837 	      if (where <= 0xfffff)
838 		{
839 		  /* The addresses should be sorted.  */
840 		  BFD_ASSERT (extbase == 0);
841 
842 		  segbase = where & 0xf0000;
843 		  addr[0] = (bfd_byte)(segbase >> 12) & 0xff;
844 		  addr[1] = (bfd_byte)(segbase >> 4) & 0xff;
845 		  if (! ihex_write_record (abfd, 2, 0, 2, addr))
846 		    return FALSE;
847 		}
848 	      else
849 		{
850 		  /* The extended address record and the extended
851                      linear address record are combined, at least by
852                      some readers.  We need an extended linear address
853                      record here, so if we've already written out an
854                      extended address record, zero it out to avoid
855                      confusion.  */
856 		  if (segbase != 0)
857 		    {
858 		      addr[0] = 0;
859 		      addr[1] = 0;
860 		      if (! ihex_write_record (abfd, 2, 0, 2, addr))
861 			return FALSE;
862 		      segbase = 0;
863 		    }
864 
865 		  extbase = where & 0xffff0000;
866 		  if (where > extbase + 0xffff)
867 		    {
868 		      char buf[20];
869 
870 		      sprintf_vma (buf, where);
871 		      (*_bfd_error_handler)
872 			(_("%s: address 0x%s out of range for Intel Hex file"),
873 			 bfd_get_filename (abfd), buf);
874 		      bfd_set_error (bfd_error_bad_value);
875 		      return FALSE;
876 		    }
877 		  addr[0] = (bfd_byte)(extbase >> 24) & 0xff;
878 		  addr[1] = (bfd_byte)(extbase >> 16) & 0xff;
879 		  if (! ihex_write_record (abfd, 2, 0, 4, addr))
880 		    return FALSE;
881 		}
882 	    }
883 
884 	  rec_addr = where - (extbase + segbase);
885 
886           /* Output records shouldn't cross 64K boundaries.  */
887           if (rec_addr + now > 0xffff)
888             now = 0x10000 - rec_addr;
889 
890 	  if (! ihex_write_record (abfd, now, rec_addr, 0, p))
891 	    return FALSE;
892 
893 	  where += now;
894 	  p += now;
895 	  count -= now;
896 	}
897     }
898 
899   if (abfd->start_address != 0)
900     {
901       bfd_vma start;
902       bfd_byte startbuf[4];
903 
904       start = abfd->start_address;
905 
906       if (start <= 0xfffff)
907 	{
908 	  startbuf[0] = (bfd_byte)((start & 0xf0000) >> 12) & 0xff;
909 	  startbuf[1] = 0;
910 	  startbuf[2] = (bfd_byte)(start >> 8) & 0xff;
911 	  startbuf[3] = (bfd_byte)start & 0xff;
912 	  if (! ihex_write_record (abfd, 4, 0, 3, startbuf))
913 	    return FALSE;
914 	}
915       else
916 	{
917 	  startbuf[0] = (bfd_byte)(start >> 24) & 0xff;
918 	  startbuf[1] = (bfd_byte)(start >> 16) & 0xff;
919 	  startbuf[2] = (bfd_byte)(start >> 8) & 0xff;
920 	  startbuf[3] = (bfd_byte)start & 0xff;
921 	  if (! ihex_write_record (abfd, 4, 0, 5, startbuf))
922 	    return FALSE;
923 	}
924     }
925 
926   if (! ihex_write_record (abfd, 0, 0, 1, NULL))
927     return FALSE;
928 
929   return TRUE;
930 }
931 
932 /* Set the architecture for the output file.  The architecture is
933    irrelevant, so we ignore errors about unknown architectures.  */
934 
935 static bfd_boolean
936 ihex_set_arch_mach (abfd, arch, mach)
937      bfd *abfd;
938      enum bfd_architecture arch;
939      unsigned long mach;
940 {
941   if (! bfd_default_set_arch_mach (abfd, arch, mach))
942     {
943       if (arch != bfd_arch_unknown)
944 	return FALSE;
945     }
946   return TRUE;
947 }
948 
949 /* Get the size of the headers, for the linker.  */
950 
951 static int
952 ihex_sizeof_headers (abfd, exec)
953      bfd *abfd ATTRIBUTE_UNUSED;
954      bfd_boolean exec ATTRIBUTE_UNUSED;
955 {
956   return 0;
957 }
958 
959 /* Some random definitions for the target vector.  */
960 
961 #define	ihex_close_and_cleanup _bfd_generic_close_and_cleanup
962 #define ihex_bfd_free_cached_info _bfd_generic_bfd_free_cached_info
963 #define ihex_new_section_hook _bfd_generic_new_section_hook
964 #define ihex_get_section_contents_in_window \
965   _bfd_generic_get_section_contents_in_window
966 
967 #define ihex_get_symtab_upper_bound bfd_0l
968 #define ihex_canonicalize_symtab \
969   ((long (*) PARAMS ((bfd *, asymbol **))) bfd_0l)
970 #define ihex_make_empty_symbol _bfd_generic_make_empty_symbol
971 #define ihex_print_symbol _bfd_nosymbols_print_symbol
972 #define ihex_get_symbol_info _bfd_nosymbols_get_symbol_info
973 #define ihex_bfd_is_local_label_name _bfd_nosymbols_bfd_is_local_label_name
974 #define ihex_get_lineno _bfd_nosymbols_get_lineno
975 #define ihex_find_nearest_line _bfd_nosymbols_find_nearest_line
976 #define ihex_bfd_make_debug_symbol _bfd_nosymbols_bfd_make_debug_symbol
977 #define ihex_read_minisymbols _bfd_nosymbols_read_minisymbols
978 #define ihex_minisymbol_to_symbol _bfd_nosymbols_minisymbol_to_symbol
979 
980 #define ihex_get_reloc_upper_bound \
981   ((long (*) PARAMS ((bfd *, asection *))) bfd_0l)
982 #define ihex_canonicalize_reloc \
983   ((long (*) PARAMS ((bfd *, asection *, arelent **, asymbol **))) bfd_0l)
984 #define ihex_bfd_reloc_type_lookup _bfd_norelocs_bfd_reloc_type_lookup
985 
986 #define ihex_bfd_get_relocated_section_contents \
987   bfd_generic_get_relocated_section_contents
988 #define ihex_bfd_relax_section bfd_generic_relax_section
989 #define ihex_bfd_gc_sections bfd_generic_gc_sections
990 #define ihex_bfd_merge_sections bfd_generic_merge_sections
991 #define ihex_bfd_discard_group bfd_generic_discard_group
992 #define ihex_bfd_link_hash_table_create _bfd_generic_link_hash_table_create
993 #define ihex_bfd_link_hash_table_free _bfd_generic_link_hash_table_free
994 #define ihex_bfd_link_add_symbols _bfd_generic_link_add_symbols
995 #define ihex_bfd_link_just_syms _bfd_generic_link_just_syms
996 #define ihex_bfd_final_link _bfd_generic_final_link
997 #define ihex_bfd_link_split_section _bfd_generic_link_split_section
998 
999 /* The Intel Hex target vector.  */
1000 
1001 const bfd_target ihex_vec =
1002 {
1003   "ihex",			/* name */
1004   bfd_target_ihex_flavour,
1005   BFD_ENDIAN_UNKNOWN,		/* target byte order */
1006   BFD_ENDIAN_UNKNOWN,		/* target headers byte order */
1007   0,				/* object flags */
1008   (SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD),	/* section flags */
1009   0,				/* leading underscore */
1010   ' ',				/* ar_pad_char */
1011   16,				/* ar_max_namelen */
1012   bfd_getb64, bfd_getb_signed_64, bfd_putb64,
1013   bfd_getb32, bfd_getb_signed_32, bfd_putb32,
1014   bfd_getb16, bfd_getb_signed_16, bfd_putb16,	/* data */
1015   bfd_getb64, bfd_getb_signed_64, bfd_putb64,
1016   bfd_getb32, bfd_getb_signed_32, bfd_putb32,
1017   bfd_getb16, bfd_getb_signed_16, bfd_putb16,	/* hdrs */
1018 
1019   {
1020     _bfd_dummy_target,
1021     ihex_object_p,		/* bfd_check_format */
1022     _bfd_dummy_target,
1023     _bfd_dummy_target,
1024   },
1025   {
1026     bfd_false,
1027     ihex_mkobject,
1028     _bfd_generic_mkarchive,
1029     bfd_false,
1030   },
1031   {				/* bfd_write_contents */
1032     bfd_false,
1033     ihex_write_object_contents,
1034     _bfd_write_archive_contents,
1035     bfd_false,
1036   },
1037 
1038   BFD_JUMP_TABLE_GENERIC (ihex),
1039   BFD_JUMP_TABLE_COPY (_bfd_generic),
1040   BFD_JUMP_TABLE_CORE (_bfd_nocore),
1041   BFD_JUMP_TABLE_ARCHIVE (_bfd_noarchive),
1042   BFD_JUMP_TABLE_SYMBOLS (ihex),
1043   BFD_JUMP_TABLE_RELOCS (ihex),
1044   BFD_JUMP_TABLE_WRITE (ihex),
1045   BFD_JUMP_TABLE_LINK (ihex),
1046   BFD_JUMP_TABLE_DYNAMIC (_bfd_nodynamic),
1047 
1048   NULL,
1049 
1050   (PTR) 0
1051 };
1052