summaryrefslogtreecommitdiff
path: root/apps/system/hex2bin/hex2bin.c
blob: 95634fcc8d4f35eef96cd9f22f0793b95cc6ee41 (plain) (blame)
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
/****************************************************************************
 * apps/system/hex2bin.c
 *
 *   Copyright (C) 2014 Gregory Nutt. All rights reserved.
 *   Author: Gregory Nutt <gnutt@nuttx.org>
 *
 * References:
 *   - http://en.wikipedia.org/wiki/Intel_HEX
 *   - Hexadecimal Object File Format Specification, Revision A January 6,
 *     1988, Intel
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name NuttX nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

/****************************************************************************
 * Included Files
 ****************************************************************************/

#include <nuttx/config.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdint.h>
#include <errno.h>

#include <nuttx/streams.h>
#include <apps/hex2bin.h>

#ifdef CONFIG_SYSTEM_HEX2BIN

/****************************************************************************
 * Pre-processor Definitions
 ****************************************************************************/

/* ASCII record sizes */

#define BYTECOUNT_ASCSIZE      2
#define ADDRESS_ASCSIZE        4
#define RECTYPE_ASCSIZE        2

#define BYTECOUNT_LINENDX      (0)
#define ADDRESS_LINENDX        (BYTECOUNT_LINENDX + BYTECOUNT_ASCSIZE)
#define RECTYPE_LINENDX        (ADDRESS_LINENDX + ADDRESS_ASCSIZE)
#define DATA_LINENDX           (RECTYPE_LINENDX + RECTYPE_ASCSIZE)
#define HEADER_ASCSIZE          DATA_LINENDX

#define CHECKSUM_ASCSIZE       2
#define TRAILER_SIZE           (CHECKSUM_ASCSIZE)

#define MAXDATA_BINSIZE        255
#define RECORD_ASCSIZE(n)      (HEADER_ASCSIZE + TRAILER_SIZE + 2*(n))
#define MAXRECORD_ASCSIZE      RECORD_ASCSIZE(MAXDATA_BINSIZE)
#define MINRECORD_ASCSIZE      RECORD_ASCSIZE(0)
#define LINE_ALLOC             MAXRECORD_ASCSIZE

/* Binary record sizes */

#define BYTECOUNT_BINSIZE      1
#define ADDRESS_BINSIZE        2
#define RECTYPE_BINSIZE        1

#define BYTECOUNT_BINNDX       (0)
#define ADDRESS_BINNDX         (BYTECOUNT_BINNDX + BYTECOUNT_BINSIZE)
#define RECTYPE_BINNDX         (ADDRESS_BINNDX + ADDRESS_BINSIZE)
#define DATA_BINNDX            (RECTYPE_BINNDX + RECTYPE_BINSIZE)
#define HEADER_BINSIZE         DATA_BINNDX

#define CHECKSUM_BINSIZE       1
#define TRAILER_BINSIZE        CHECKSUM_BINSIZE

#define RECORD_BINSIZE(n)      (HEADER_BINSIZE + TRAILER_BINSIZE + (n))
#define MAXRECORD_BINSIZE      RECORD_BINSIZE(MAXDATA_BINSIZE)
#define MINRECORD_BKINSIZE     RECORD_BINSIZE(0)
#define BIN_ALLOC              MAXRECORD_BINSIZE

/* Record start code */

#define RECORD_STARTCODE       ':'

/* Record Types */

#define RECORD_DATA            0  /* Data */
#define RECORD_EOF             1  /* End of file */
#define RECORD_EXT_SEGADDR     2  /* Extended segment address record */
#define RECORD_START_SEGADDR   3  /* Start segment address record */
#define RECORD_EXT_LINADDR     4  /* Extended linear address record */
#define RECORD_START_LINADDR   5  /* Start linear address record */

/****************************************************************************
 * Private Types
 ****************************************************************************/

/****************************************************************************
 * Private Functions
 ****************************************************************************/

/****************************************************************************
 * Name: nibble2bin
 ****************************************************************************/

static int nibble2bin(uint8_t ascii)
{
  if (ascii >= '0' && ascii <= '9')
    {
      return (ascii - 0x30);
    }
  else if (ascii >= 'a' && ascii <= 'f')
    {
      return (ascii - 'a' + 10);
    }
  else if (ascii >= 'A' && ascii <= 'F')
    {
      return (ascii - 'A' + 10);
    }

  return -EINVAL;
}

/****************************************************************************
 * Name: byte2bin
 ****************************************************************************/

static int byte2bin(FAR const uint8_t *ascii)
{
  int nibble;
  int byte;

  /* Get the MS nibble (big endian order) */

  nibble = nibble2bin(*ascii++);
  if (nibble < 0)
    {
      return nibble;
    }

  byte = (nibble << 4);

  /* Get the MS nibble */

  nibble = nibble2bin(*ascii);
  if (nibble < 0)
    {
      return nibble;
    }

  byte |= nibble;
  return byte;
}

/****************************************************************************
 * Name: word2bin
 ****************************************************************************/

#if 0 /* Not used */
static int word2bin(FAR const char *ascii)
{
  int byte;
  int word;

  /* Get the MS byte (big endian order) */

  byte = word2bin(ascii);
  if (byte < 0)
    {
      return byte;
    }

  word = (byte << 8);

  /* Get the MS byte */

  byte = word2bin(ascii + 2);
  if (byte < 0)
    {
      return byte;
    }

  word |= byte;
  return word;
}
#endif

/****************************************************************************
 * Name: data2bin
 ****************************************************************************/

int data2bin(FAR uint8_t* dest, FAR const uint8_t *src, int nsrcbytes)
{
  int byte;

  /* An even number of source bytes is expected */

  if ((nsrcbytes & 1) != 0)
    {
      return -EINVAL;
    }

  /* Convert src bytes in groups of 2, writing one byte to the output on each
   * pass through the loop. */

  while (nsrcbytes > 0)
    {
      /* Get the MS nibble (big endian order) */

      byte = byte2bin(src);
      if (byte < 0)
        {
          return byte;
        }

      src += 2;

      /* And write the byte to the destination */

      *dest++ = byte;
      nsrcbytes -= 2;
    }

  return OK;
}

/****************************************************************************
 * Name: readstream
 ****************************************************************************/

static int readstream(FAR struct lib_instream_s *instream,
                      FAR uint8_t *line, unsigned int lineno)
{
  int nbytes = 0;
  int ch;

  /* Skip until the beginning of line start code is encountered */

  ch = instream->get(instream);
  while (ch != RECORD_STARTCODE && ch != EOF)
    {
      ch = instream->get(instream);
    }

  /* Skip over the startcode */

  if (ch != EOF)
    {
      ch = instream->get(instream);
    }

  /* Then read, verify, and buffer until the end of line is encountered */

  while (ch != EOF && nbytes < (MAXRECORD_ASCSIZE-1))
    {
#if defined(CONFIG_EOL_IS_LF)
      if (ch == '\n')
        {
          *line = '\0';
          return nbytes;
        }

#elif defined(CONFIG_EOL_IS_BOTH_CRLF)
      if (ch == '\r')
        {
          continue;
        }
      else if (ch == '\n')
        {
          *line = '\0';
          return nbytes;
        }
#elif defined(CONFIG_EOL_IS_CR)
      if (ch == '\r')
        {
          *line = '\0';
          return nbytes;
        }
#elif CONFIG_EOL_IS_EITHER_CRLF
      if (ch == '\n' || ch == '\r')
        {
          *line = '\0';
          return nbytes;
        }
#endif
      /* Only hex data goes into the line buffer */

      else if (isxdigit(ch))
        {
          *line++ = ch;
          nbytes++;
        }
      else if (!isspace(ch)) /* Not expected */
        {
          hex2bin_debug("Line %u ERROR: Unexpected character %c[%02x] in stream\n",
                        lineno, isprint(ch) ? ch : '.', ch);
          break;
        }

      /* Read the next character from the input stream */

      ch = instream->get(instream);
    }

  /* Some error occurred: Unexpected EOF, line too long, or bad character in
   * stream
   */

  hex2bin_debug("Line %u ERROR: Failed to read line. %d characters read\n",
                lineno, nbytes);
  return EOF;
}

/****************************************************************************
 * Name: hex2bin_swap16 and hex2bin_swap32
 ****************************************************************************/

static inline void hex2bin_swap16(FAR uint8_t *data, int bytecount)
{
  for (; bytecount > 0; bytecount -= 2)
    {
      uint8_t b0 = data[0];
      uint8_t b1 = data[1];

      *data++ = b1;
      *data++ = b0;
    }
}

static inline void hex2bin_swap32(FAR uint8_t *data, int bytecount)
{
  for (; bytecount > 0; bytecount -= 4)
    {
      uint8_t b0 = data[0];
      uint8_t b1 = data[1];
      uint8_t b2 = data[2];
      uint8_t b3 = data[3];

      *data++ = b3;
      *data++ = b2;
      *data++ = b1;
      *data++ = b0;
    }
}

/****************************************************************************
 * Name: writedata
 ****************************************************************************/

static inline void writedata(FAR struct lib_sostream_s *outstream,
                             FAR uint8_t *data, int bytecount)
{
  for (; bytecount > 0; bytecount--)
    {
      outstream->put(outstream, *data++);
    }
}

/****************************************************************************
 * Public Functions
 ****************************************************************************/

/****************************************************************************
 * Name: hex2bin
 *
 * Description:
 *   Read the Intel HEX ASCII data provided on the serial IN stream and write
 *   the binary to the seek-able serial OUT stream.
 *
 *   These streams may be files or, in another usage example, the IN stream
 *   could be a serial port and the OUT stream could be a memory stream.  This
 *   would decode and write the serial input to memory.
 *
 * Input Parameters:
 *   instream  - The incoming stream from which Intel HEX data will be
 *               received.
 *   outstream - The outgoing stream in which binary data will be written.
 *   baseaddr  - The base address of the outgoing stream.  Seeking in the
 *               output stream will be relative to this address.
 *   endpaddr  - The end address (plus 1) of the outgoing stream.  This
 *               value is used only for range checking.  endpaddr must
 *               be larger than baseaddr.  A zero value for endpaddr
 *               disables range checking.
 *   swap      - Controls byte ordering.  See enum hex2bin_swap_e for
 *               description of the values.
 *
 * Returned Value
 *   Zero (OK) is returned on success; a negated errno value is returned on
 *   failure.
 * 
 ****************************************************************************/

int hex2bin(FAR struct lib_instream_s *instream,
            FAR struct lib_sostream_s *outstream, uint32_t baseaddr,
            uint32_t endpaddr, enum hex2bin_swap_e swap)
{
  FAR uint8_t *alloc;
  FAR uint8_t *line;
  FAR uint8_t *bin;
  int nbytes;
  int bytecount;
  uint32_t address;
  uint32_t endaddr;
  uint32_t expected;
  uint16_t extension;
  uint16_t address16;
  uint8_t checksum;
  unsigned int lineno;
  int i;
  int ret = OK;

  /* Allocate buffer memory */

  alloc = (FAR uint8_t *)malloc(LINE_ALLOC + BIN_ALLOC);
  if (alloc == NULL)
    {
      hex2bin_debug("ERROR: Failed to allocate memory\n");
      return -ENOMEM;
    }

  line = alloc;
  bin  = &alloc[LINE_ALLOC];

  extension = 0;
  expected = 0;
  lineno = 0;

  while ((nbytes = readstream(instream, line, lineno)) != EOF)
    {
      /* Increment the line number */

      lineno++;

      /* Did we read enough data to do anything? */

      if (nbytes < MINRECORD_ASCSIZE)
        {
          hex2bin_debug("Line %u ERROR: Record too short: %d\n",
                        lineno, nbytes);
          goto errout_with_einval;
        }

      /* We should always read an even number of bytes */

      if ((nbytes & 1) != 0)
        {
          hex2bin_debug("Line %u ERROR: Record length is odd: %d\n",
                        lineno, nbytes);
          goto errout_with_einval;
        }

      /* Get the data byte count */

      bytecount = byte2bin(&line[BYTECOUNT_LINENDX]);
      if (bytecount < 0)
        {
          hex2bin_debug("Line %u ERROR: Failed to read bytecount: %d\n",
                        lineno, bytecount);
          ret = bytecount;
          goto errout_with_buffers;
        }

      /* Verify that the bytecount matches the length of the record */

      if (RECORD_ASCSIZE(bytecount) != nbytes)
        {
          hex2bin_debug("Line %u ERROR: Expected %d bytes, read %d\n",
                        lineno, RECORD_ASCSIZE(bytecount), nbytes);
          goto errout_with_einval;
        }

      /* Convert the entire line to binary.  We need to do this for
       * checksum calculation which includes the entire line (minus
       * the start code and the checksum at the end of the line itself)
       */

      ret = data2bin(bin, line, nbytes);
      if (ret < 0)
        {
          hex2bin_debug("Line %u ERROR: Failed to convert line to binary: %d\n",
                        lineno, ret);
          goto errout_with_buffers;
        }

      /* Calculate and verify the checksum over all of the data */

      nbytes >>= 1;  /* Number of bytes in bin[] */
      checksum = 0;

      for (i = 0; i < nbytes; i++)
        {
          checksum += bin[i];
        }

      if (checksum != 0)
        {
          hex2bin_debug("Line %u ERROR: Bad checksum %02x\n",
                        lineno, checksum);
          goto errout_with_einval;
        }

      /* Get the 16-bit (unextended) address from the record */

      address16 = (uint16_t)bin[ADDRESS_BINNDX] << 8 |
                  (uint16_t)bin[ADDRESS_BINNDX+1];

      /* Handle the record by its record type */

      switch (bin[RECTYPE_BINNDX])
        {
        case RECORD_DATA: /* Data */
          {
            /* Swap data in place in the binary buffer as required */

            switch (swap)
              {
              case HEX2BIN_NOSWAP: /* No swap, stream is the correct byte order */
                break;

              case HEX2BIN_SWAP16: /* Swap bytes in 16-bit values */
                {
                  if ((bytecount & 1) != 0)
                    {
                      hex2bin_debug("Line %d ERROR: Byte count %d is not a multiple of 2\n",
                                    lineno, bytecount);
                       goto errout_with_einval;
                    }

                  /* Do the byte swap */

                  hex2bin_swap16(&bin[DATA_BINNDX], bytecount);
                }
                break;

              case HEX2BIN_SWAP32: /* Swap bytes in 32-bit values */
                {
                  if ((bytecount & 3) != 0)
                    {
                      hex2bin_debug("Line %d ERROR: Byte count %d is not a multiple of 4\n",
                                    lineno, bytecount);
                       goto errout_with_einval;
                    }

                  /* Do the byte swap */

                  hex2bin_swap32(&bin[DATA_BINNDX], bytecount);
                }
                break;

              default:
                {
                  hex2bin_debug("ERROR: Invalid swap argument: %d\n", swap);
                  goto errout_with_einval;
                }
              }

            /* Get and verify the full 32-bit address */

            address = ((uint32_t)extension << 16) | (uint32_t)address16;
            endaddr = address + bytecount;

            if (address < baseaddr || (endpaddr != 0 && endaddr >= endpaddr))
              {
                hex2bin_debug("Line %d ERROR: Extended address %08lx is out of range\n", 
                              lineno, (unsigned long)address);
                goto errout_with_einval;
              }

            /* Seek to the correct position in the OUT stream if we have
             * made an unexpected jump in the data address.
             */

            if (address != expected)
              {
                off_t pos = outstream->seek(outstream, address - baseaddr, SEEK_SET);
                if (pos == (off_t)-1)
                  {
                    hex2bin_debug("Line %u ERROR: Seek to address %08lu failed\n",
                                  lineno, (unsigned long)address);
                    ret = -ESPIPE;
                    goto errout_with_buffers;
                  }
              }

            /* Transfer data to the OUT stream */

            writedata(outstream, &bin[DATA_BINNDX], bytecount);

            /* This is the next data address that we expect to see */

            expected = address + bytecount;
          }
          break;

        case RECORD_EOF: /* End of file */
          /*  End Of File record.  Must occur exactly once per file in the
           * last line of the file. The byte count is 00 and the data field
           * is empty. Usually the address field is also 0000.
           */

          if (bytecount == 0)
            {
              ret = OK;
              goto exit_with_buffers;
            }

          hex2bin_debug("Line %u ERROR: Nonzero bytecount %d in EOF\n",
                        lineno, bytecount);
          goto errout_with_einval;

        case RECORD_EXT_SEGADDR: /* Extended segment address record */
          /* The address specified by the data field is multiplied by 16
           * (shifted 4 bits left) and added to the subsequent data record
           * addresses. This allows addressing of up to a megabyte of
           * address space. The address field of this record has to be
           * 0000, the byte count is 02 (the segment is 16-bit). The
           * least significant hex digit of the segment address is always
           * 0.
           */

          if (bytecount != 2 || address16 != 0 || bin[DATA_BINNDX+1] != 0)
            {
              hex2bin_debug("Line %u ERROR: Invalid segment address\n",
                            lineno);
              hex2bin_debug("  bytecount=%d address=%04x segment=%02x%02x\n",
                            bytecount, address16, bin[DATA_BINNDX],
                            bin[DATA_BINNDX+1]);
              goto errout_with_einval;
            }

          extension = (uint16_t)bin[DATA_BINNDX];
          break;

        case RECORD_START_SEGADDR: /* Start segment address record */
          /* For 80x86 processors, it specifies the initial content of
           * the CS:IP registers. The address field is 0000, the byte
           * count is 04, the first two bytes are the CS value, the
           * latter two are the IP value.
           */

          break;

        case RECORD_EXT_LINADDR: /* Extended linear address record */
          /* The address field is 0000, the byte count is 02. The two
           * data bytes (two hex digit pairs in big endian order)
           * represent the upper 16 bits of the 32 bit address for
           * all subsequent 00 type records until the next 04 type
           * record comes. If there is not a 04 type record, the
           * upper 16 bits default to 0000. To get the absolute
           * address for subsequent 00 type records, the address
           * specified by the data field of the most recent 04 record
           * is added to the 00 record addresses.
           */

          if (bytecount != 2 || address16 != 0)
            {
              hex2bin_debug("Line %u ERROR: Invalid linear address\n",
                            lineno);
              hex2bin_debug("  bytecount=%d address=%04x\n",
                            bytecount, address16);
              goto errout_with_einval;
            }

          extension = (uint16_t)bin[DATA_BINNDX] << 8 |
                      (uint16_t)bin[DATA_BINNDX+1];
          break;

        case RECORD_START_LINADDR: /* Start linear address record */
          /* The address field is 0000, the byte count is 04. The 4
           * data bytes represent the 32-bit value loaded into the EIP
           * register of the 80386 and higher CPU.
           */

          break;

        default:
          break;
        }
    }

  hex2bin_debug("ERROR: No EOF record found\n");

errout_with_einval:
  ret = -EINVAL;

errout_with_buffers:
exit_with_buffers:
  free(alloc);
  return ret;
}

#endif /* CONFIG_SYSTEM_HEX2BIN */