summaryrefslogtreecommitdiff
path: root/misc/buildroot/toolchain/nxflat/mknxflat.c
blob: 7a66280bb7fc136927cedaaaf6667b430293dc37 (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
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
/***********************************************************************
 * xflat/tools/mknxflat.c
 *
 *   Copyright (C) 2009 Gregory Nutt. All rights reserved.
 *   Author: Gregory Nutt <gnutt@nuttx.org>
 *
 * Modified from ldelflib (see http://xflat.org):
 *
 *   Copyright (c) 2002, 2006, Cadenux, LLC.  All rights reserved.
 *   Copyright (c) 2002, 2006, Gregory Nutt.  All rights reserved.
 *   Author: Gregory Nutt <gnutt@nuttx.org>
 *
 * 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 "config.h"

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>

#include "bfd.h"

#include "nxflat.h"
#include "arch/arch.h"

/***********************************************************************
 * Definitions
 ***********************************************************************/

#define dbg(format, arg...) \
    if (verbose) printf(format, ## arg)

#define BSF_GLOBL_FUNC (BSF_GLOBAL|BSF_FUNCTION)
#define BSF_WEAK_FUNC  (BSF_WEAK|BSF_FUNCTION)
#define BSF_DEFINED    (BSF_LOCAL|BSF_GLOBAL)

#define IS_GLOBL_FUNC(x) ((((x)->flags)&(BSF_GLOBL_FUNC))==(BSF_GLOBL_FUNC))
#define IS_WEAK_FUNC(x)  ((((x)->flags)&(BSF_WEAK_FUNC))==(BSF_WEAK_FUNC))
#define IS_DEFINED(x)    ((((x)->flags)&(BSF_DEFINED))!=0)
#define IS_OBJECT(x)     ((((x)->flags)&(BSF_OBJECT))!=0)
#define IS_WEAK(x)       ((((x)->flags)&(BSF_WEAK))!=0)

#define MAX_EXPORT_NAMES    1024

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

typedef int (*symfunc_type) (asymbol * sym, void *arg);
typedef int (*namefunc_type) (const char *name, void *arg);

/***********************************************************************
 * Private Variables
 ***********************************************************************/

/* Command line settings (counters but treated like booleans) */

static int verbose = 0;
static int weak_imports = 0;
static int dsyms = 0;

/* Characteristics of things */
static int calls_nonreturning_functions = 0;

/* Sizes of things */

static long number_of_symbols = 0;
static long number_undefined = 0;

/* Names of things */

static const char *program_name = NULL;
static const char *bfd_filename = NULL;
static const char *out_filename = NULL;

/* The symbol table. */

static asymbol **symbol_table = NULL;

/* handle to included file */

static FILE *include_stream = NULL;
static char token[1024];

static int counter;

/***********************************************************************
 * Private constant data
 ***********************************************************************/

/* All of the strings defining the generated file are here: */

#include "arch/dyncall_skeleton.def"

static const char dyn_symbol_prefix[] = "__dyn";
#define DYN_SYMBOL_PREFIX_LEN 5

/* This is the list of names of libc and libpthread functions that
 * do not return.  These may require some special handling -- at a
 * minimum, they must tie up resources that can only be released
 * when the function returns.
 */

static const char *const nonreturners[] = {
  "abort",                      /* Never returns */
  "exit",                       /* Never returns */
  "_exit",                      /* Never returns */
  "longjmp",                    /* Never returns */
  "_longjmp",                   /* Never returns */
  "pthread_exit",               /* Never returns */
  "siglongjmp",                 /* Never returns */
  NULL                          /* End of list */
};

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

/***********************************************************************
 * show_usage
 ***********************************************************************/

static void show_usage(void)
{
  fprintf(stderr, "Usage: %s [options] <bfd-filename>\n\n", program_name);
  fprintf(stderr, "Where options are one or more of the following.  Note\n");
  fprintf(stderr, "that a space is always required between the option and\n");
  fprintf(stderr, "any following arguments.\n\n");
  fprintf(stderr, "  -d Use dynamic symbol table. [symtab]\n");
  fprintf(stderr, "  -f <cmd-filename>\n");
  fprintf(stderr, "      Take next commands from <cmd-filename> [cmd-line]\n");
  fprintf(stderr, "  -o <out-filename>\n");
  fprintf(stderr, "     Output to <out-filename> [stdout]\n");
  fprintf(stderr, "  -v Verbose output [no output]\n");
  fprintf(stderr, "  -w Import weakly declared functions, i.e., weakly\n");
  fprintf(stderr, "     declared functions are expected to be provided at\n");
  fprintf(stderr, "     load-time [not imported]\n");
  fprintf(stderr, "\n");
  exit(1);
}

/***********************************************************************
 * get_symbols
 ***********************************************************************/

static asymbol **get_symbols(bfd * abfd, long *num)
{
  long storage_needed;
  asymbol **symbol_table;
  long number_of_symbols;

  if (dsyms)
    storage_needed = bfd_get_dynamic_symtab_upper_bound(abfd);
  else
    storage_needed = bfd_get_symtab_upper_bound(abfd);

  if (storage_needed < 0)
    abort();

  if (storage_needed == 0)
    return NULL;

  symbol_table = (asymbol **) malloc(storage_needed);

  if (dsyms)
    number_of_symbols = bfd_canonicalize_dynamic_symtab(abfd, symbol_table);
  else
    number_of_symbols = bfd_canonicalize_symtab(abfd, symbol_table);
  if (number_of_symbols < 0)
    abort();

  *num = number_of_symbols;
  return symbol_table;
}

/***********************************************************************
 * traverse_undefined_functions
 ***********************************************************************/

static int traverse_undefined_functions(void *arg, symfunc_type fn)
{
  int i;

  for (i = 0; i < number_of_symbols; i++)
    {
      /* Check if it is undefined and not an object. I have found that symbol
       * typing can be misleading: Imported functions are not marked as
       * BSF_FUNCTION; weakly defined objects are listed as undefined objects.
       * Conclusion: We will error if a object is truly undefined! */

      if ((symbol_table[i]->value == 0) &&
          (!IS_DEFINED(symbol_table[i])) && (!IS_OBJECT(symbol_table[i])))
        {
          /* Is is imported as a "weak" symbol? If so, we will process the
           * symbol only if we were requested to do so from the command line. */

          if ((!IS_WEAK(symbol_table[i])) || (weak_imports > 0))
            {
              /* Yes, process the symbol */

              if (fn(symbol_table[i], arg) != 0)
                {
                  /* If the function returns a non-zero value, then we
                   * terminate the traversal and return a non-zero value also. */

                  return 1;
                }
            }
        }
    }

  /* Return 0 meaning that all undefined symbols were examined successfully. */

  return 0;
}

/***********************************************************************
 * put_string
 ***********************************************************************/

static void put_string(int fd, const char *string)
{
  ssize_t bytes_available = strlen(string);
  ssize_t bytes_written = write(fd, string, bytes_available);
  if (bytes_written < 0)
    {
      fprintf(stderr,
              "Failed to write %ld bytes of string to output, errno=%d\n",
              (long)bytes_available, errno);
      exit(5);
    }
  else if (bytes_written != bytes_available)
    {
      fprintf(stderr, "Only wrote %ld of %ld bytes of string to output\n",
              (long)bytes_written, (long)bytes_available);
      exit(6);
    }
}

/***********************************************************************
 * does_not_return_name/sym
 ***********************************************************************/

static int does_not_return_name(const char *func_name)
{
  int i;

  /* Check every name in the list of (usually) non-returning function */

  for (i = 0; nonreturners[i] != NULL; i++)
    {
      /* Is this function name in the list */

      if (strcmp(func_name, nonreturners[i]) == 0)
        {
          /* Yes, return true now. */

          return 1;
        }
    }

  /* Its not in the list, return false */

  return 0;
}

static int does_not_return_sym(asymbol * sym, void *arg)
{
  const char *func_name = sym->name;
  if (func_name)
    return does_not_return_name(func_name);
  else
    return 0;
}

/***********************************************************************
 * check_for_nonreturning_functions
 ***********************************************************************/

static void check_for_nonreturning_functions(void)
{
  calls_nonreturning_functions =
    traverse_undefined_functions(NULL, does_not_return_sym);
}

/***********************************************************************
 * count_undefined
 ***********************************************************************/

static int count_undefined(asymbol * sym, void *arg)
{
  number_undefined++;
  return 0;
}

/***********************************************************************
 * put_dynimport_decl
 ***********************************************************************/

static int put_dynimport_decl(asymbol * sym, void *arg)
{
  char dynimport_decl[1024];
  const char *func_name = sym->name;
  int fd = (int)arg;

  /* Put the declaration for the dynamic info structure */
  if (func_name)
    {
      sprintf(dynimport_decl, dynimport_decl_format,
              MKINFODECLARGS(func_name, counter));
      put_string(fd, dynimport_decl);
      counter++;
    }
  return 0;
}

/***********************************************************************
 * put_dynimport_array
 ***********************************************************************/

static int put_dynimport_array(asymbol * sym, void *arg)
{
  char dynimport_array[1024];
  const char *func_name = sym->name;
  int fd = (int)arg;

  /* Create the dynimport_array */

  if (func_name)
    {
      sprintf(dynimport_array, dynimport_array_format,
              MKINFOARGS(func_name, counter));
      put_string(fd, dynimport_array);
      counter++;
    }
  return 0;
}

/***********************************************************************
 * put_nxflat_import
 ***********************************************************************/

static int put_nxflat_import(asymbol * sym, void *arg)
{
  char thunk[4096];
  const char *func_name = sym->name;
  int fd = (int)arg;

  if (func_name)
    {
      /* Create the thunk */

      if (does_not_return_name(func_name) != 0)
        {
          /* The special case for functions that may not return */

          sprintf(thunk, nonreturning_dyncall_format, MKCALLARGS(func_name, counter));
        }
      else
        {
          /* The normal case */

          sprintf(thunk, dyncall_format, MKCALLARGS(func_name, counter));
        }

      put_string(fd, thunk);
      counter++;
    }
  return 0;
}

/***********************************************************************
 * put_all_nxflat_import
 ***********************************************************************/

static void put_all_nxflat_import(int fd)
{
  if (number_undefined > 0)
    {
      /* Put all of the declarations for the dynimport structures together. */

      put_string(fd, dynimport_decl_prologue);
      counter = 0;
      (void)traverse_undefined_functions((void *)fd, put_dynimport_decl);

      /* Put all of the dynimport structures together as an array */

      put_string(fd, dynimport_array_prologue);
      counter = 0;
      (void)traverse_undefined_functions((void *)fd, put_dynimport_array);
      put_string(fd, dynimport_array_epilogue);

      /* Put all of the dyncall logic together */

      put_string(fd, dyncall_decl_prologue);
      counter = 0;
      (void)traverse_undefined_functions((void *)fd, put_nxflat_import);
    }
}

/***********************************************************************
 * put_import_name
 ***********************************************************************/

static int put_import_name(asymbol * sym, void *arg)
{
  char import_name[512];
  const char *func_name = sym->name;
  int fd = (int)arg;

  /* Create the import_name */

  if (func_name)
    {
      sprintf(import_name, import_name_strtab_format,
              MKIMPSTRTABARG(func_name, counter));
      put_string(fd, import_name);
      counter++;
    }
  return 0;
}

/***********************************************************************
 * put_import_name_strtab
 ***********************************************************************/

static void inline put_import_name_strtab(int fd)
{
  if (number_undefined > 0)
    {
      counter = 0;
      put_string(fd, import_name_strtab_prologue);
      (void)traverse_undefined_functions((void *)fd, put_import_name);
    }
}

/***********************************************************************
 * put_file_epilogue
 ***********************************************************************/

static void inline put_file_epilogue(int fd)
{
  put_string(fd, file_epilogue);
}

/***********************************************************************
 * put_file_prologue
 ***********************************************************************/

static void inline put_file_prologue(int fd)
{
  put_string(fd, file_prologue);

  if (number_undefined > 0)
    {
      put_string(fd, import_prologue);
    }
}

/***********************************************************************
 * get_file_token
 ***********************************************************************/

#define ISSPACE(c) \
((c==' ')||(c=='\f')||(c=='\n')||(c=='\r')||(c=='\t')||(c=='\v'))

#define ISTERMINATOR(c) (ISSPACE(c)||(c==EOF))

static int get_file_token(FILE * in_stream)
{
  int i;
  int c;

  /* Skip over leading whitespace */

  do
    c = getc(in_stream);
  while ISSPACE
  (c);

  if (c == EOF)
    return EOF;

  /* Add the token to the buffer. Copy characters until the buffer is full, or
   * a terminator is encountered. */

  for (i = 0; ((i < 1023) && !ISTERMINATOR(c)); i++, c = getc(in_stream))
    {
      token[i] = (char)c;
    }

  /* Handle the string truncation case. */

  token[i] = '\0';
  while (!ISTERMINATOR(c))
    c = getc(in_stream);

  /* Return success.  On next entry, we will get the next character after the
   * terminator.  If the terminator was EOF, we should get EOF again. */

  return 0;
}

/***********************************************************************
 * get_token
 ***********************************************************************/

static char *get_token(int *argno, int argc, char **argv)
{
  char *retval = NULL;

  if (include_stream)
    {
      if (get_file_token(include_stream) == EOF)
        {
          fclose(include_stream);
          include_stream = NULL;
          retval = get_token(argno, argc, argv);
        }
      else
        {
          retval = strdup(token);
        }
    }
  else if (*argno >= argc)
    {
      retval = NULL;
    }
  else
    {
      retval = argv[*argno];
      (*argno)++;
    }
  return retval;
}

/***********************************************************************
 * get_arg
 ***********************************************************************/

static char *get_arg(int *argno, int argc, char **argv)
{
  char *retval;

  /* Get the next argument */

  retval = get_token(argno, argc, argv);
  if ((retval == NULL) || (retval[0] == '-'))
    {
      fprintf(stderr, "Option requires an argument\n\n");
      show_usage();
    }
  return retval;
}

/***********************************************************************
 * get_opt
 ***********************************************************************/

static int get_opt(int *argno, int argc, char **argv)
{
  char *opt;
  int len;
  int retval = -1;

  /* Get the next argument */

  opt = get_token(argno, argc, argv);
  if (opt != NULL)
    {
      /* It must be of length 2 and start with a '-' */

      len = strlen(opt);
      if ((len == 2) && (opt[0] == '-'))
        {
          retval = (int)opt[1];
        }
      else
        {
          fprintf(stderr, "%s Unrecognized option\n\n", opt);
          show_usage();
        }
    }
  return retval;
}

/***********************************************************************
 * parse_args
 ***********************************************************************/

static void parse_args(int argc, char **argv)
{
  int argno = 1;
  int opt;

  /* Save our name (for show_usage) */

  program_name = argv[0];

  if (argc < 2)
    {
      fprintf(stderr, "ERROR:  Missing required arguments\n\n");
      show_usage();
    }

  /* Get the name of the input BFD file. This is always the last thing in the
   * argument list.  We decrement argc so that the parsing logic will not look
   * at it. */

  bfd_filename = argv[argc - 1];
  argc--;

  /* Get miscellaneous options from the command line. */

  while ((opt = get_opt(&argno, argc, argv)) != -1)
    {
      switch (opt)
        {
        case 'd':
          dsyms++;
          break;

        case 'f':
          {
            char *filename = get_arg(&argno, argc, argv);
            if (include_stream)
              {
                fprintf(stderr, "Cannot use -f from within a cmd-file\n\n");
                show_usage();
              }
            else
              {
                include_stream = fopen(filename, "r");
                if (!include_stream)
                  {
                    fprintf(stderr, "Could not open cmd-file %s\n\n", filename);
                    show_usage();
                  }
              }
          }
          break;

        case 'o':
          out_filename = get_arg(&argno, argc, argv);
          break;

        case 'v':
          verbose++;
          break;

        case 'w':
          weak_imports++;
          break;

        default:
          fprintf(stderr, "%s Unknown option\n\n", argv[0]);
          show_usage();
          break;
        }
    }
}

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

/***********************************************************************
 * main
 ***********************************************************************/

int main(int argc, char **argv, char **envp)
{
  bfd *bf;
  int out_fd = 0;

  /* Get the input arguments */

  parse_args(argc, argv);

  /* Make sure that we can option the BFD file */

  dbg("Opening BFD file: %s\n", bfd_filename);
  if (!(bf = bfd_openr(bfd_filename, 0)))
    {
      fprintf(stderr, "Failed to open BFD file: %s, errno=%d\n",
              bfd_filename, errno);
      exit(2);
    }

  dbg("Checking format\n");
  if (bfd_check_format(bf, bfd_object) == 0)
    {
      fprintf(stderr, "BFD file %s is not an object file\n", bfd_filename);
      exit(3);
    }

  dbg("Loading symbol table from BFD file %s\n", bfd_filename);
  symbol_table = get_symbols(bf, &number_of_symbols);

  /* Count the number of undefined function symbols */

  (void)traverse_undefined_functions(NULL, count_undefined);

  /* Check if the module calls any non-returning functions (like exit).  These
   * will require some additional setup. */

  check_for_nonreturning_functions();

  /* Make sure that we can open the output file if one is specified. If no
   * out_filename is specified, we'll use stdout. */

  if (out_filename)
    {
      out_fd = open(out_filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);
      if (out_fd < 0)
        {
          fprintf(stderr, "Failed to open output file: %s, errno=%d\n",
                  out_filename, errno);
          exit(4);
        }
    }

  /* Output the thunk file in three pieces: 1. The constant file prologue 2.
   * Library path information (if any) 3. Library file name information (if
   * any) 4. Exported symbole information (if any) 5. Imported symbole
   * information (if any) 6. The constant file epilogue. */

  put_file_prologue(out_fd);
  put_import_name_strtab(out_fd);
  put_all_nxflat_import(out_fd);
  put_file_epilogue(out_fd);

  if (out_fd > 0)
    close(out_fd);
  exit(0);
}