ChangeLog rotatation and copyright year update
[external/binutils.git] / binutils / nlmconv.c
1 /* nlmconv.c -- NLM conversion program
2    Copyright (C) 1993-2015 Free Software Foundation, Inc.
3
4    This file is part of GNU Binutils.
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
19    MA 02110-1301, USA.  */
20
21
22 /* Written by Ian Lance Taylor <ian@cygnus.com>.
23
24    This program can be used to convert any appropriate object file
25    into a NetWare Loadable Module (an NLM).  It will accept a linker
26    specification file which is identical to that accepted by the
27    NetWare linker, NLMLINK.  */
28
29 /* AIX requires this to be the first thing in the file.  */
30 #ifndef __GNUC__
31 # ifdef _AIX
32  #pragma alloca
33 #endif
34 #endif
35
36 #include "sysdep.h"
37 #include "bfd.h"
38 #include "libiberty.h"
39 #include "filenames.h"
40 #include "safe-ctype.h"
41
42 #include "ansidecl.h"
43 #include <time.h>
44 #include <assert.h>
45 #include "getopt.h"
46
47 /* Internal BFD NLM header.  */
48 #include "libnlm.h"
49 #include "nlmconv.h"
50
51 #ifdef NLMCONV_ALPHA
52 #include "coff/sym.h"
53 #include "coff/ecoff.h"
54 #endif
55
56 #include "bucomm.h"
57
58 /* If strerror is just a macro, we want to use the one from libiberty
59    since it will handle undefined values.  */
60 #undef strerror
61 extern char *strerror (int);
62
63 #ifndef SEEK_SET
64 #define SEEK_SET 0
65 #endif
66
67 #ifndef R_OK
68 #define R_OK 4
69 #define W_OK 2
70 #define X_OK 1
71 #endif
72 \f
73 /* Global variables.  */
74
75 /* The name used to invoke the program.  */
76 char *program_name;
77
78 /* Local variables.  */
79
80 /* Whether to print out debugging information (currently just controls
81    whether it prints the linker command if there is one).  */
82 static int debug;
83
84 /* The symbol table.  */
85 static asymbol **symbols;
86
87 /* A section we create in the output file to hold pointers to where
88    the sections of the input file end up.  We will put a pointer to
89    this section in the NLM header.  These is an entry for each input
90    section.  The format is
91        null terminated section name
92        zeroes to adjust to 4 byte boundary
93        4 byte section data file pointer
94        4 byte section size
95    We don't need a version number.  The way we find this information
96    is by finding a stamp in the NLM header information.  If we need to
97    change the format of this information, we can simply change the
98    stamp.  */
99 static asection *secsec;
100
101 /* A temporary file name to be unlinked on exit.  Actually, for most
102    errors, we leave it around.  It's not clear whether that is helpful
103    or not.  */
104 static char *unlink_on_exit;
105
106 /* The list of long options.  */
107 static struct option long_options[] =
108 {
109   { "debug", no_argument, 0, 'd' },
110   { "header-file", required_argument, 0, 'T' },
111   { "help", no_argument, 0, 'h' },
112   { "input-target", required_argument, 0, 'I' },
113   { "input-format", required_argument, 0, 'I' }, /* Obsolete */
114   { "linker", required_argument, 0, 'l' },
115   { "output-target", required_argument, 0, 'O' },
116   { "output-format", required_argument, 0, 'O' }, /* Obsolete */
117   { "version", no_argument, 0, 'V' },
118   { NULL, no_argument, 0, 0 }
119 };
120
121 /* Local routines.  */
122
123 int main (int, char **);
124
125 static void show_usage (FILE *, int);
126 static const char *select_output_format
127   (enum bfd_architecture, unsigned long, bfd_boolean);
128 static void setup_sections (bfd *, asection *, void *);
129 static void copy_sections (bfd *, asection *, void *);
130 static void mangle_relocs
131   (bfd *, asection *, arelent ***, long *, char *, bfd_size_type);
132 static void default_mangle_relocs
133   (bfd *, asection *, arelent ***, long *, char *, bfd_size_type);
134 static char *link_inputs (struct string_list *, char *, char *);
135
136 #ifdef NLMCONV_I386
137 static void i386_mangle_relocs (bfd *, asection *, arelent ***, long *, char *, bfd_size_type);
138 #endif
139
140 #ifdef NLMCONV_ALPHA
141 static void alpha_mangle_relocs (bfd *, asection *, arelent ***, long *, char *, bfd_size_type);
142 #endif
143
144 #ifdef NLMCONV_POWERPC
145 static void powerpc_build_stubs (bfd *, bfd *, asymbol ***, long *);
146 static void powerpc_resolve_stubs (bfd *, bfd *);
147 static void powerpc_mangle_relocs (bfd *, asection *, arelent ***, long *, char *, bfd_size_type);
148 #endif
149 \f
150 /* The main routine.  */
151
152 int
153 main (int argc, char **argv)
154 {
155   int opt;
156   char *input_file = NULL;
157   const char *input_format = NULL;
158   const char *output_format = NULL;
159   const char *header_file = NULL;
160   char *ld_arg = NULL;
161   Nlm_Internal_Fixed_Header fixed_hdr_struct;
162   Nlm_Internal_Variable_Header var_hdr_struct;
163   Nlm_Internal_Version_Header version_hdr_struct;
164   Nlm_Internal_Copyright_Header copyright_hdr_struct;
165   Nlm_Internal_Extended_Header extended_hdr_struct;
166   bfd *inbfd;
167   bfd *outbfd;
168   asymbol **newsyms, **outsyms;
169   long symcount, newsymalloc, newsymcount;
170   long symsize;
171   asection *text_sec, *bss_sec, *data_sec;
172   bfd_vma vma;
173   bfd_size_type align;
174   asymbol *endsym;
175   long i;
176   char inlead, outlead;
177   bfd_boolean gotstart, gotexit, gotcheck;
178   struct stat st;
179   FILE *custom_data = NULL;
180   FILE *help_data = NULL;
181   FILE *message_data = NULL;
182   FILE *rpc_data = NULL;
183   FILE *shared_data = NULL;
184   size_t custom_size = 0;
185   size_t help_size = 0;
186   size_t message_size = 0;
187   size_t module_size = 0;
188   size_t rpc_size = 0;
189   asection *custom_section = NULL;
190   asection *help_section = NULL;
191   asection *message_section = NULL;
192   asection *module_section = NULL;
193   asection *rpc_section = NULL;
194   asection *shared_section = NULL;
195   bfd *sharedbfd;
196   size_t shared_offset = 0;
197   size_t shared_size = 0;
198   static Nlm_Internal_Fixed_Header sharedhdr;
199   int len;
200   char *modname;
201   char **matching;
202
203 #if defined (HAVE_SETLOCALE) && defined (HAVE_LC_MESSAGES)
204   setlocale (LC_MESSAGES, "");
205 #endif
206 #if defined (HAVE_SETLOCALE)
207   setlocale (LC_CTYPE, "");
208 #endif
209   bindtextdomain (PACKAGE, LOCALEDIR);
210   textdomain (PACKAGE);
211
212   program_name = argv[0];
213   xmalloc_set_program_name (program_name);
214
215   expandargv (&argc, &argv);
216
217   bfd_init ();
218   set_default_bfd_target ();
219
220   while ((opt = getopt_long (argc, argv, "dHhI:l:O:T:Vv", long_options,
221                              (int *) NULL))
222          != EOF)
223     {
224       switch (opt)
225         {
226         case 'd':
227           debug = 1;
228           break;
229         case 'H':
230         case 'h':
231           show_usage (stdout, 0);
232           break;
233         case 'I':
234           input_format = optarg;
235           break;
236         case 'l':
237           ld_arg = optarg;
238           break;
239         case 'O':
240           output_format = optarg;
241           break;
242         case 'T':
243           header_file = optarg;
244           break;
245         case 'v':
246         case 'V':
247           print_version ("nlmconv");
248           break;
249         case 0:
250           break;
251         default:
252           show_usage (stderr, 1);
253           break;
254         }
255     }
256
257   /* The input and output files may be named on the command line.  */
258   output_file = NULL;
259   if (optind < argc)
260     {
261       input_file = argv[optind];
262       ++optind;
263       if (optind < argc)
264         {
265           output_file = argv[optind];
266           ++optind;
267           if (optind < argc)
268             show_usage (stderr, 1);
269           if (filename_cmp (input_file, output_file) == 0)
270             {
271               fatal (_("input and output files must be different"));
272             }
273         }
274     }
275
276   /* Initialize the header information to default values.  */
277   fixed_hdr = &fixed_hdr_struct;
278   memset ((void *) &fixed_hdr_struct, 0, sizeof fixed_hdr_struct);
279   var_hdr = &var_hdr_struct;
280   memset ((void *) &var_hdr_struct, 0, sizeof var_hdr_struct);
281   version_hdr = &version_hdr_struct;
282   memset ((void *) &version_hdr_struct, 0, sizeof version_hdr_struct);
283   copyright_hdr = &copyright_hdr_struct;
284   memset ((void *) &copyright_hdr_struct, 0, sizeof copyright_hdr_struct);
285   extended_hdr = &extended_hdr_struct;
286   memset ((void *) &extended_hdr_struct, 0, sizeof extended_hdr_struct);
287   check_procedure = NULL;
288   custom_file = NULL;
289   debug_info = FALSE;
290   exit_procedure = "_Stop";
291   export_symbols = NULL;
292   map_file = NULL;
293   full_map = FALSE;
294   help_file = NULL;
295   import_symbols = NULL;
296   message_file = NULL;
297   modules = NULL;
298   sharelib_file = NULL;
299   start_procedure = "_Prelude";
300   verbose = FALSE;
301   rpc_file = NULL;
302
303   parse_errors = 0;
304
305   /* Parse the header file (if there is one).  */
306   if (header_file != NULL)
307     {
308       if (! nlmlex_file (header_file)
309           || yyparse () != 0
310           || parse_errors != 0)
311         exit (1);
312     }
313
314   if (input_files != NULL)
315     {
316       if (input_file != NULL)
317         {
318           fatal (_("input file named both on command line and with INPUT"));
319         }
320       if (input_files->next == NULL)
321         input_file = input_files->string;
322       else
323         input_file = link_inputs (input_files, ld_arg, map_file);
324     }
325   else if (input_file == NULL)
326     {
327       non_fatal (_("no input file"));
328       show_usage (stderr, 1);
329     }
330
331   inbfd = bfd_openr (input_file, input_format);
332   if (inbfd == NULL)
333     bfd_fatal (input_file);
334
335   if (! bfd_check_format_matches (inbfd, bfd_object, &matching))
336     {
337       bfd_nonfatal (input_file);
338       if (bfd_get_error () == bfd_error_file_ambiguously_recognized)
339         {
340           list_matching_formats (matching);
341           free (matching);
342         }
343       exit (1);
344     }
345
346   if (output_format == NULL)
347     output_format = select_output_format (bfd_get_arch (inbfd),
348                                           bfd_get_mach (inbfd),
349                                           bfd_big_endian (inbfd));
350
351   assert (output_format != NULL);
352
353   /* Use the output file named on the command line if it exists.
354      Otherwise use the file named in the OUTPUT statement.  */
355   if (output_file == NULL)
356     {
357       non_fatal (_("no name for output file"));
358       show_usage (stderr, 1);
359     }
360
361   outbfd = bfd_openw (output_file, output_format);
362   if (outbfd == NULL)
363     bfd_fatal (output_file);
364   if (! bfd_set_format (outbfd, bfd_object))
365     bfd_fatal (output_file);
366
367   assert (bfd_get_flavour (outbfd) == bfd_target_nlm_flavour);
368
369   /* XXX: Should we accept the unknown bfd format here ?  */
370   if (bfd_arch_get_compatible (inbfd, outbfd, TRUE) == NULL)
371     non_fatal (_("warning: input and output formats are not compatible"));
372
373   /* Move the values read from the command file into outbfd.  */
374   *nlm_fixed_header (outbfd) = fixed_hdr_struct;
375   *nlm_variable_header (outbfd) = var_hdr_struct;
376   *nlm_version_header (outbfd) = version_hdr_struct;
377   *nlm_copyright_header (outbfd) = copyright_hdr_struct;
378   *nlm_extended_header (outbfd) = extended_hdr_struct;
379
380   /* Start copying the input BFD to the output BFD.  */
381   if (! bfd_set_file_flags (outbfd, bfd_get_file_flags (inbfd)))
382     bfd_fatal (bfd_get_filename (outbfd));
383
384   symsize = bfd_get_symtab_upper_bound (inbfd);
385   if (symsize < 0)
386     bfd_fatal (input_file);
387   symbols = (asymbol **) xmalloc (symsize);
388   symcount = bfd_canonicalize_symtab (inbfd, symbols);
389   if (symcount < 0)
390     bfd_fatal (input_file);
391
392   /* Make sure we have a .bss section.  */
393   bss_sec = bfd_get_section_by_name (outbfd, NLM_UNINITIALIZED_DATA_NAME);
394   if (bss_sec == NULL)
395     {
396       bss_sec = bfd_make_section_with_flags (outbfd,
397                                              NLM_UNINITIALIZED_DATA_NAME,
398                                              SEC_ALLOC);
399       if (bss_sec == NULL
400           || ! bfd_set_section_alignment (outbfd, bss_sec, 1))
401         bfd_fatal (_("make .bss section"));
402     }
403
404   /* We store the original section names in the .nlmsections section,
405      so that programs which understand it can resurrect the original
406      sections from the NLM.  We will put a pointer to .nlmsections in
407      the NLM header area.  */
408   secsec = bfd_make_section_with_flags (outbfd, ".nlmsections",
409                                         SEC_HAS_CONTENTS);
410   if (secsec == NULL)
411     bfd_fatal (_("make .nlmsections section"));
412
413 #ifdef NLMCONV_POWERPC
414   /* For PowerPC NetWare we need to build stubs for calls to undefined
415      symbols.  Because each stub requires an entry in the TOC section
416      which must be at the same location as other entries in the TOC
417      section, we must do this before determining where the TOC section
418      goes in setup_sections.  */
419   if (bfd_get_arch (inbfd) == bfd_arch_powerpc)
420     powerpc_build_stubs (inbfd, outbfd, &symbols, &symcount);
421 #endif
422
423   /* Set up the sections.  */
424   bfd_map_over_sections (inbfd, setup_sections, (void *) outbfd);
425
426   text_sec = bfd_get_section_by_name (outbfd, NLM_CODE_NAME);
427
428   /* The .bss section immediately follows the .data section.  */
429   data_sec = bfd_get_section_by_name (outbfd, NLM_INITIALIZED_DATA_NAME);
430   if (data_sec != NULL)
431     {
432       bfd_size_type add;
433
434       vma = bfd_get_section_size (data_sec);
435       align = 1 << bss_sec->alignment_power;
436       add = ((vma + align - 1) &~ (align - 1)) - vma;
437       vma += add;
438       if (! bfd_set_section_vma (outbfd, bss_sec, vma))
439         bfd_fatal (_("set .bss vma"));
440       if (add != 0)
441         {
442           bfd_size_type data_size;
443
444           data_size = bfd_get_section_size (data_sec);
445           if (! bfd_set_section_size (outbfd, data_sec, data_size + add))
446             bfd_fatal (_("set .data size"));
447         }
448     }
449
450   /* Adjust symbol information.  */
451   inlead = bfd_get_symbol_leading_char (inbfd);
452   outlead = bfd_get_symbol_leading_char (outbfd);
453   gotstart = FALSE;
454   gotexit = FALSE;
455   gotcheck = FALSE;
456   newsymalloc = 10;
457   newsyms = (asymbol **) xmalloc (newsymalloc * sizeof (asymbol *));
458   newsymcount = 0;
459   endsym = NULL;
460   for (i = 0; i < symcount; i++)
461     {
462       asymbol *sym;
463
464       sym = symbols[i];
465
466       /* Add or remove a leading underscore.  */
467       if (inlead != outlead)
468         {
469           if (inlead != '\0')
470             {
471               if (bfd_asymbol_name (sym)[0] == inlead)
472                 {
473                   if (outlead == '\0')
474                     ++sym->name;
475                   else
476                     {
477                       char *new_name;
478
479                       new_name = xmalloc (strlen (bfd_asymbol_name (sym)) + 1);
480                       new_name[0] = outlead;
481                       strcpy (new_name + 1, bfd_asymbol_name (sym) + 1);
482                       sym->name = new_name;
483                     }
484                 }
485             }
486           else
487             {
488               char *new_name;
489
490               new_name = xmalloc (strlen (bfd_asymbol_name (sym)) + 2);
491               new_name[0] = outlead;
492               strcpy (new_name + 1, bfd_asymbol_name (sym));
493               sym->name = new_name;
494             }
495         }
496
497       /* NLM's have an uninitialized data section, but they do not
498          have a common section in the Unix sense.  Move all common
499          symbols into the .bss section, and mark them as exported.  */
500       if (bfd_is_com_section (bfd_get_section (sym)))
501         {
502           bfd_vma size = sym->value;
503
504           sym->section = bss_sec;
505           sym->value = bfd_get_section_size (bss_sec);
506           size += sym->value;
507           align = 1 << bss_sec->alignment_power;
508           size = (size + align - 1) & ~(align - 1);
509           bfd_set_section_size (outbfd, bss_sec, size);
510           sym->flags |= BSF_EXPORT | BSF_GLOBAL;
511         }
512       else if (bfd_get_section (sym)->output_section != NULL)
513         {
514           /* Move the symbol into the output section.  */
515           sym->value += bfd_get_section (sym)->output_offset;
516           sym->section = bfd_get_section (sym)->output_section;
517           /* This is no longer a section symbol.  */
518           sym->flags &=~ BSF_SECTION_SYM;
519         }
520
521       /* Force _edata and _end to be defined.  This would normally be
522          done by the linker, but the manipulation of the common
523          symbols will confuse it.  */
524       if ((sym->flags & BSF_DEBUGGING) == 0
525           && bfd_asymbol_name (sym)[0] == '_'
526           && bfd_is_und_section (bfd_get_section (sym)))
527         {
528           if (strcmp (bfd_asymbol_name (sym), "_edata") == 0)
529             {
530               sym->section = bss_sec;
531               sym->value = 0;
532             }
533           if (strcmp (bfd_asymbol_name (sym), "_end") == 0)
534             {
535               sym->section = bss_sec;
536               endsym = sym;
537             }
538
539 #ifdef NLMCONV_POWERPC
540           /* For PowerPC NetWare, we define __GOT0.  This is the start
541              of the .got section.  */
542           if (bfd_get_arch (inbfd) == bfd_arch_powerpc
543               && strcmp (bfd_asymbol_name (sym), "__GOT0") == 0)
544             {
545               asection *got_sec;
546
547               got_sec = bfd_get_section_by_name (inbfd, ".got");
548               assert (got_sec != (asection *) NULL);
549               sym->value = got_sec->output_offset;
550               sym->section = got_sec->output_section;
551             }
552 #endif
553         }
554
555       /* If this is a global symbol, check the export list.  */
556       if ((sym->flags & (BSF_EXPORT | BSF_GLOBAL)) != 0)
557         {
558           struct string_list *l;
559           int found_simple;
560
561           /* Unfortunately, a symbol can appear multiple times on the
562              export list, with and without prefixes.  */
563           found_simple = 0;
564           for (l = export_symbols; l != NULL; l = l->next)
565             {
566               if (strcmp (l->string, bfd_asymbol_name (sym)) == 0)
567                 found_simple = 1;
568               else
569                 {
570                   char *zbase;
571
572                   zbase = strchr (l->string, '@');
573                   if (zbase != NULL
574                       && strcmp (zbase + 1, bfd_asymbol_name (sym)) == 0)
575                     {
576                       /* We must add a symbol with this prefix.  */
577                       if (newsymcount >= newsymalloc)
578                         {
579                           newsymalloc += 10;
580                           newsyms = ((asymbol **)
581                                      xrealloc ((void *) newsyms,
582                                                (newsymalloc
583                                                 * sizeof (asymbol *))));
584                         }
585                       newsyms[newsymcount] =
586                         (asymbol *) xmalloc (sizeof (asymbol));
587                       *newsyms[newsymcount] = *sym;
588                       newsyms[newsymcount]->name = l->string;
589                       ++newsymcount;
590                     }
591                 }
592             }
593           if (! found_simple)
594             {
595               /* The unmodified symbol is actually not exported at
596                  all.  */
597               sym->flags &=~ (BSF_GLOBAL | BSF_EXPORT);
598               sym->flags |= BSF_LOCAL;
599             }
600         }
601
602       /* If it's an undefined symbol, see if it's on the import list.
603          Change the prefix if necessary.  */
604       if (bfd_is_und_section (bfd_get_section (sym)))
605         {
606           struct string_list *l;
607
608           for (l = import_symbols; l != NULL; l = l->next)
609             {
610               if (strcmp (l->string, bfd_asymbol_name (sym)) == 0)
611                 break;
612               else
613                 {
614                   char *zbase;
615
616                   zbase = strchr (l->string, '@');
617                   if (zbase != NULL
618                       && strcmp (zbase + 1, bfd_asymbol_name (sym)) == 0)
619                     {
620                       sym->name = l->string;
621                       break;
622                     }
623                 }
624             }
625           if (l == NULL)
626             non_fatal (_("warning: symbol %s imported but not in import list"),
627                        bfd_asymbol_name (sym));
628         }
629
630       /* See if it's one of the special named symbols.  */
631       if ((sym->flags & BSF_DEBUGGING) == 0)
632         {
633           bfd_vma val;
634
635           /* FIXME: If these symbols are not in the .text section, we
636              add the .text section size to the value.  This may not be
637              correct for all targets.  I'm not sure how this should
638              really be handled.  */
639           if (strcmp (bfd_asymbol_name (sym), start_procedure) == 0)
640             {
641               val = bfd_asymbol_value (sym);
642               if (bfd_get_section (sym) == data_sec
643                   && text_sec != (asection *) NULL)
644                 val += bfd_section_size (outbfd, text_sec);
645               if (! bfd_set_start_address (outbfd, val))
646                 bfd_fatal (_("set start address"));
647               gotstart = TRUE;
648             }
649           if (strcmp (bfd_asymbol_name (sym), exit_procedure) == 0)
650             {
651               val = bfd_asymbol_value (sym);
652               if (bfd_get_section (sym) == data_sec
653                   && text_sec != (asection *) NULL)
654                 val += bfd_section_size (outbfd, text_sec);
655               nlm_fixed_header (outbfd)->exitProcedureOffset = val;
656               gotexit = TRUE;
657             }
658           if (check_procedure != NULL
659               && strcmp (bfd_asymbol_name (sym), check_procedure) == 0)
660             {
661               val = bfd_asymbol_value (sym);
662               if (bfd_get_section (sym) == data_sec
663                   && text_sec != (asection *) NULL)
664                 val += bfd_section_size (outbfd, text_sec);
665               nlm_fixed_header (outbfd)->checkUnloadProcedureOffset = val;
666               gotcheck = TRUE;
667             }
668         }
669     }
670
671   if (endsym != NULL)
672     {
673       endsym->value = bfd_get_section_size (bss_sec);
674
675       /* FIXME: If any relocs referring to _end use inplace addends,
676          then I think they need to be updated.  This is handled by
677          i386_mangle_relocs.  Is it needed for any other object
678          formats?  */
679     }
680
681   if (newsymcount == 0)
682     outsyms = symbols;
683   else
684     {
685       outsyms = (asymbol **) xmalloc ((symcount + newsymcount + 1)
686                                       * sizeof (asymbol *));
687       memcpy (outsyms, symbols, symcount * sizeof (asymbol *));
688       memcpy (outsyms + symcount, newsyms, newsymcount * sizeof (asymbol *));
689       outsyms[symcount + newsymcount] = NULL;
690     }
691
692   bfd_set_symtab (outbfd, outsyms, symcount + newsymcount);
693
694   if (! gotstart)
695     non_fatal (_("warning: START procedure %s not defined"), start_procedure);
696   if (! gotexit)
697     non_fatal (_("warning: EXIT procedure %s not defined"), exit_procedure);
698   if (check_procedure != NULL && ! gotcheck)
699     non_fatal (_("warning: CHECK procedure %s not defined"), check_procedure);
700
701   /* Add additional sections required for the header information.  */
702   if (custom_file != NULL)
703     {
704       custom_data = fopen (custom_file, "r");
705       if (custom_data == NULL
706           || fstat (fileno (custom_data), &st) < 0)
707         {
708           fprintf (stderr, "%s:%s: %s\n", program_name, custom_file,
709                    strerror (errno));
710           custom_file = NULL;
711         }
712       else
713         {
714           custom_size = st.st_size;
715           custom_section = bfd_make_section_with_flags (outbfd, ".nlmcustom",
716                                                         SEC_HAS_CONTENTS);
717           if (custom_section == NULL
718               || ! bfd_set_section_size (outbfd, custom_section, custom_size))
719             bfd_fatal (_("custom section"));
720         }
721     }
722   if (help_file != NULL)
723     {
724       help_data = fopen (help_file, "r");
725       if (help_data == NULL
726           || fstat (fileno (help_data), &st) < 0)
727         {
728           fprintf (stderr, "%s:%s: %s\n", program_name, help_file,
729                    strerror (errno));
730           help_file = NULL;
731         }
732       else
733         {
734           help_size = st.st_size;
735           help_section = bfd_make_section_with_flags (outbfd, ".nlmhelp",
736                                                       SEC_HAS_CONTENTS);
737           if (help_section == NULL
738               || ! bfd_set_section_size (outbfd, help_section, help_size))
739             bfd_fatal (_("help section"));
740           LITMEMCPY (nlm_extended_header (outbfd)->stamp, "MeSsAgEs");
741         }
742     }
743   if (message_file != NULL)
744     {
745       message_data = fopen (message_file, "r");
746       if (message_data == NULL
747           || fstat (fileno (message_data), &st) < 0)
748         {
749           fprintf (stderr, "%s:%s: %s\n", program_name, message_file,
750                    strerror (errno));
751           message_file = NULL;
752         }
753       else
754         {
755           message_size = st.st_size;
756           message_section = bfd_make_section_with_flags (outbfd,
757                                                          ".nlmmessages",
758                                                          SEC_HAS_CONTENTS);
759           if (message_section == NULL
760               || ! bfd_set_section_size (outbfd, message_section, message_size))
761             bfd_fatal (_("message section"));
762           LITMEMCPY (nlm_extended_header (outbfd)->stamp, "MeSsAgEs");
763         }
764     }
765   if (modules != NULL)
766     {
767       struct string_list *l;
768
769       module_size = 0;
770       for (l = modules; l != NULL; l = l->next)
771         module_size += strlen (l->string) + 1;
772       module_section = bfd_make_section_with_flags (outbfd, ".nlmmodules",
773                                                     SEC_HAS_CONTENTS);
774       if (module_section == NULL
775           || ! bfd_set_section_size (outbfd, module_section, module_size))
776         bfd_fatal (_("module section"));
777     }
778   if (rpc_file != NULL)
779     {
780       rpc_data = fopen (rpc_file, "r");
781       if (rpc_data == NULL
782           || fstat (fileno (rpc_data), &st) < 0)
783         {
784           fprintf (stderr, "%s:%s: %s\n", program_name, rpc_file,
785                    strerror (errno));
786           rpc_file = NULL;
787         }
788       else
789         {
790           rpc_size = st.st_size;
791           rpc_section = bfd_make_section_with_flags (outbfd, ".nlmrpc",
792                                                      SEC_HAS_CONTENTS);
793           if (rpc_section == NULL
794               || ! bfd_set_section_size (outbfd, rpc_section, rpc_size))
795             bfd_fatal (_("rpc section"));
796           LITMEMCPY (nlm_extended_header (outbfd)->stamp, "MeSsAgEs");
797         }
798     }
799   if (sharelib_file != NULL)
800     {
801       sharedbfd = bfd_openr (sharelib_file, output_format);
802       if (sharedbfd == NULL
803           || ! bfd_check_format (sharedbfd, bfd_object))
804         {
805           fprintf (stderr, "%s:%s: %s\n", program_name, sharelib_file,
806                    bfd_errmsg (bfd_get_error ()));
807           sharelib_file = NULL;
808         }
809       else
810         {
811           sharedhdr = *nlm_fixed_header (sharedbfd);
812           bfd_close (sharedbfd);
813           shared_data = fopen (sharelib_file, "r");
814           if (shared_data == NULL
815               || (fstat (fileno (shared_data), &st) < 0))
816             {
817               fprintf (stderr, "%s:%s: %s\n", program_name, sharelib_file,
818                        strerror (errno));
819               sharelib_file = NULL;
820             }
821           else
822             {
823               /* If we were clever, we could just copy out the
824                  sections of the shared library which we actually
825                  need.  However, we would have to figure out the sizes
826                  of the external and public information, and that can
827                  not be done without reading through them.  */
828               if (sharedhdr.uninitializedDataSize > 0)
829                 {
830                   /* There is no place to record this information.  */
831                   non_fatal (_("%s: warning: shared libraries can not have uninitialized data"),
832                              sharelib_file);
833                 }
834               shared_offset = st.st_size;
835               if (shared_offset > (size_t) sharedhdr.codeImageOffset)
836                 shared_offset = sharedhdr.codeImageOffset;
837               if (shared_offset > (size_t) sharedhdr.dataImageOffset)
838                 shared_offset = sharedhdr.dataImageOffset;
839               if (shared_offset > (size_t) sharedhdr.relocationFixupOffset)
840                 shared_offset = sharedhdr.relocationFixupOffset;
841               if (shared_offset > (size_t) sharedhdr.externalReferencesOffset)
842                 shared_offset = sharedhdr.externalReferencesOffset;
843               if (shared_offset > (size_t) sharedhdr.publicsOffset)
844                 shared_offset = sharedhdr.publicsOffset;
845               shared_size = st.st_size - shared_offset;
846               shared_section = bfd_make_section_with_flags (outbfd,
847                                                             ".nlmshared",
848                                                             SEC_HAS_CONTENTS);
849               if (shared_section == NULL
850                   || ! bfd_set_section_size (outbfd, shared_section,
851                                              shared_size))
852                 bfd_fatal (_("shared section"));
853               LITMEMCPY (nlm_extended_header (outbfd)->stamp, "MeSsAgEs");
854             }
855         }
856     }
857
858   /* Check whether a version was given.  */
859   if (!CONST_STRNEQ (version_hdr->stamp, "VeRsIoN#"))
860     non_fatal (_("warning: No version number given"));
861
862   /* At least for now, always create an extended header, because that
863      is what NLMLINK does.  */
864   LITMEMCPY (nlm_extended_header (outbfd)->stamp, "MeSsAgEs");
865
866   LITMEMCPY (nlm_cygnus_ext_header (outbfd)->stamp, "CyGnUsEx");
867
868   /* If the date was not given, force it in.  */
869   if (nlm_version_header (outbfd)->month == 0
870       && nlm_version_header (outbfd)->day == 0
871       && nlm_version_header (outbfd)->year == 0)
872     {
873       time_t now;
874       struct tm *ptm;
875
876       time (&now);
877       ptm = localtime (&now);
878       nlm_version_header (outbfd)->month = ptm->tm_mon + 1;
879       nlm_version_header (outbfd)->day = ptm->tm_mday;
880       nlm_version_header (outbfd)->year = ptm->tm_year + 1900;
881       LITMEMCPY (version_hdr->stamp, "VeRsIoN#");
882     }
883
884 #ifdef NLMCONV_POWERPC
885   /* Resolve the stubs we build for PowerPC NetWare.  */
886   if (bfd_get_arch (inbfd) == bfd_arch_powerpc)
887     powerpc_resolve_stubs (inbfd, outbfd);
888 #endif
889
890   /* Copy over the sections.  */
891   bfd_map_over_sections (inbfd, copy_sections, (void *) outbfd);
892
893   /* Finish up the header information.  */
894   if (custom_file != NULL)
895     {
896       void *data;
897
898       data = xmalloc (custom_size);
899       if (fread (data, 1, custom_size, custom_data) != custom_size)
900         non_fatal (_("%s: read: %s"), custom_file, strerror (errno));
901       else
902         {
903           if (! bfd_set_section_contents (outbfd, custom_section, data,
904                                           (file_ptr) 0, custom_size))
905             bfd_fatal (_("custom section"));
906           nlm_fixed_header (outbfd)->customDataOffset =
907             custom_section->filepos;
908           nlm_fixed_header (outbfd)->customDataSize = custom_size;
909         }
910       free (data);
911     }
912   if (! debug_info)
913     {
914       /* As a special hack, the backend recognizes a debugInfoOffset
915          of -1 to mean that it should not output any debugging
916          information.  This can not be handling by fiddling with the
917          symbol table because exported symbols appear in both the
918          export information and the debugging information.  */
919       nlm_fixed_header (outbfd)->debugInfoOffset = (file_ptr) -1;
920     }
921   if (full_map)
922     non_fatal (_("warning: FULLMAP is not supported; try ld -M"));
923   if (help_file != NULL)
924     {
925       void *data;
926
927       data = xmalloc (help_size);
928       if (fread (data, 1, help_size, help_data) != help_size)
929         non_fatal (_("%s: read: %s"), help_file, strerror (errno));
930       else
931         {
932           if (! bfd_set_section_contents (outbfd, help_section, data,
933                                           (file_ptr) 0, help_size))
934             bfd_fatal (_("help section"));
935           nlm_extended_header (outbfd)->helpFileOffset =
936             help_section->filepos;
937           nlm_extended_header (outbfd)->helpFileLength = help_size;
938         }
939       free (data);
940     }
941   if (message_file != NULL)
942     {
943       void *data;
944
945       data = xmalloc (message_size);
946       if (fread (data, 1, message_size, message_data) != message_size)
947         non_fatal (_("%s: read: %s"), message_file, strerror (errno));
948       else
949         {
950           if (! bfd_set_section_contents (outbfd, message_section, data,
951                                           (file_ptr) 0, message_size))
952             bfd_fatal (_("message section"));
953           nlm_extended_header (outbfd)->messageFileOffset =
954             message_section->filepos;
955           nlm_extended_header (outbfd)->messageFileLength = message_size;
956
957           /* FIXME: Are these offsets correct on all platforms?  Are
958              they 32 bits on all platforms?  What endianness?  */
959           nlm_extended_header (outbfd)->languageID =
960             bfd_h_get_32 (outbfd, (bfd_byte *) data + 106);
961           nlm_extended_header (outbfd)->messageCount =
962             bfd_h_get_32 (outbfd, (bfd_byte *) data + 110);
963         }
964       free (data);
965     }
966   if (modules != NULL)
967     {
968       void *data;
969       unsigned char *set;
970       struct string_list *l;
971       bfd_size_type c;
972
973       data = xmalloc (module_size);
974       c = 0;
975       set = (unsigned char *) data;
976       for (l = modules; l != NULL; l = l->next)
977         {
978           *set = strlen (l->string);
979           strncpy ((char *) set + 1, l->string, *set);
980           set += *set + 1;
981           ++c;
982         }
983       if (! bfd_set_section_contents (outbfd, module_section, data,
984                                       (file_ptr) 0, module_size))
985         bfd_fatal (_("module section"));
986       nlm_fixed_header (outbfd)->moduleDependencyOffset =
987         module_section->filepos;
988       nlm_fixed_header (outbfd)->numberOfModuleDependencies = c;
989     }
990   if (rpc_file != NULL)
991     {
992       void *data;
993
994       data = xmalloc (rpc_size);
995       if (fread (data, 1, rpc_size, rpc_data) != rpc_size)
996         non_fatal (_("%s: read: %s"), rpc_file, strerror (errno));
997       else
998         {
999           if (! bfd_set_section_contents (outbfd, rpc_section, data,
1000                                           (file_ptr) 0, rpc_size))
1001             bfd_fatal (_("rpc section"));
1002           nlm_extended_header (outbfd)->RPCDataOffset =
1003             rpc_section->filepos;
1004           nlm_extended_header (outbfd)->RPCDataLength = rpc_size;
1005         }
1006       free (data);
1007     }
1008   if (sharelib_file != NULL)
1009     {
1010       void *data;
1011
1012       data = xmalloc (shared_size);
1013       if (fseek (shared_data, shared_offset, SEEK_SET) != 0
1014           || fread (data, 1, shared_size, shared_data) != shared_size)
1015         non_fatal (_("%s: read: %s"), sharelib_file, strerror (errno));
1016       else
1017         {
1018           if (! bfd_set_section_contents (outbfd, shared_section, data,
1019                                           (file_ptr) 0, shared_size))
1020             bfd_fatal (_("shared section"));
1021         }
1022       nlm_extended_header (outbfd)->sharedCodeOffset =
1023         sharedhdr.codeImageOffset - shared_offset + shared_section->filepos;
1024       nlm_extended_header (outbfd)->sharedCodeLength =
1025         sharedhdr.codeImageSize;
1026       nlm_extended_header (outbfd)->sharedDataOffset =
1027         sharedhdr.dataImageOffset - shared_offset + shared_section->filepos;
1028       nlm_extended_header (outbfd)->sharedDataLength =
1029         sharedhdr.dataImageSize;
1030       nlm_extended_header (outbfd)->sharedRelocationFixupOffset =
1031         (sharedhdr.relocationFixupOffset
1032          - shared_offset
1033          + shared_section->filepos);
1034       nlm_extended_header (outbfd)->sharedRelocationFixupCount =
1035         sharedhdr.numberOfRelocationFixups;
1036       nlm_extended_header (outbfd)->sharedExternalReferenceOffset =
1037         (sharedhdr.externalReferencesOffset
1038          - shared_offset
1039          + shared_section->filepos);
1040       nlm_extended_header (outbfd)->sharedExternalReferenceCount =
1041         sharedhdr.numberOfExternalReferences;
1042       nlm_extended_header (outbfd)->sharedPublicsOffset =
1043         sharedhdr.publicsOffset - shared_offset + shared_section->filepos;
1044       nlm_extended_header (outbfd)->sharedPublicsCount =
1045         sharedhdr.numberOfPublics;
1046       nlm_extended_header (outbfd)->sharedDebugRecordOffset =
1047         sharedhdr.debugInfoOffset - shared_offset + shared_section->filepos;
1048       nlm_extended_header (outbfd)->sharedDebugRecordCount =
1049         sharedhdr.numberOfDebugRecords;
1050       nlm_extended_header (outbfd)->SharedInitializationOffset =
1051         sharedhdr.codeStartOffset;
1052       nlm_extended_header (outbfd)->SharedExitProcedureOffset =
1053         sharedhdr.exitProcedureOffset;
1054       free (data);
1055     }
1056
1057   {
1058     const int    max_len  = NLM_MODULE_NAME_SIZE - 2;
1059     const char * filename = lbasename (output_file);
1060     
1061     len = strlen (filename);
1062     if (len > max_len)
1063       len = max_len;
1064     nlm_fixed_header (outbfd)->moduleName[0] = len;
1065
1066     strncpy (nlm_fixed_header (outbfd)->moduleName + 1, filename, max_len);
1067     nlm_fixed_header (outbfd)->moduleName[max_len + 1] = '\0';
1068
1069     for (modname = nlm_fixed_header (outbfd)->moduleName;
1070          *modname != '\0';
1071          modname++)
1072       *modname = TOUPPER (*modname);
1073   }
1074
1075   strncpy (nlm_variable_header (outbfd)->oldThreadName, " LONG",
1076            NLM_OLD_THREAD_NAME_LENGTH);
1077
1078   nlm_cygnus_ext_header (outbfd)->offset = secsec->filepos;
1079   nlm_cygnus_ext_header (outbfd)->length = bfd_section_size (outbfd, secsec);
1080
1081   if (! bfd_close (outbfd))
1082     bfd_fatal (output_file);
1083   if (! bfd_close (inbfd))
1084     bfd_fatal (input_file);
1085
1086   if (unlink_on_exit != NULL)
1087     unlink (unlink_on_exit);
1088
1089   return 0;
1090 }
1091 \f
1092
1093 /* Show a usage message and exit.  */
1094
1095 static void
1096 show_usage (FILE *file, int status)
1097 {
1098   fprintf (file, _("Usage: %s [option(s)] [in-file [out-file]]\n"), program_name);
1099   fprintf (file, _(" Convert an object file into a NetWare Loadable Module\n"));
1100   fprintf (file, _(" The options are:\n\
1101   -I --input-target=<bfdname>   Set the input binary file format\n\
1102   -O --output-target=<bfdname>  Set the output binary file format\n\
1103   -T --header-file=<file>       Read <file> for NLM header information\n\
1104   -l --linker=<linker>          Use <linker> for any linking\n\
1105   -d --debug                    Display on stderr the linker command line\n\
1106   @<file>                       Read options from <file>.\n\
1107   -h --help                     Display this information\n\
1108   -v --version                  Display the program's version\n\
1109 "));
1110   if (REPORT_BUGS_TO[0] && status == 0)
1111     fprintf (file, _("Report bugs to %s\n"), REPORT_BUGS_TO);
1112   exit (status);
1113 }
1114 \f
1115 /* Select the output format based on the input architecture, machine,
1116    and endianness.  This chooses the appropriate NLM target.  */
1117
1118 static const char *
1119 select_output_format (enum bfd_architecture arch, unsigned long mach,
1120                       bfd_boolean bigendian ATTRIBUTE_UNUSED)
1121 {
1122   switch (arch)
1123     {
1124 #ifdef NLMCONV_I386
1125     case bfd_arch_i386:
1126       return "nlm32-i386";
1127 #endif
1128 #ifdef NLMCONV_SPARC
1129     case bfd_arch_sparc:
1130       return "nlm32-sparc";
1131 #endif
1132 #ifdef NLMCONV_ALPHA
1133     case bfd_arch_alpha:
1134       return "nlm32-alpha";
1135 #endif
1136 #ifdef NLMCONV_POWERPC
1137     case bfd_arch_powerpc:
1138       return "nlm32-powerpc";
1139 #endif
1140     default:
1141       fatal (_("support not compiled in for %s"),
1142              bfd_printable_arch_mach (arch, mach));
1143     }
1144   /*NOTREACHED*/
1145 }
1146 \f
1147 /* The BFD sections are copied in two passes.  This function selects
1148    the output section for each input section, and sets up the section
1149    name, size, etc.  */
1150
1151 static void
1152 setup_sections (bfd *inbfd ATTRIBUTE_UNUSED, asection *insec, void *data_ptr)
1153 {
1154   bfd *outbfd = (bfd *) data_ptr;
1155   flagword f;
1156   const char *outname;
1157   asection *outsec;
1158   bfd_vma offset;
1159   bfd_size_type align;
1160   bfd_size_type add;
1161   bfd_size_type secsecsize;
1162
1163   f = bfd_get_section_flags (inbfd, insec);
1164   if (f & SEC_CODE)
1165     outname = NLM_CODE_NAME;
1166   else if ((f & SEC_LOAD) && (f & SEC_HAS_CONTENTS))
1167     outname = NLM_INITIALIZED_DATA_NAME;
1168   else if (f & SEC_ALLOC)
1169     outname = NLM_UNINITIALIZED_DATA_NAME;
1170   else
1171     outname = bfd_section_name (inbfd, insec);
1172
1173   outsec = bfd_get_section_by_name (outbfd, outname);
1174   if (outsec == NULL)
1175     {
1176       outsec = bfd_make_section (outbfd, outname);
1177       if (outsec == NULL)
1178         bfd_fatal (_("make section"));
1179     }
1180
1181   insec->output_section = outsec;
1182
1183   offset = bfd_section_size (outbfd, outsec);
1184   align = 1 << bfd_section_alignment (inbfd, insec);
1185   add = ((offset + align - 1) &~ (align - 1)) - offset;
1186   insec->output_offset = offset + add;
1187
1188   if (! bfd_set_section_size (outbfd, outsec,
1189                               (bfd_section_size (outbfd, outsec)
1190                                + bfd_section_size (inbfd, insec)
1191                                + add)))
1192     bfd_fatal (_("set section size"));
1193
1194   if ((bfd_section_alignment (inbfd, insec)
1195        > bfd_section_alignment (outbfd, outsec))
1196       && ! bfd_set_section_alignment (outbfd, outsec,
1197                                       bfd_section_alignment (inbfd, insec)))
1198     bfd_fatal (_("set section alignment"));
1199
1200   if (! bfd_set_section_flags (outbfd, outsec,
1201                                f | bfd_get_section_flags (outbfd, outsec)))
1202     bfd_fatal (_("set section flags"));
1203
1204   bfd_set_reloc (outbfd, outsec, (arelent **) NULL, 0);
1205
1206   /* For each input section we allocate space for an entry in
1207      .nlmsections.  */
1208   secsecsize = bfd_section_size (outbfd, secsec);
1209   secsecsize += strlen (bfd_section_name (inbfd, insec)) + 1;
1210   secsecsize = (secsecsize + 3) &~ 3;
1211   secsecsize += 8;
1212   if (! bfd_set_section_size (outbfd, secsec, secsecsize))
1213     bfd_fatal (_("set .nlmsections size"));
1214 }
1215
1216 /* Copy the section contents.  */
1217
1218 static void
1219 copy_sections (bfd *inbfd, asection *insec, void *data_ptr)
1220 {
1221   static bfd_size_type secsecoff = 0;
1222   bfd *outbfd = (bfd *) data_ptr;
1223   const char *inname;
1224   asection *outsec;
1225   bfd_size_type size;
1226   void *contents;
1227   long reloc_size;
1228   bfd_byte buf[4];
1229   bfd_size_type add;
1230
1231   inname = bfd_section_name (inbfd, insec);
1232
1233   outsec = insec->output_section;
1234   assert (outsec != NULL);
1235
1236   size = bfd_get_section_size (insec);
1237
1238   if ((bfd_get_section_flags (inbfd, insec) & SEC_HAS_CONTENTS) == 0)
1239     contents = NULL;
1240   else
1241     {
1242       contents = xmalloc (size);
1243       if (! bfd_get_section_contents (inbfd, insec, contents,
1244                                       (file_ptr) 0, size))
1245         bfd_fatal (bfd_get_filename (inbfd));
1246     }
1247
1248   reloc_size = bfd_get_reloc_upper_bound (inbfd, insec);
1249   if (reloc_size < 0)
1250     bfd_fatal (bfd_get_filename (inbfd));
1251   if (reloc_size != 0)
1252     {
1253       arelent **relocs;
1254       long reloc_count;
1255
1256       relocs = (arelent **) xmalloc (reloc_size);
1257       reloc_count = bfd_canonicalize_reloc (inbfd, insec, relocs, symbols);
1258       if (reloc_count < 0)
1259         bfd_fatal (bfd_get_filename (inbfd));
1260       mangle_relocs (outbfd, insec, &relocs, &reloc_count, (char *) contents,
1261                      size);
1262
1263       /* FIXME: refers to internal BFD fields.  */
1264       if (outsec->orelocation != (arelent **) NULL)
1265         {
1266           bfd_size_type total_count;
1267           arelent **combined;
1268
1269           total_count = reloc_count + outsec->reloc_count;
1270           combined = (arelent **) xmalloc (total_count * sizeof (arelent *));
1271           memcpy (combined, outsec->orelocation,
1272                   outsec->reloc_count * sizeof (arelent *));
1273           memcpy (combined + outsec->reloc_count, relocs,
1274                   (size_t) (reloc_count * sizeof (arelent *)));
1275           free (outsec->orelocation);
1276           reloc_count = total_count;
1277           relocs = combined;
1278         }
1279
1280       bfd_set_reloc (outbfd, outsec, relocs, reloc_count);
1281     }
1282
1283   if (contents != NULL)
1284     {
1285       if (! bfd_set_section_contents (outbfd, outsec, contents,
1286                                       insec->output_offset, size))
1287         bfd_fatal (bfd_get_filename (outbfd));
1288       free (contents);
1289     }
1290
1291   /* Add this section to .nlmsections.  */
1292   if (! bfd_set_section_contents (outbfd, secsec, (void *) inname, secsecoff,
1293                                   strlen (inname) + 1))
1294     bfd_fatal (_("set .nlmsection contents"));
1295   secsecoff += strlen (inname) + 1;
1296
1297   add = ((secsecoff + 3) &~ 3) - secsecoff;
1298   if (add != 0)
1299     {
1300       bfd_h_put_32 (outbfd, (bfd_vma) 0, buf);
1301       if (! bfd_set_section_contents (outbfd, secsec, buf, secsecoff, add))
1302         bfd_fatal (_("set .nlmsection contents"));
1303       secsecoff += add;
1304     }
1305
1306   if (contents != NULL)
1307     bfd_h_put_32 (outbfd, (bfd_vma) outsec->filepos, buf);
1308   else
1309     bfd_h_put_32 (outbfd, (bfd_vma) 0, buf);
1310   if (! bfd_set_section_contents (outbfd, secsec, buf, secsecoff, 4))
1311     bfd_fatal (_("set .nlmsection contents"));
1312   secsecoff += 4;
1313
1314   bfd_h_put_32 (outbfd, (bfd_vma) size, buf);
1315   if (! bfd_set_section_contents (outbfd, secsec, buf, secsecoff, 4))
1316     bfd_fatal (_("set .nlmsection contents"));
1317   secsecoff += 4;
1318 }
1319
1320 /* Some, perhaps all, NetWare targets require changing the relocs used
1321    by the input formats.  */
1322
1323 static void
1324 mangle_relocs (bfd *outbfd, asection *insec, arelent ***relocs_ptr,
1325                long *reloc_count_ptr, char *contents,
1326                bfd_size_type contents_size)
1327 {
1328   switch (bfd_get_arch (outbfd))
1329     {
1330 #ifdef NLMCONV_I386
1331     case bfd_arch_i386:
1332       i386_mangle_relocs (outbfd, insec, relocs_ptr, reloc_count_ptr,
1333                           contents, contents_size);
1334       break;
1335 #endif
1336 #ifdef NLMCONV_ALPHA
1337     case bfd_arch_alpha:
1338       alpha_mangle_relocs (outbfd, insec, relocs_ptr, reloc_count_ptr,
1339                            contents, contents_size);
1340       break;
1341 #endif
1342 #ifdef NLMCONV_POWERPC
1343     case bfd_arch_powerpc:
1344       powerpc_mangle_relocs (outbfd, insec, relocs_ptr, reloc_count_ptr,
1345                              contents, contents_size);
1346       break;
1347 #endif
1348     default:
1349       default_mangle_relocs (outbfd, insec, relocs_ptr, reloc_count_ptr,
1350                              contents, contents_size);
1351       break;
1352     }
1353 }
1354
1355 /* By default all we need to do for relocs is change the address by
1356    the output_offset.  */
1357
1358 static void
1359 default_mangle_relocs (bfd *outbfd ATTRIBUTE_UNUSED, asection *insec,
1360                        arelent ***relocs_ptr, long *reloc_count_ptr,
1361                        char *contents ATTRIBUTE_UNUSED,
1362                        bfd_size_type contents_size ATTRIBUTE_UNUSED)
1363 {
1364   if (insec->output_offset != 0)
1365     {
1366       long reloc_count;
1367       arelent **relocs;
1368       long i;
1369
1370       reloc_count = *reloc_count_ptr;
1371       relocs = *relocs_ptr;
1372       for (i = 0; i < reloc_count; i++, relocs++)
1373         (*relocs)->address += insec->output_offset;
1374     }
1375 }
1376 \f
1377 #ifdef NLMCONV_I386
1378
1379 /* NetWare on the i386 supports a restricted set of relocs, which are
1380    different from those used on other i386 targets.  This routine
1381    converts the relocs.  It is, obviously, very target dependent.  At
1382    the moment, the nlm32-i386 backend performs similar translations;
1383    however, it is more reliable and efficient to do them here.  */
1384
1385 static reloc_howto_type nlm_i386_pcrel_howto =
1386   HOWTO (1,                     /* type */
1387          0,                     /* rightshift */
1388          2,                     /* size (0 = byte, 1 = short, 2 = long) */
1389          32,                    /* bitsize */
1390          TRUE,                  /* pc_relative */
1391          0,                     /* bitpos */
1392          complain_overflow_signed, /* complain_on_overflow */
1393          0,                     /* special_function */
1394          "DISP32",              /* name */
1395          TRUE,                  /* partial_inplace */
1396          0xffffffff,            /* src_mask */
1397          0xffffffff,            /* dst_mask */
1398          TRUE);                 /* pcrel_offset */
1399
1400 static void
1401 i386_mangle_relocs (bfd *outbfd, asection *insec, arelent ***relocs_ptr,
1402                     long *reloc_count_ptr, char *contents,
1403                     bfd_size_type contents_size)
1404 {
1405   long reloc_count, i;
1406   arelent **relocs;
1407
1408   reloc_count = *reloc_count_ptr;
1409   relocs = *relocs_ptr;
1410   for (i = 0; i < reloc_count; i++)
1411     {
1412       arelent *rel;
1413       asymbol *sym;
1414       bfd_size_type address;
1415       bfd_vma addend;
1416
1417       rel = *relocs++;
1418       sym = *rel->sym_ptr_ptr;
1419
1420       /* We're moving the relocs from the input section to the output
1421          section, so we must adjust the address accordingly.  */
1422       address = rel->address;
1423       rel->address += insec->output_offset;
1424
1425       /* Note that no serious harm will ensue if we fail to change a
1426          reloc.  The backend will fail when writing out the reloc.  */
1427
1428       /* Make sure this reloc is within the data we have.  We use only
1429          4 byte relocs here, so we insist on having 4 bytes.  */
1430       if (address + 4 > contents_size)
1431         continue;
1432
1433       /* A PC relative reloc entirely within a single section is
1434          completely unnecessary.  This can be generated by ld -r.  */
1435       if (sym == insec->symbol
1436           && rel->howto != NULL
1437           && rel->howto->pc_relative
1438           && ! rel->howto->pcrel_offset)
1439         {
1440           --*reloc_count_ptr;
1441           --relocs;
1442           memmove (relocs, relocs + 1,
1443                    (size_t) ((reloc_count - i) * sizeof (arelent *)));
1444           continue;
1445         }
1446
1447       /* Get the amount the relocation will add in.  */
1448       addend = rel->addend + sym->value;
1449
1450       /* NetWare doesn't support PC relative relocs against defined
1451          symbols, so we have to eliminate them by doing the relocation
1452          now.  We can only do this if the reloc is within a single
1453          section.  */
1454       if (rel->howto != NULL
1455           && rel->howto->pc_relative
1456           && bfd_get_section (sym) == insec->output_section)
1457         {
1458           bfd_vma val;
1459
1460           if (rel->howto->pcrel_offset)
1461             addend -= address;
1462
1463           val = bfd_get_32 (outbfd, (bfd_byte *) contents + address);
1464           val += addend;
1465           bfd_put_32 (outbfd, val, (bfd_byte *) contents + address);
1466
1467           --*reloc_count_ptr;
1468           --relocs;
1469           memmove (relocs, relocs + 1,
1470                    (size_t) ((reloc_count - i) * sizeof (arelent *)));
1471           continue;
1472         }
1473
1474       /* NetWare doesn't support reloc addends, so we get rid of them
1475          here by simply adding them into the object data.  We handle
1476          the symbol value, if any, the same way.  */
1477       if (addend != 0
1478           && rel->howto != NULL
1479           && rel->howto->rightshift == 0
1480           && rel->howto->size == 2
1481           && rel->howto->bitsize == 32
1482           && rel->howto->bitpos == 0
1483           && rel->howto->src_mask == 0xffffffff
1484           && rel->howto->dst_mask == 0xffffffff)
1485         {
1486           bfd_vma val;
1487
1488           val = bfd_get_32 (outbfd, (bfd_byte *) contents + address);
1489           val += addend;
1490           bfd_put_32 (outbfd, val, (bfd_byte *) contents + address);
1491
1492           /* Adjust the reloc for the changes we just made.  */
1493           rel->addend = 0;
1494           if (! bfd_is_und_section (bfd_get_section (sym)))
1495             rel->sym_ptr_ptr = bfd_get_section (sym)->symbol_ptr_ptr;
1496         }
1497
1498       /* NetWare uses a reloc with pcrel_offset set.  We adjust
1499          pc_relative relocs accordingly.  We are going to change the
1500          howto field, so we can only do this if the current one is
1501          compatible.  We should check that special_function is NULL
1502          here, but at the moment coff-i386 uses a special_function
1503          which does not affect what we are doing here.  */
1504       if (rel->howto != NULL
1505           && rel->howto->pc_relative
1506           && ! rel->howto->pcrel_offset
1507           && rel->howto->rightshift == 0
1508           && rel->howto->size == 2
1509           && rel->howto->bitsize == 32
1510           && rel->howto->bitpos == 0
1511           && rel->howto->src_mask == 0xffffffff
1512           && rel->howto->dst_mask == 0xffffffff)
1513         {
1514           bfd_vma val;
1515
1516           /* When pcrel_offset is not set, it means that the negative
1517              of the address of the memory location is stored in the
1518              memory location.  We must add it back in.  */
1519           val = bfd_get_32 (outbfd, (bfd_byte *) contents + address);
1520           val += address;
1521           bfd_put_32 (outbfd, val, (bfd_byte *) contents + address);
1522
1523           /* We must change to a new howto.  */
1524           rel->howto = &nlm_i386_pcrel_howto;
1525         }
1526     }
1527 }
1528
1529 #endif /* NLMCONV_I386 */
1530 \f
1531 #ifdef NLMCONV_ALPHA
1532
1533 /* On the Alpha the first reloc for every section must be a special
1534    relocs which hold the GP address.  Also, the first reloc in the
1535    file must be a special reloc which holds the address of the .lita
1536    section.  */
1537
1538 static reloc_howto_type nlm32_alpha_nw_howto =
1539   HOWTO (ALPHA_R_NW_RELOC,      /* type */
1540          0,                     /* rightshift */
1541          0,                     /* size (0 = byte, 1 = short, 2 = long) */
1542          0,                     /* bitsize */
1543          FALSE,                 /* pc_relative */
1544          0,                     /* bitpos */
1545          complain_overflow_dont, /* complain_on_overflow */
1546          0,                     /* special_function */
1547          "NW_RELOC",            /* name */
1548          FALSE,                 /* partial_inplace */
1549          0,                     /* src_mask */
1550          0,                     /* dst_mask */
1551          FALSE);                /* pcrel_offset */
1552
1553 static void
1554 alpha_mangle_relocs (bfd *outbfd, asection *insec,
1555                      arelent ***relocs_ptr, long *reloc_count_ptr,
1556                      char *contents ATTRIBUTE_UNUSED,
1557                      bfd_size_type contents_size ATTRIBUTE_UNUSED)
1558 {
1559   long old_reloc_count;
1560   arelent **old_relocs;
1561   arelent **relocs;
1562
1563   old_reloc_count = *reloc_count_ptr;
1564   old_relocs = *relocs_ptr;
1565   relocs = (arelent **) xmalloc ((old_reloc_count + 3) * sizeof (arelent *));
1566   *relocs_ptr = relocs;
1567
1568   if (nlm_alpha_backend_data (outbfd)->lita_address == 0)
1569     {
1570       bfd *inbfd;
1571       asection *lita_section;
1572
1573       inbfd = insec->owner;
1574       lita_section = bfd_get_section_by_name (inbfd, _LITA);
1575       if (lita_section != (asection *) NULL)
1576         {
1577           nlm_alpha_backend_data (outbfd)->lita_address =
1578             bfd_get_section_vma (inbfd, lita_section);
1579           nlm_alpha_backend_data (outbfd)->lita_size =
1580             bfd_section_size (inbfd, lita_section);
1581         }
1582       else
1583         {
1584           /* Avoid outputting this reloc again.  */
1585           nlm_alpha_backend_data (outbfd)->lita_address = 4;
1586         }
1587
1588       *relocs = (arelent *) xmalloc (sizeof (arelent));
1589       (*relocs)->sym_ptr_ptr = bfd_abs_section_ptr->symbol_ptr_ptr;
1590       (*relocs)->address = nlm_alpha_backend_data (outbfd)->lita_address;
1591       (*relocs)->addend = nlm_alpha_backend_data (outbfd)->lita_size + 1;
1592       (*relocs)->howto = &nlm32_alpha_nw_howto;
1593       ++relocs;
1594       ++(*reloc_count_ptr);
1595     }
1596
1597   /* Get the GP value from bfd.  */
1598   if (nlm_alpha_backend_data (outbfd)->gp == 0)
1599     nlm_alpha_backend_data (outbfd)->gp =
1600       bfd_ecoff_get_gp_value (insec->owner);
1601
1602   *relocs = (arelent *) xmalloc (sizeof (arelent));
1603   (*relocs)->sym_ptr_ptr = bfd_abs_section_ptr->symbol_ptr_ptr;
1604   (*relocs)->address = nlm_alpha_backend_data (outbfd)->gp;
1605   (*relocs)->addend = 0;
1606   (*relocs)->howto = &nlm32_alpha_nw_howto;
1607   ++relocs;
1608   ++(*reloc_count_ptr);
1609
1610   memcpy (relocs, old_relocs, (size_t) old_reloc_count * sizeof (arelent *));
1611   relocs[old_reloc_count] = (arelent *) NULL;
1612
1613   free (old_relocs);
1614
1615   if (insec->output_offset != 0)
1616     {
1617       bfd_size_type i;
1618
1619       for (i = 0; i < (bfd_size_type) old_reloc_count; i++, relocs++)
1620         (*relocs)->address += insec->output_offset;
1621     }
1622 }
1623
1624 #endif /* NLMCONV_ALPHA */
1625 \f
1626 #ifdef NLMCONV_POWERPC
1627
1628 /* We keep a linked list of stubs which we must build.  Because BFD
1629    requires us to know the sizes of all sections before we can set the
1630    contents of any, we must figure out which stubs we want to build
1631    before we can actually build any of them.  */
1632
1633 struct powerpc_stub
1634 {
1635   /* Next stub in linked list.  */
1636   struct powerpc_stub *next;
1637
1638   /* Symbol whose value is the start of the stub.  This is a symbol
1639      whose name begins with `.'.  */
1640   asymbol *start;
1641
1642   /* Symbol we are going to create a reloc against.  This is a symbol
1643      with the same name as START but without the leading `.'.  */
1644   asymbol *reloc;
1645
1646   /* The TOC index for this stub.  This is the index into the TOC
1647      section at which the reloc is created.  */
1648   unsigned int toc_index;
1649 };
1650
1651 /* The linked list of stubs.  */
1652
1653 static struct powerpc_stub *powerpc_stubs;
1654
1655 /* This is what a stub looks like.  The first instruction will get
1656    adjusted with the correct TOC index.  */
1657
1658 static unsigned long powerpc_stub_insns[] =
1659 {
1660   0x81820000,           /* lwz   r12,0(r2) */
1661   0x90410014,           /* stw   r2,20(r1) */
1662   0x800c0000,           /* lwz   r0,0(r12) */
1663   0x804c0004,           /* lwz   r2,r(r12) */
1664   0x7c0903a6,           /* mtctr r0 */
1665   0x4e800420,           /* bctr */
1666   0,                    /* Traceback table.  */
1667   0xc8000,
1668   0
1669 };
1670
1671 #define POWERPC_STUB_INSN_COUNT \
1672   (sizeof powerpc_stub_insns / sizeof powerpc_stub_insns[0])
1673
1674 #define POWERPC_STUB_SIZE (4 * POWERPC_STUB_INSN_COUNT)
1675
1676 /* Each stub uses a four byte TOC entry.  */
1677 #define POWERPC_STUB_TOC_ENTRY_SIZE (4)
1678
1679 /* The original size of the .got section.  */
1680 static bfd_size_type powerpc_initial_got_size;
1681
1682 /* Look for all undefined symbols beginning with `.', and prepare to
1683    build a stub for each one.  */
1684
1685 static void
1686 powerpc_build_stubs (bfd *inbfd, bfd *outbfd ATTRIBUTE_UNUSED,
1687                      asymbol ***symbols_ptr, long *symcount_ptr)
1688 {
1689   asection *stub_sec;
1690   asection *got_sec;
1691   unsigned int got_base;
1692   long i;
1693   long symcount;
1694   long stubcount;
1695
1696   /* Make a section to hold stubs.  We don't set SEC_HAS_CONTENTS for
1697      the section to prevent copy_sections from reading from it.  */
1698   stub_sec = bfd_make_section_with_flags (inbfd, ".stubs",
1699                                           (SEC_CODE
1700                                            | SEC_RELOC
1701                                            | SEC_ALLOC
1702                                            | SEC_LOAD));
1703   if (stub_sec == (asection *) NULL
1704       || ! bfd_set_section_alignment (inbfd, stub_sec, 2))
1705     bfd_fatal (".stubs");
1706
1707   /* Get the TOC section, which is named .got.  */
1708   got_sec = bfd_get_section_by_name (inbfd, ".got");
1709   if (got_sec == (asection *) NULL)
1710     {
1711       got_sec = bfd_make_section_with_flags (inbfd, ".got",
1712                                              (SEC_DATA
1713                                               | SEC_RELOC
1714                                               | SEC_ALLOC
1715                                               | SEC_LOAD
1716                                               | SEC_HAS_CONTENTS));
1717       if (got_sec == (asection *) NULL
1718           || ! bfd_set_section_alignment (inbfd, got_sec, 2))
1719         bfd_fatal (".got");
1720     }
1721
1722   powerpc_initial_got_size = bfd_section_size (inbfd, got_sec);
1723   got_base = powerpc_initial_got_size;
1724   got_base = (got_base + 3) &~ 3;
1725
1726   stubcount = 0;
1727
1728   symcount = *symcount_ptr;
1729   for (i = 0; i < symcount; i++)
1730     {
1731       asymbol *sym;
1732       asymbol *newsym;
1733       char *newname;
1734       struct powerpc_stub *item;
1735
1736       sym = (*symbols_ptr)[i];
1737
1738       /* We must make a stub for every undefined symbol whose name
1739          starts with '.'.  */
1740       if (bfd_asymbol_name (sym)[0] != '.'
1741           || ! bfd_is_und_section (bfd_get_section (sym)))
1742         continue;
1743
1744       /* Make a new undefined symbol with the same name but without
1745          the leading `.'.  */
1746       newsym = xmalloc (sizeof (asymbol));
1747       *newsym = *sym;
1748       newname = xmalloc (strlen (bfd_asymbol_name (sym)));
1749       strcpy (newname, bfd_asymbol_name (sym) + 1);
1750       newsym->name = newname;
1751
1752       /* Define the `.' symbol to be in the stub section.  */
1753       sym->section = stub_sec;
1754       sym->value = stubcount * POWERPC_STUB_SIZE;
1755       /* We set the BSF_DYNAMIC flag here so that we can check it when
1756          we are mangling relocs.  FIXME: This is a hack.  */
1757       sym->flags = BSF_LOCAL | BSF_DYNAMIC;
1758
1759       /* Add this stub to the linked list.  */
1760       item = (struct powerpc_stub *) xmalloc (sizeof (struct powerpc_stub));
1761       item->start = sym;
1762       item->reloc = newsym;
1763       item->toc_index = got_base + stubcount * POWERPC_STUB_TOC_ENTRY_SIZE;
1764
1765       item->next = powerpc_stubs;
1766       powerpc_stubs = item;
1767
1768       ++stubcount;
1769     }
1770
1771   if (stubcount > 0)
1772     {
1773       asymbol **s;
1774       struct powerpc_stub *l;
1775
1776       /* Add the new symbols we just created to the symbol table.  */
1777       *symbols_ptr = (asymbol **) xrealloc ((char *) *symbols_ptr,
1778                                             ((symcount + stubcount)
1779                                              * sizeof (asymbol)));
1780       *symcount_ptr += stubcount;
1781       s = &(*symbols_ptr)[symcount];
1782       for (l = powerpc_stubs; l != (struct powerpc_stub *) NULL; l = l->next)
1783         *s++ = l->reloc;
1784
1785       /* Set the size of the .stubs section and increase the size of
1786          the .got section.  */
1787       if (! bfd_set_section_size (inbfd, stub_sec,
1788                                   stubcount * POWERPC_STUB_SIZE)
1789           || ! bfd_set_section_size (inbfd, got_sec,
1790                                      (got_base
1791                                       + (stubcount
1792                                          * POWERPC_STUB_TOC_ENTRY_SIZE))))
1793         bfd_fatal (_("stub section sizes"));
1794     }
1795 }
1796
1797 /* Resolve all the stubs for PowerPC NetWare.  We fill in the contents
1798    of the output section, and create new relocs in the TOC.  */
1799
1800 static void
1801 powerpc_resolve_stubs (bfd *inbfd, bfd *outbfd)
1802 {
1803   bfd_byte buf[POWERPC_STUB_SIZE];
1804   unsigned int i;
1805   unsigned int stubcount;
1806   arelent **relocs;
1807   asection *got_sec;
1808   arelent **r;
1809   struct powerpc_stub *l;
1810
1811   if (powerpc_stubs == (struct powerpc_stub *) NULL)
1812     return;
1813
1814   for (i = 0; i < POWERPC_STUB_INSN_COUNT; i++)
1815     bfd_put_32 (outbfd, (bfd_vma) powerpc_stub_insns[i], buf + i * 4);
1816
1817   got_sec = bfd_get_section_by_name (inbfd, ".got");
1818   assert (got_sec != (asection *) NULL);
1819   assert (got_sec->output_section->orelocation == (arelent **) NULL);
1820
1821   stubcount = 0;
1822   for (l = powerpc_stubs; l != (struct powerpc_stub *) NULL; l = l->next)
1823     ++stubcount;
1824   relocs = (arelent **) xmalloc (stubcount * sizeof (arelent *));
1825
1826   r = relocs;
1827   for (l = powerpc_stubs; l != (struct powerpc_stub *) NULL; l = l->next)
1828     {
1829       arelent *reloc;
1830
1831       /* Adjust the first instruction to use the right TOC index.  */
1832       bfd_put_32 (outbfd, (bfd_vma) powerpc_stub_insns[0] + l->toc_index, buf);
1833
1834       /* Write this stub out.  */
1835       if (! bfd_set_section_contents (outbfd,
1836                                       bfd_get_section (l->start),
1837                                       buf,
1838                                       l->start->value,
1839                                       POWERPC_STUB_SIZE))
1840         bfd_fatal (_("writing stub"));
1841
1842       /* Create a new reloc for the TOC entry.  */
1843       reloc = (arelent *) xmalloc (sizeof (arelent));
1844       reloc->sym_ptr_ptr = &l->reloc;
1845       reloc->address = l->toc_index + got_sec->output_offset;
1846       reloc->addend = 0;
1847       reloc->howto = bfd_reloc_type_lookup (inbfd, BFD_RELOC_32);
1848
1849       *r++ = reloc;
1850     }
1851
1852   bfd_set_reloc (outbfd, got_sec->output_section, relocs, stubcount);
1853 }
1854
1855 /* Adjust relocation entries for PowerPC NetWare.  We do not output
1856    TOC relocations.  The object code already contains the offset from
1857    the TOC pointer.  When the function is called, the TOC register,
1858    r2, will be set to the correct TOC value, so there is no need for
1859    any further reloc.  */
1860
1861 static void
1862 powerpc_mangle_relocs (bfd *outbfd, asection *insec,
1863                        arelent ***relocs_ptr,
1864                        long *reloc_count_ptr, char *contents,
1865                        bfd_size_type contents_size ATTRIBUTE_UNUSED)
1866 {
1867   reloc_howto_type *toc_howto;
1868   long reloc_count;
1869   arelent **relocs;
1870   long i;
1871
1872   toc_howto = bfd_reloc_type_lookup (insec->owner, BFD_RELOC_PPC_TOC16);
1873   if (toc_howto == (reloc_howto_type *) NULL)
1874     abort ();
1875
1876   /* If this is the .got section, clear out all the contents beyond
1877      the initial size.  We must do this here because copy_sections is
1878      going to write out whatever we return in the contents field.  */
1879   if (strcmp (bfd_get_section_name (insec->owner, insec), ".got") == 0)
1880     memset (contents + powerpc_initial_got_size, 0,
1881             (size_t) (bfd_get_section_size (insec) - powerpc_initial_got_size));
1882
1883   reloc_count = *reloc_count_ptr;
1884   relocs = *relocs_ptr;
1885   for (i = 0; i < reloc_count; i++)
1886     {
1887       arelent *rel;
1888       asymbol *sym;
1889       bfd_vma sym_value;
1890
1891       rel = *relocs++;
1892       sym = *rel->sym_ptr_ptr;
1893
1894       /* Convert any relocs against the .bss section into relocs
1895          against the .data section.  */
1896       if (strcmp (bfd_get_section_name (outbfd, bfd_get_section (sym)),
1897                   NLM_UNINITIALIZED_DATA_NAME) == 0)
1898         {
1899           asection *datasec;
1900
1901           datasec = bfd_get_section_by_name (outbfd,
1902                                              NLM_INITIALIZED_DATA_NAME);
1903           if (datasec != NULL)
1904             {
1905               rel->addend += (bfd_get_section_vma (outbfd,
1906                                                    bfd_get_section (sym))
1907                               + sym->value);
1908               rel->sym_ptr_ptr = datasec->symbol_ptr_ptr;
1909               sym = *rel->sym_ptr_ptr;
1910             }
1911         }
1912
1913       /* We must be able to resolve all PC relative relocs at this
1914          point.  If we get a branch to an undefined symbol we build a
1915          stub, since NetWare will resolve undefined symbols into a
1916          pointer to a function descriptor.  */
1917       if (rel->howto->pc_relative)
1918         {
1919           /* This check for whether a symbol is in the same section as
1920              the reloc will be wrong if there is a PC relative reloc
1921              between two sections both of which were placed in the
1922              same output section.  This should not happen.  */
1923           if (bfd_get_section (sym) != insec->output_section)
1924             non_fatal (_("unresolved PC relative reloc against %s"),
1925                        bfd_asymbol_name (sym));
1926           else
1927             {
1928               bfd_vma val;
1929
1930               assert (rel->howto->size == 2 && rel->howto->pcrel_offset);
1931               val = bfd_get_32 (outbfd, (bfd_byte *) contents + rel->address);
1932               val = ((val &~ rel->howto->dst_mask)
1933                      | (((val & rel->howto->src_mask)
1934                          + (sym->value - rel->address)
1935                          + rel->addend)
1936                         & rel->howto->dst_mask));
1937               bfd_put_32 (outbfd, val, (bfd_byte *) contents + rel->address);
1938
1939               /* If this reloc is against an stubbed symbol and the
1940                  next instruction is
1941                      cror 31,31,31
1942                  then we replace the next instruction with
1943                      lwz  r2,20(r1)
1944                  This reloads the TOC pointer after a stub call.  */
1945               if (bfd_asymbol_name (sym)[0] == '.'
1946                   && (sym->flags & BSF_DYNAMIC) != 0
1947                   && (bfd_get_32 (outbfd,
1948                                   (bfd_byte *) contents + rel->address + 4)
1949                       == 0x4ffffb82)) /* cror 31,31,31 */
1950                 bfd_put_32 (outbfd, (bfd_vma) 0x80410014, /* lwz r2,20(r1) */
1951                             (bfd_byte *) contents + rel->address + 4);
1952
1953               --*reloc_count_ptr;
1954               --relocs;
1955               memmove (relocs, relocs + 1,
1956                        (size_t) ((reloc_count - 1) * sizeof (arelent *)));
1957               continue;
1958             }
1959         }
1960
1961       /* When considering a TOC reloc, we do not want to include the
1962          symbol value.  The symbol will be start of the TOC section
1963          (which is named .got).  We do want to include the addend.  */
1964       if (rel->howto == toc_howto)
1965         sym_value = 0;
1966       else
1967         sym_value = sym->value;
1968
1969       /* If this is a relocation against a symbol with a value, or
1970          there is a reloc addend, we need to update the addend in the
1971          object file.  */
1972       if (sym_value + rel->addend != 0)
1973         {
1974           bfd_vma val;
1975
1976           switch (rel->howto->size)
1977             {
1978             case 1:
1979               val = bfd_get_16 (outbfd,
1980                                 (bfd_byte *) contents + rel->address);
1981               val = ((val &~ rel->howto->dst_mask)
1982                      | (((val & rel->howto->src_mask)
1983                          + sym_value
1984                          + rel->addend)
1985                         & rel->howto->dst_mask));
1986               if ((bfd_signed_vma) val < - 0x8000
1987                   || (bfd_signed_vma) val >= 0x8000)
1988                 non_fatal (_("overflow when adjusting relocation against %s"),
1989                            bfd_asymbol_name (sym));
1990               bfd_put_16 (outbfd, val, (bfd_byte *) contents + rel->address);
1991               break;
1992
1993             case 2:
1994               val = bfd_get_32 (outbfd,
1995                                 (bfd_byte *) contents + rel->address);
1996               val = ((val &~ rel->howto->dst_mask)
1997                      | (((val & rel->howto->src_mask)
1998                          + sym_value
1999                          + rel->addend)
2000                         & rel->howto->dst_mask));
2001               bfd_put_32 (outbfd, val, (bfd_byte *) contents + rel->address);
2002               break;
2003
2004             default:
2005               abort ();
2006             }
2007
2008           if (! bfd_is_und_section (bfd_get_section (sym)))
2009             rel->sym_ptr_ptr = bfd_get_section (sym)->symbol_ptr_ptr;
2010           rel->addend = 0;
2011         }
2012
2013       /* Now that we have incorporated the addend, remove any TOC
2014          relocs.  */
2015       if (rel->howto == toc_howto)
2016         {
2017           --*reloc_count_ptr;
2018           --relocs;
2019           memmove (relocs, relocs + 1,
2020                    (size_t) ((reloc_count - i) * sizeof (arelent *)));
2021           continue;
2022         }
2023
2024       rel->address += insec->output_offset;
2025     }
2026 }
2027
2028 #endif /* NLMCONV_POWERPC */
2029 \f
2030 /* Name of linker.  */
2031 #ifndef LD_NAME
2032 #define LD_NAME "ld"
2033 #endif
2034
2035 /* The user has specified several input files.  Invoke the linker to
2036    link them all together, and convert and delete the resulting output
2037    file.  */
2038
2039 static char *
2040 link_inputs (struct string_list *inputs, char *ld, char * mfile)
2041 {
2042   size_t c;
2043   struct string_list *q;
2044   char **argv;
2045   size_t i;
2046   int pid;
2047   int status;
2048   char *errfmt;
2049   char *errarg;
2050
2051   c = 0;
2052   for (q = inputs; q != NULL; q = q->next)
2053     ++c;
2054
2055   argv = (char **) alloca ((c + 7) * sizeof (char *));
2056
2057 #ifndef __MSDOS__
2058   if (ld == NULL)
2059     {
2060       char *p;
2061
2062       /* Find the linker to invoke based on how nlmconv was run.  */
2063       p = program_name + strlen (program_name);
2064       while (p != program_name)
2065         {
2066           if (p[-1] == '/')
2067             {
2068               ld = (char *) xmalloc (p - program_name + strlen (LD_NAME) + 1);
2069               memcpy (ld, program_name, p - program_name);
2070               strcpy (ld + (p - program_name), LD_NAME);
2071               break;
2072             }
2073           --p;
2074         }
2075     }
2076 #endif
2077
2078   if (ld == NULL)
2079     ld = (char *) LD_NAME;
2080
2081   unlink_on_exit = make_temp_file (".O");
2082
2083   argv[0] = ld;
2084   argv[1] = (char *) "-Ur";
2085   argv[2] = (char *) "-o";
2086   argv[3] = unlink_on_exit;
2087   /* If we have been given the name of a mapfile and that
2088      name is not 'stderr' then pass it on to the linker.  */
2089   if (mfile
2090       && * mfile
2091       && strcmp (mfile, "stderr") == 0)
2092     {
2093       argv[4] = (char *) "-Map";
2094       argv[5] = mfile;
2095       i = 6;
2096     }
2097   else
2098     i = 4;
2099
2100   for (q = inputs; q != NULL; q = q->next, i++)
2101     argv[i] = q->string;
2102   argv[i] = NULL;
2103
2104   if (debug)
2105     {
2106       for (i = 0; argv[i] != NULL; i++)
2107         fprintf (stderr, " %s", argv[i]);
2108       fprintf (stderr, "\n");
2109     }
2110
2111   pid = pexecute (ld, argv, program_name, (char *) NULL, &errfmt, &errarg,
2112                   PEXECUTE_SEARCH | PEXECUTE_ONE);
2113   if (pid == -1)
2114     {
2115       fprintf (stderr, _("%s: execution of %s failed: "), program_name, ld);
2116       fprintf (stderr, errfmt, errarg);
2117       unlink (unlink_on_exit);
2118       exit (1);
2119     }
2120
2121   if (pwait (pid, &status, 0) < 0)
2122     {
2123       perror ("pwait");
2124       unlink (unlink_on_exit);
2125       exit (1);
2126     }
2127
2128   if (status != 0)
2129     {
2130       non_fatal (_("Execution of %s failed"), ld);
2131       unlink (unlink_on_exit);
2132       exit (1);
2133     }
2134
2135   return unlink_on_exit;
2136 }