* aout-encap.c: Fix comment typos.
[platform/upstream/binutils.git] / bfd / som.c
1 /* bfd back-end for HP PA-RISC SOM objects.
2    Copyright 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
3    2000, 2001
4    Free Software Foundation, Inc.
5
6    Contributed by the Center for Software Science at the
7    University of Utah.
8
9    This file is part of BFD, the Binary File Descriptor library.
10
11    This program is free software; you can redistribute it and/or modify
12    it under the terms of the GNU General Public License as published by
13    the Free Software Foundation; either version 2 of the License, or
14    (at your option) any later version.
15
16    This program is distributed in the hope that it will be useful,
17    but WITHOUT ANY WARRANTY; without even the implied warranty of
18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19    GNU General Public License for more details.
20
21    You should have received a copy of the GNU General Public License
22    along with this program; if not, write to the Free Software
23    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
24    02111-1307, USA.  */
25
26 #include "alloca-conf.h"
27 #include "bfd.h"
28 #include "sysdep.h"
29
30 #if defined (HOST_HPPAHPUX) || defined (HOST_HPPABSD) || defined (HOST_HPPAOSF) || defined(HOST_HPPAMPEIX)
31
32 #include "libbfd.h"
33 #include "som.h"
34 #include "safe-ctype.h"
35
36 #include <sys/param.h>
37 #include <signal.h>
38 #include <machine/reg.h>
39 #include <sys/file.h>
40
41 /* Magic not defined in standard HP-UX header files until 8.0 */
42
43 #ifndef CPU_PA_RISC1_0
44 #define CPU_PA_RISC1_0 0x20B
45 #endif /* CPU_PA_RISC1_0 */
46
47 #ifndef CPU_PA_RISC1_1
48 #define CPU_PA_RISC1_1 0x210
49 #endif /* CPU_PA_RISC1_1 */
50
51 #ifndef CPU_PA_RISC2_0
52 #define CPU_PA_RISC2_0 0x214
53 #endif /* CPU_PA_RISC2_0 */
54
55 #ifndef _PA_RISC1_0_ID
56 #define _PA_RISC1_0_ID CPU_PA_RISC1_0
57 #endif /* _PA_RISC1_0_ID */
58
59 #ifndef _PA_RISC1_1_ID
60 #define _PA_RISC1_1_ID CPU_PA_RISC1_1
61 #endif /* _PA_RISC1_1_ID */
62
63 #ifndef _PA_RISC2_0_ID
64 #define _PA_RISC2_0_ID CPU_PA_RISC2_0
65 #endif /* _PA_RISC2_0_ID */
66
67 #ifndef _PA_RISC_MAXID
68 #define _PA_RISC_MAXID  0x2FF
69 #endif /* _PA_RISC_MAXID */
70
71 #ifndef _PA_RISC_ID
72 #define _PA_RISC_ID(__m_num)            \
73     (((__m_num) == _PA_RISC1_0_ID) ||   \
74      ((__m_num) >= _PA_RISC1_1_ID && (__m_num) <= _PA_RISC_MAXID))
75 #endif /* _PA_RISC_ID */
76
77 /* HIUX in it's infinite stupidity changed the names for several "well
78    known" constants.  Work around such braindamage.  Try the HPUX version
79    first, then the HIUX version, and finally provide a default.  */
80 #ifdef HPUX_AUX_ID
81 #define EXEC_AUX_ID HPUX_AUX_ID
82 #endif
83
84 #if !defined (EXEC_AUX_ID) && defined (HIUX_AUX_ID)
85 #define EXEC_AUX_ID HIUX_AUX_ID
86 #endif
87
88 #ifndef EXEC_AUX_ID
89 #define EXEC_AUX_ID 0
90 #endif
91
92 /* Size (in chars) of the temporary buffers used during fixup and string
93    table writes.   */
94
95 #define SOM_TMP_BUFSIZE 8192
96
97 /* Size of the hash table in archives.  */
98 #define SOM_LST_HASH_SIZE 31
99
100 /* Max number of SOMs to be found in an archive.  */
101 #define SOM_LST_MODULE_LIMIT 1024
102
103 /* Generic alignment macro.  */
104 #define SOM_ALIGN(val, alignment) \
105   (((val) + (alignment) - 1) &~ ((unsigned long) (alignment) - 1))
106
107 /* SOM allows any one of the four previous relocations to be reused
108    with a "R_PREV_FIXUP" relocation entry.  Since R_PREV_FIXUP
109    relocations are always a single byte, using a R_PREV_FIXUP instead
110    of some multi-byte relocation makes object files smaller.
111
112    Note one side effect of using a R_PREV_FIXUP is the relocation that
113    is being repeated moves to the front of the queue.  */
114 struct reloc_queue {
115   unsigned char *reloc;
116   unsigned int size;
117 } reloc_queue[4];
118
119 /* This fully describes the symbol types which may be attached to
120    an EXPORT or IMPORT directive.  Only SOM uses this formation
121    (ELF has no need for it).  */
122 typedef enum {
123   SYMBOL_TYPE_UNKNOWN,
124   SYMBOL_TYPE_ABSOLUTE,
125   SYMBOL_TYPE_CODE,
126   SYMBOL_TYPE_DATA,
127   SYMBOL_TYPE_ENTRY,
128   SYMBOL_TYPE_MILLICODE,
129   SYMBOL_TYPE_PLABEL,
130   SYMBOL_TYPE_PRI_PROG,
131   SYMBOL_TYPE_SEC_PROG,
132 } pa_symbol_type;
133
134 struct section_to_type {
135   char *section;
136   char type;
137 };
138
139 /* Assorted symbol information that needs to be derived from the BFD symbol
140    and/or the BFD backend private symbol data.  */
141 struct som_misc_symbol_info {
142   unsigned int symbol_type;
143   unsigned int symbol_scope;
144   unsigned int arg_reloc;
145   unsigned int symbol_info;
146   unsigned int symbol_value;
147   unsigned int priv_level;
148   unsigned int secondary_def;
149 };
150
151 /* Forward declarations */
152
153 static boolean som_mkobject PARAMS ((bfd *));
154 static const bfd_target * som_object_setup PARAMS ((bfd *,
155                                                     struct header *,
156                                                     struct som_exec_auxhdr *,
157                                                     unsigned long));
158 static boolean setup_sections PARAMS ((bfd *, struct header *, unsigned long));
159 static const bfd_target * som_object_p PARAMS ((bfd *));
160 static boolean som_write_object_contents PARAMS ((bfd *));
161 static boolean som_slurp_string_table PARAMS ((bfd *));
162 static unsigned int som_slurp_symbol_table PARAMS ((bfd *));
163 static long som_get_symtab_upper_bound PARAMS ((bfd *));
164 static long som_canonicalize_reloc PARAMS ((bfd *, sec_ptr,
165                                             arelent **, asymbol **));
166 static long som_get_reloc_upper_bound PARAMS ((bfd *, sec_ptr));
167 static unsigned int som_set_reloc_info PARAMS ((unsigned char *, unsigned int,
168                                                 arelent *, asection *,
169                                                 asymbol **, boolean));
170 static boolean som_slurp_reloc_table PARAMS ((bfd *, asection *,
171                                               asymbol **, boolean));
172 static long som_get_symtab PARAMS ((bfd *, asymbol **));
173 static asymbol * som_make_empty_symbol PARAMS ((bfd *));
174 static void som_print_symbol PARAMS ((bfd *, PTR,
175                                       asymbol *, bfd_print_symbol_type));
176 static boolean som_new_section_hook PARAMS ((bfd *, asection *));
177 static boolean som_bfd_copy_private_symbol_data PARAMS ((bfd *, asymbol *,
178                                                           bfd *, asymbol *));
179 static boolean som_bfd_copy_private_section_data PARAMS ((bfd *, asection *,
180                                                           bfd *, asection *));
181 static boolean som_bfd_copy_private_bfd_data PARAMS ((bfd *, bfd *));
182 #define som_bfd_merge_private_bfd_data _bfd_generic_bfd_merge_private_bfd_data
183 #define som_bfd_set_private_flags _bfd_generic_bfd_set_private_flags
184 static boolean som_bfd_is_local_label_name PARAMS ((bfd *, const char *));
185 static boolean som_set_section_contents PARAMS ((bfd *, sec_ptr, PTR,
186                                                  file_ptr, bfd_size_type));
187 static boolean som_get_section_contents PARAMS ((bfd *, sec_ptr, PTR,
188                                                  file_ptr, bfd_size_type));
189 static boolean som_set_arch_mach PARAMS ((bfd *, enum bfd_architecture,
190                                           unsigned long));
191 static boolean som_find_nearest_line PARAMS ((bfd *, asection *,
192                                               asymbol **, bfd_vma,
193                                               const char **,
194                                               const char **,
195                                               unsigned int *));
196 static void som_get_symbol_info PARAMS ((bfd *, asymbol *, symbol_info *));
197 static asection * bfd_section_from_som_symbol PARAMS ((bfd *,
198                                         struct symbol_dictionary_record *));
199 static int log2 PARAMS ((unsigned int));
200 static bfd_reloc_status_type hppa_som_reloc PARAMS ((bfd *, arelent *,
201                                                      asymbol *, PTR,
202                                                      asection *, bfd *,
203                                                      char **));
204 static void som_initialize_reloc_queue PARAMS ((struct reloc_queue *));
205 static void som_reloc_queue_insert PARAMS ((unsigned char *, unsigned int,
206                                             struct reloc_queue *));
207 static void som_reloc_queue_fix PARAMS ((struct reloc_queue *, unsigned int));
208 static int som_reloc_queue_find PARAMS ((unsigned char *, unsigned int,
209                                          struct reloc_queue *));
210 static unsigned char * try_prev_fixup PARAMS ((bfd *, int *, unsigned char *,
211                                                unsigned int,
212                                                struct reloc_queue *));
213
214 static unsigned char * som_reloc_skip PARAMS ((bfd *, unsigned int,
215                                                unsigned char *, unsigned int *,
216                                                struct reloc_queue *));
217 static unsigned char * som_reloc_addend PARAMS ((bfd *, bfd_vma,
218                                                  unsigned char *,
219                                                  unsigned int *,
220                                                  struct reloc_queue *));
221 static unsigned char * som_reloc_call PARAMS ((bfd *, unsigned char *,
222                                                unsigned int *,
223                                                arelent *, int,
224                                                struct reloc_queue *));
225 static unsigned long som_count_spaces PARAMS ((bfd *));
226 static unsigned long som_count_subspaces PARAMS ((bfd *));
227 static int compare_syms PARAMS ((const void *, const void *));
228 static int compare_subspaces PARAMS ((const void *, const void *));
229 static unsigned long som_compute_checksum PARAMS ((bfd *));
230 static boolean som_prep_headers PARAMS ((bfd *));
231 static int som_sizeof_headers PARAMS ((bfd *, boolean));
232 static boolean som_finish_writing PARAMS ((bfd *));
233 static boolean som_build_and_write_symbol_table PARAMS ((bfd *));
234 static void som_prep_for_fixups PARAMS ((bfd *, asymbol **, unsigned long));
235 static boolean som_write_fixups PARAMS ((bfd *, unsigned long, unsigned int *));
236 static boolean som_write_space_strings PARAMS ((bfd *, unsigned long,
237                                                 unsigned int *));
238 static boolean som_write_symbol_strings PARAMS ((bfd *, unsigned long,
239                                                  asymbol **, unsigned int,
240                                                  unsigned *,
241                                                  COMPUNIT *));
242 static boolean som_begin_writing PARAMS ((bfd *));
243 static reloc_howto_type * som_bfd_reloc_type_lookup
244         PARAMS ((bfd *, bfd_reloc_code_real_type));
245 static char som_section_type PARAMS ((const char *));
246 static int som_decode_symclass PARAMS ((asymbol *));
247 static boolean som_bfd_count_ar_symbols PARAMS ((bfd *, struct lst_header *,
248                                                  symindex *));
249
250 static boolean som_bfd_fill_in_ar_symbols PARAMS ((bfd *, struct lst_header *,
251                                                    carsym **syms));
252 static boolean som_slurp_armap PARAMS ((bfd *));
253 static boolean som_write_armap PARAMS ((bfd *, unsigned int, struct orl *,
254                                         unsigned int, int));
255 static void som_bfd_derive_misc_symbol_info PARAMS ((bfd *, asymbol *,
256                                              struct som_misc_symbol_info *));
257 static boolean som_bfd_prep_for_ar_write PARAMS ((bfd *, unsigned int *,
258                                                   unsigned int *));
259 static unsigned int som_bfd_ar_symbol_hash PARAMS ((asymbol *));
260 static boolean som_bfd_ar_write_symbol_stuff PARAMS ((bfd *, unsigned int,
261                                                       unsigned int,
262                                                       struct lst_header,
263                                                       unsigned int));
264 static boolean som_is_space PARAMS ((asection *));
265 static boolean som_is_subspace PARAMS ((asection *));
266 static boolean som_is_container PARAMS ((asection *, asection *));
267 static boolean som_bfd_free_cached_info PARAMS ((bfd *));
268 static boolean som_bfd_link_split_section PARAMS ((bfd *, asection *));
269
270 /* Map SOM section names to POSIX/BSD single-character symbol types.
271
272    This table includes all the standard subspaces as defined in the
273    current "PRO ABI for PA-RISC Systems", $UNWIND$ which for
274    some reason was left out, and sections specific to embedded stabs.  */
275
276 static const struct section_to_type stt[] = {
277   {"$TEXT$", 't'},
278   {"$SHLIB_INFO$", 't'},
279   {"$MILLICODE$", 't'},
280   {"$LIT$", 't'},
281   {"$CODE$", 't'},
282   {"$UNWIND_START$", 't'},
283   {"$UNWIND$", 't'},
284   {"$PRIVATE$", 'd'},
285   {"$PLT$", 'd'},
286   {"$SHLIB_DATA$", 'd'},
287   {"$DATA$", 'd'},
288   {"$SHORTDATA$", 'g'},
289   {"$DLT$", 'd'},
290   {"$GLOBAL$", 'g'},
291   {"$SHORTBSS$", 's'},
292   {"$BSS$", 'b'},
293   {"$GDB_STRINGS$", 'N'},
294   {"$GDB_SYMBOLS$", 'N'},
295   {0, 0}
296 };
297
298 /* About the relocation formatting table...
299
300    There are 256 entries in the table, one for each possible
301    relocation opcode available in SOM.  We index the table by
302    the relocation opcode.  The names and operations are those
303    defined by a.out_800 (4).
304
305    Right now this table is only used to count and perform minimal
306    processing on relocation streams so that they can be internalized
307    into BFD and symbolically printed by utilities.  To make actual use
308    of them would be much more difficult, BFD's concept of relocations
309    is far too simple to handle SOM relocations.  The basic assumption
310    that a relocation can be completely processed independent of other
311    relocations before an object file is written is invalid for SOM.
312
313    The SOM relocations are meant to be processed as a stream, they
314    specify copying of data from the input section to the output section
315    while possibly modifying the data in some manner.  They also can
316    specify that a variable number of zeros or uninitialized data be
317    inserted on in the output segment at the current offset.  Some
318    relocations specify that some previous relocation be re-applied at
319    the current location in the input/output sections.  And finally a number
320    of relocations have effects on other sections (R_ENTRY, R_EXIT,
321    R_UNWIND_AUX and a variety of others).  There isn't even enough room
322    in the BFD relocation data structure to store enough information to
323    perform all the relocations.
324
325    Each entry in the table has three fields.
326
327    The first entry is an index into this "class" of relocations.  This
328    index can then be used as a variable within the relocation itself.
329
330    The second field is a format string which actually controls processing
331    of the relocation.  It uses a simple postfix machine to do calculations
332    based on variables/constants found in the string and the relocation
333    stream.
334
335    The third field specifys whether or not this relocation may use
336    a constant (V) from the previous R_DATA_OVERRIDE rather than a constant
337    stored in the instruction.
338
339    Variables:
340
341    L = input space byte count
342    D = index into class of relocations
343    M = output space byte count
344    N = statement number (unused?)
345    O = stack operation
346    R = parameter relocation bits
347    S = symbol index
348    T = first 32 bits of stack unwind information
349    U = second 32 bits of stack unwind information
350    V = a literal constant (usually used in the next relocation)
351    P = a previous relocation
352
353    Lower case letters (starting with 'b') refer to following
354    bytes in the relocation stream.  'b' is the next 1 byte,
355    c is the next 2 bytes, d is the next 3 bytes, etc...
356    This is the variable part of the relocation entries that
357    makes our life a living hell.
358
359    numerical constants are also used in the format string.  Note
360    the constants are represented in decimal.
361
362    '+', "*" and "=" represents the obvious postfix operators.
363    '<' represents a left shift.
364
365    Stack Operations:
366
367    Parameter Relocation Bits:
368
369    Unwind Entries:
370
371    Previous Relocations:  The index field represents which in the queue
372    of 4 previous fixups should be re-applied.
373
374    Literal Constants:  These are generally used to represent addend
375    parts of relocations when these constants are not stored in the
376    fields of the instructions themselves.  For example the instruction
377    addil foo-$global$-0x1234 would use an override for "0x1234" rather
378    than storing it into the addil itself.  */
379
380 struct fixup_format {
381   int D;
382   const char *format;
383 };
384
385 static const struct fixup_format som_fixup_formats[256] = {
386   /* R_NO_RELOCATION */
387   {  0, "LD1+4*=" },            /* 0x00 */
388   {  1, "LD1+4*=" },            /* 0x01 */
389   {  2, "LD1+4*=" },            /* 0x02 */
390   {  3, "LD1+4*=" },            /* 0x03 */
391   {  4, "LD1+4*=" },            /* 0x04 */
392   {  5, "LD1+4*=" },            /* 0x05 */
393   {  6, "LD1+4*=" },            /* 0x06 */
394   {  7, "LD1+4*=" },            /* 0x07 */
395   {  8, "LD1+4*=" },            /* 0x08 */
396   {  9, "LD1+4*=" },            /* 0x09 */
397   { 10, "LD1+4*=" },            /* 0x0a */
398   { 11, "LD1+4*=" },            /* 0x0b */
399   { 12, "LD1+4*=" },            /* 0x0c */
400   { 13, "LD1+4*=" },            /* 0x0d */
401   { 14, "LD1+4*=" },            /* 0x0e */
402   { 15, "LD1+4*=" },            /* 0x0f */
403   { 16, "LD1+4*=" },            /* 0x10 */
404   { 17, "LD1+4*=" },            /* 0x11 */
405   { 18, "LD1+4*=" },            /* 0x12 */
406   { 19, "LD1+4*=" },            /* 0x13 */
407   { 20, "LD1+4*=" },            /* 0x14 */
408   { 21, "LD1+4*=" },            /* 0x15 */
409   { 22, "LD1+4*=" },            /* 0x16 */
410   { 23, "LD1+4*=" },            /* 0x17 */
411   {  0, "LD8<b+1+4*=" },        /* 0x18 */
412   {  1, "LD8<b+1+4*=" },        /* 0x19 */
413   {  2, "LD8<b+1+4*=" },        /* 0x1a */
414   {  3, "LD8<b+1+4*=" },        /* 0x1b */
415   {  0, "LD16<c+1+4*=" },       /* 0x1c */
416   {  1, "LD16<c+1+4*=" },       /* 0x1d */
417   {  2, "LD16<c+1+4*=" },       /* 0x1e */
418   {  0, "Ld1+=" },              /* 0x1f */
419   /* R_ZEROES */
420   {  0, "Lb1+4*=" },            /* 0x20 */
421   {  1, "Ld1+=" },              /* 0x21 */
422   /* R_UNINIT */
423   {  0, "Lb1+4*=" },            /* 0x22 */
424   {  1, "Ld1+=" },              /* 0x23 */
425   /* R_RELOCATION */
426   {  0, "L4=" },                /* 0x24 */
427   /* R_DATA_ONE_SYMBOL */
428   {  0, "L4=Sb=" },             /* 0x25 */
429   {  1, "L4=Sd=" },             /* 0x26 */
430   /* R_DATA_PLEBEL */
431   {  0, "L4=Sb=" },             /* 0x27 */
432   {  1, "L4=Sd=" },             /* 0x28 */
433   /* R_SPACE_REF */
434   {  0, "L4=" },                /* 0x29 */
435   /* R_REPEATED_INIT */
436   {  0, "L4=Mb1+4*=" },         /* 0x2a */
437   {  1, "Lb4*=Mb1+L*=" },       /* 0x2b */
438   {  2, "Lb4*=Md1+4*=" },       /* 0x2c */
439   {  3, "Ld1+=Me1+=" },         /* 0x2d */
440   {  0, "" },                   /* 0x2e */
441   {  0, "" },                   /* 0x2f */
442   /* R_PCREL_CALL */
443   {  0, "L4=RD=Sb=" },          /* 0x30 */
444   {  1, "L4=RD=Sb=" },          /* 0x31 */
445   {  2, "L4=RD=Sb=" },          /* 0x32 */
446   {  3, "L4=RD=Sb=" },          /* 0x33 */
447   {  4, "L4=RD=Sb=" },          /* 0x34 */
448   {  5, "L4=RD=Sb=" },          /* 0x35 */
449   {  6, "L4=RD=Sb=" },          /* 0x36 */
450   {  7, "L4=RD=Sb=" },          /* 0x37 */
451   {  8, "L4=RD=Sb=" },          /* 0x38 */
452   {  9, "L4=RD=Sb=" },          /* 0x39 */
453   {  0, "L4=RD8<b+=Sb=" },      /* 0x3a */
454   {  1, "L4=RD8<b+=Sb=" },      /* 0x3b */
455   {  0, "L4=RD8<b+=Sd=" },      /* 0x3c */
456   {  1, "L4=RD8<b+=Sd=" },      /* 0x3d */
457   /* R_SHORT_PCREL_MODE */
458   {  0, "" },                   /* 0x3e */
459   /* R_LONG_PCREL_MODE */
460   {  0, "" },                   /* 0x3f */
461   /* R_ABS_CALL */
462   {  0, "L4=RD=Sb=" },          /* 0x40 */
463   {  1, "L4=RD=Sb=" },          /* 0x41 */
464   {  2, "L4=RD=Sb=" },          /* 0x42 */
465   {  3, "L4=RD=Sb=" },          /* 0x43 */
466   {  4, "L4=RD=Sb=" },          /* 0x44 */
467   {  5, "L4=RD=Sb=" },          /* 0x45 */
468   {  6, "L4=RD=Sb=" },          /* 0x46 */
469   {  7, "L4=RD=Sb=" },          /* 0x47 */
470   {  8, "L4=RD=Sb=" },          /* 0x48 */
471   {  9, "L4=RD=Sb=" },          /* 0x49 */
472   {  0, "L4=RD8<b+=Sb=" },      /* 0x4a */
473   {  1, "L4=RD8<b+=Sb=" },      /* 0x4b */
474   {  0, "L4=RD8<b+=Sd=" },      /* 0x4c */
475   {  1, "L4=RD8<b+=Sd=" },      /* 0x4d */
476   /* R_RESERVED */
477   {  0, "" },                   /* 0x4e */
478   {  0, "" },                   /* 0x4f */
479   /* R_DP_RELATIVE */
480   {  0, "L4=SD=" },             /* 0x50 */
481   {  1, "L4=SD=" },             /* 0x51 */
482   {  2, "L4=SD=" },             /* 0x52 */
483   {  3, "L4=SD=" },             /* 0x53 */
484   {  4, "L4=SD=" },             /* 0x54 */
485   {  5, "L4=SD=" },             /* 0x55 */
486   {  6, "L4=SD=" },             /* 0x56 */
487   {  7, "L4=SD=" },             /* 0x57 */
488   {  8, "L4=SD=" },             /* 0x58 */
489   {  9, "L4=SD=" },             /* 0x59 */
490   { 10, "L4=SD=" },             /* 0x5a */
491   { 11, "L4=SD=" },             /* 0x5b */
492   { 12, "L4=SD=" },             /* 0x5c */
493   { 13, "L4=SD=" },             /* 0x5d */
494   { 14, "L4=SD=" },             /* 0x5e */
495   { 15, "L4=SD=" },             /* 0x5f */
496   { 16, "L4=SD=" },             /* 0x60 */
497   { 17, "L4=SD=" },             /* 0x61 */
498   { 18, "L4=SD=" },             /* 0x62 */
499   { 19, "L4=SD=" },             /* 0x63 */
500   { 20, "L4=SD=" },             /* 0x64 */
501   { 21, "L4=SD=" },             /* 0x65 */
502   { 22, "L4=SD=" },             /* 0x66 */
503   { 23, "L4=SD=" },             /* 0x67 */
504   { 24, "L4=SD=" },             /* 0x68 */
505   { 25, "L4=SD=" },             /* 0x69 */
506   { 26, "L4=SD=" },             /* 0x6a */
507   { 27, "L4=SD=" },             /* 0x6b */
508   { 28, "L4=SD=" },             /* 0x6c */
509   { 29, "L4=SD=" },             /* 0x6d */
510   { 30, "L4=SD=" },             /* 0x6e */
511   { 31, "L4=SD=" },             /* 0x6f */
512   { 32, "L4=Sb=" },             /* 0x70 */
513   { 33, "L4=Sd=" },             /* 0x71 */
514   /* R_RESERVED */
515   {  0, "" },                   /* 0x72 */
516   {  0, "" },                   /* 0x73 */
517   {  0, "" },                   /* 0x74 */
518   {  0, "" },                   /* 0x75 */
519   {  0, "" },                   /* 0x76 */
520   {  0, "" },                   /* 0x77 */
521   /* R_DLT_REL */
522   {  0, "L4=Sb=" },             /* 0x78 */
523   {  1, "L4=Sd=" },             /* 0x79 */
524   /* R_RESERVED */
525   {  0, "" },                   /* 0x7a */
526   {  0, "" },                   /* 0x7b */
527   {  0, "" },                   /* 0x7c */
528   {  0, "" },                   /* 0x7d */
529   {  0, "" },                   /* 0x7e */
530   {  0, "" },                   /* 0x7f */
531   /* R_CODE_ONE_SYMBOL */
532   {  0, "L4=SD=" },             /* 0x80 */
533   {  1, "L4=SD=" },             /* 0x81 */
534   {  2, "L4=SD=" },             /* 0x82 */
535   {  3, "L4=SD=" },             /* 0x83 */
536   {  4, "L4=SD=" },             /* 0x84 */
537   {  5, "L4=SD=" },             /* 0x85 */
538   {  6, "L4=SD=" },             /* 0x86 */
539   {  7, "L4=SD=" },             /* 0x87 */
540   {  8, "L4=SD=" },             /* 0x88 */
541   {  9, "L4=SD=" },             /* 0x89 */
542   { 10, "L4=SD=" },             /* 0x8q */
543   { 11, "L4=SD=" },             /* 0x8b */
544   { 12, "L4=SD=" },             /* 0x8c */
545   { 13, "L4=SD=" },             /* 0x8d */
546   { 14, "L4=SD=" },             /* 0x8e */
547   { 15, "L4=SD=" },             /* 0x8f */
548   { 16, "L4=SD=" },             /* 0x90 */
549   { 17, "L4=SD=" },             /* 0x91 */
550   { 18, "L4=SD=" },             /* 0x92 */
551   { 19, "L4=SD=" },             /* 0x93 */
552   { 20, "L4=SD=" },             /* 0x94 */
553   { 21, "L4=SD=" },             /* 0x95 */
554   { 22, "L4=SD=" },             /* 0x96 */
555   { 23, "L4=SD=" },             /* 0x97 */
556   { 24, "L4=SD=" },             /* 0x98 */
557   { 25, "L4=SD=" },             /* 0x99 */
558   { 26, "L4=SD=" },             /* 0x9a */
559   { 27, "L4=SD=" },             /* 0x9b */
560   { 28, "L4=SD=" },             /* 0x9c */
561   { 29, "L4=SD=" },             /* 0x9d */
562   { 30, "L4=SD=" },             /* 0x9e */
563   { 31, "L4=SD=" },             /* 0x9f */
564   { 32, "L4=Sb=" },             /* 0xa0 */
565   { 33, "L4=Sd=" },             /* 0xa1 */
566   /* R_RESERVED */
567   {  0, "" },                   /* 0xa2 */
568   {  0, "" },                   /* 0xa3 */
569   {  0, "" },                   /* 0xa4 */
570   {  0, "" },                   /* 0xa5 */
571   {  0, "" },                   /* 0xa6 */
572   {  0, "" },                   /* 0xa7 */
573   {  0, "" },                   /* 0xa8 */
574   {  0, "" },                   /* 0xa9 */
575   {  0, "" },                   /* 0xaa */
576   {  0, "" },                   /* 0xab */
577   {  0, "" },                   /* 0xac */
578   {  0, "" },                   /* 0xad */
579   /* R_MILLI_REL */
580   {  0, "L4=Sb=" },             /* 0xae */
581   {  1, "L4=Sd=" },             /* 0xaf */
582   /* R_CODE_PLABEL */
583   {  0, "L4=Sb=" },             /* 0xb0 */
584   {  1, "L4=Sd=" },             /* 0xb1 */
585   /* R_BREAKPOINT */
586   {  0, "L4=" },                /* 0xb2 */
587   /* R_ENTRY */
588   {  0, "Te=Ue=" },             /* 0xb3 */
589   {  1, "Uf=" },                /* 0xb4 */
590   /* R_ALT_ENTRY */
591   {  0, "" },                   /* 0xb5 */
592   /* R_EXIT */
593   {  0, "" },                   /* 0xb6 */
594   /* R_BEGIN_TRY */
595   {  0, "" },                   /* 0xb7 */
596   /* R_END_TRY */
597   {  0, "R0=" },                /* 0xb8 */
598   {  1, "Rb4*=" },              /* 0xb9 */
599   {  2, "Rd4*=" },              /* 0xba */
600   /* R_BEGIN_BRTAB */
601   {  0, "" },                   /* 0xbb */
602   /* R_END_BRTAB */
603   {  0, "" },                   /* 0xbc */
604   /* R_STATEMENT */
605   {  0, "Nb=" },                /* 0xbd */
606   {  1, "Nc=" },                /* 0xbe */
607   {  2, "Nd=" },                /* 0xbf */
608   /* R_DATA_EXPR */
609   {  0, "L4=" },                /* 0xc0 */
610   /* R_CODE_EXPR */
611   {  0, "L4=" },                /* 0xc1 */
612   /* R_FSEL */
613   {  0, "" },                   /* 0xc2 */
614   /* R_LSEL */
615   {  0, "" },                   /* 0xc3 */
616   /* R_RSEL */
617   {  0, "" },                   /* 0xc4 */
618   /* R_N_MODE */
619   {  0, "" },                   /* 0xc5 */
620   /* R_S_MODE */
621   {  0, "" },                   /* 0xc6 */
622   /* R_D_MODE */
623   {  0, "" },                   /* 0xc7 */
624   /* R_R_MODE */
625   {  0, "" },                   /* 0xc8 */
626   /* R_DATA_OVERRIDE */
627   {  0, "V0=" },                /* 0xc9 */
628   {  1, "Vb=" },                /* 0xca */
629   {  2, "Vc=" },                /* 0xcb */
630   {  3, "Vd=" },                /* 0xcc */
631   {  4, "Ve=" },                /* 0xcd */
632   /* R_TRANSLATED */
633   {  0, "" },                   /* 0xce */
634   /* R_AUX_UNWIND */
635   {  0,"Sd=Vf=Ef=" },          /* 0xcf */
636   /* R_COMP1 */
637   {  0, "Ob=" },                /* 0xd0 */
638   /* R_COMP2 */
639   {  0, "Ob=Sd=" },             /* 0xd1 */
640   /* R_COMP3 */
641   {  0, "Ob=Ve=" },             /* 0xd2 */
642   /* R_PREV_FIXUP */
643   {  0, "P" },                  /* 0xd3 */
644   {  1, "P" },                  /* 0xd4 */
645   {  2, "P" },                  /* 0xd5 */
646   {  3, "P" },                  /* 0xd6 */
647   /* R_SEC_STMT */
648   {  0, "" },                   /* 0xd7 */
649   /* R_N0SEL */
650   {  0, "" },                   /* 0xd8 */
651   /* R_N1SEL */
652   {  0, "" },                   /* 0xd9 */
653   /* R_LINETAB */
654   {  0, "Eb=Sd=Ve=" },          /* 0xda */
655   /* R_LINETAB_ESC */
656   {  0, "Eb=Mb=" },             /* 0xdb */
657   /* R_LTP_OVERRIDE */
658   {  0, "" },                   /* 0xdc */
659   /* R_COMMENT */
660   {  0, "Ob=Ve=" },             /* 0xdd */
661   /* R_RESERVED */
662   {  0, "" },                   /* 0xde */
663   {  0, "" },                   /* 0xdf */
664   {  0, "" },                   /* 0xe0 */
665   {  0, "" },                   /* 0xe1 */
666   {  0, "" },                   /* 0xe2 */
667   {  0, "" },                   /* 0xe3 */
668   {  0, "" },                   /* 0xe4 */
669   {  0, "" },                   /* 0xe5 */
670   {  0, "" },                   /* 0xe6 */
671   {  0, "" },                   /* 0xe7 */
672   {  0, "" },                   /* 0xe8 */
673   {  0, "" },                   /* 0xe9 */
674   {  0, "" },                   /* 0xea */
675   {  0, "" },                   /* 0xeb */
676   {  0, "" },                   /* 0xec */
677   {  0, "" },                   /* 0xed */
678   {  0, "" },                   /* 0xee */
679   {  0, "" },                   /* 0xef */
680   {  0, "" },                   /* 0xf0 */
681   {  0, "" },                   /* 0xf1 */
682   {  0, "" },                   /* 0xf2 */
683   {  0, "" },                   /* 0xf3 */
684   {  0, "" },                   /* 0xf4 */
685   {  0, "" },                   /* 0xf5 */
686   {  0, "" },                   /* 0xf6 */
687   {  0, "" },                   /* 0xf7 */
688   {  0, "" },                   /* 0xf8 */
689   {  0, "" },                   /* 0xf9 */
690   {  0, "" },                   /* 0xfa */
691   {  0, "" },                   /* 0xfb */
692   {  0, "" },                   /* 0xfc */
693   {  0, "" },                   /* 0xfd */
694   {  0, "" },                   /* 0xfe */
695   {  0, "" },                   /* 0xff */
696 };
697
698 static const int comp1_opcodes[] = {
699   0x00,
700   0x40,
701   0x41,
702   0x42,
703   0x43,
704   0x44,
705   0x45,
706   0x46,
707   0x47,
708   0x48,
709   0x49,
710   0x4a,
711   0x4b,
712   0x60,
713   0x80,
714   0xa0,
715   0xc0,
716   -1
717 };
718
719 static const int comp2_opcodes[] = {
720   0x00,
721   0x80,
722   0x82,
723   0xc0,
724   -1
725 };
726
727 static const int comp3_opcodes[] = {
728   0x00,
729   0x02,
730   -1
731 };
732
733 /* These apparently are not in older versions of hpux reloc.h (hpux7).  */
734 #ifndef R_DLT_REL
735 #define R_DLT_REL 0x78
736 #endif
737
738 #ifndef R_AUX_UNWIND
739 #define R_AUX_UNWIND 0xcf
740 #endif
741
742 #ifndef R_SEC_STMT
743 #define R_SEC_STMT 0xd7
744 #endif
745
746 /* And these first appeared in hpux10.  */
747 #ifndef R_SHORT_PCREL_MODE
748 #define NO_PCREL_MODES
749 #define R_SHORT_PCREL_MODE 0x3e
750 #endif
751
752 #ifndef R_LONG_PCREL_MODE
753 #define R_LONG_PCREL_MODE 0x3f
754 #endif
755
756 #ifndef R_N0SEL
757 #define R_N0SEL 0xd8
758 #endif
759
760 #ifndef R_N1SEL
761 #define R_N1SEL 0xd9
762 #endif
763
764 #ifndef R_LINETAB
765 #define R_LINETAB 0xda
766 #endif
767
768 #ifndef R_LINETAB_ESC
769 #define R_LINETAB_ESC 0xdb
770 #endif
771
772 #ifndef R_LTP_OVERRIDE
773 #define R_LTP_OVERRIDE 0xdc
774 #endif
775
776 #ifndef R_COMMENT
777 #define R_COMMENT 0xdd
778 #endif
779
780 #define SOM_HOWTO(TYPE, NAME)   \
781   HOWTO(TYPE, 0, 0, 32, false, 0, 0, hppa_som_reloc, NAME, false, 0, 0, false)
782
783 static reloc_howto_type som_hppa_howto_table[] = {
784   SOM_HOWTO (R_NO_RELOCATION, "R_NO_RELOCATION"),
785   SOM_HOWTO (R_NO_RELOCATION, "R_NO_RELOCATION"),
786   SOM_HOWTO (R_NO_RELOCATION, "R_NO_RELOCATION"),
787   SOM_HOWTO (R_NO_RELOCATION, "R_NO_RELOCATION"),
788   SOM_HOWTO (R_NO_RELOCATION, "R_NO_RELOCATION"),
789   SOM_HOWTO (R_NO_RELOCATION, "R_NO_RELOCATION"),
790   SOM_HOWTO (R_NO_RELOCATION, "R_NO_RELOCATION"),
791   SOM_HOWTO (R_NO_RELOCATION, "R_NO_RELOCATION"),
792   SOM_HOWTO (R_NO_RELOCATION, "R_NO_RELOCATION"),
793   SOM_HOWTO (R_NO_RELOCATION, "R_NO_RELOCATION"),
794   SOM_HOWTO (R_NO_RELOCATION, "R_NO_RELOCATION"),
795   SOM_HOWTO (R_NO_RELOCATION, "R_NO_RELOCATION"),
796   SOM_HOWTO (R_NO_RELOCATION, "R_NO_RELOCATION"),
797   SOM_HOWTO (R_NO_RELOCATION, "R_NO_RELOCATION"),
798   SOM_HOWTO (R_NO_RELOCATION, "R_NO_RELOCATION"),
799   SOM_HOWTO (R_NO_RELOCATION, "R_NO_RELOCATION"),
800   SOM_HOWTO (R_NO_RELOCATION, "R_NO_RELOCATION"),
801   SOM_HOWTO (R_NO_RELOCATION, "R_NO_RELOCATION"),
802   SOM_HOWTO (R_NO_RELOCATION, "R_NO_RELOCATION"),
803   SOM_HOWTO (R_NO_RELOCATION, "R_NO_RELOCATION"),
804   SOM_HOWTO (R_NO_RELOCATION, "R_NO_RELOCATION"),
805   SOM_HOWTO (R_NO_RELOCATION, "R_NO_RELOCATION"),
806   SOM_HOWTO (R_NO_RELOCATION, "R_NO_RELOCATION"),
807   SOM_HOWTO (R_NO_RELOCATION, "R_NO_RELOCATION"),
808   SOM_HOWTO (R_NO_RELOCATION, "R_NO_RELOCATION"),
809   SOM_HOWTO (R_NO_RELOCATION, "R_NO_RELOCATION"),
810   SOM_HOWTO (R_NO_RELOCATION, "R_NO_RELOCATION"),
811   SOM_HOWTO (R_NO_RELOCATION, "R_NO_RELOCATION"),
812   SOM_HOWTO (R_NO_RELOCATION, "R_NO_RELOCATION"),
813   SOM_HOWTO (R_NO_RELOCATION, "R_NO_RELOCATION"),
814   SOM_HOWTO (R_NO_RELOCATION, "R_NO_RELOCATION"),
815   SOM_HOWTO (R_NO_RELOCATION, "R_NO_RELOCATION"),
816   SOM_HOWTO (R_ZEROES, "R_ZEROES"),
817   SOM_HOWTO (R_ZEROES, "R_ZEROES"),
818   SOM_HOWTO (R_UNINIT, "R_UNINIT"),
819   SOM_HOWTO (R_UNINIT, "R_UNINIT"),
820   SOM_HOWTO (R_RELOCATION, "R_RELOCATION"),
821   SOM_HOWTO (R_DATA_ONE_SYMBOL, "R_DATA_ONE_SYMBOL"),
822   SOM_HOWTO (R_DATA_ONE_SYMBOL, "R_DATA_ONE_SYMBOL"),
823   SOM_HOWTO (R_DATA_PLABEL, "R_DATA_PLABEL"),
824   SOM_HOWTO (R_DATA_PLABEL, "R_DATA_PLABEL"),
825   SOM_HOWTO (R_SPACE_REF, "R_SPACE_REF"),
826   SOM_HOWTO (R_REPEATED_INIT, "REPEATED_INIT"),
827   SOM_HOWTO (R_REPEATED_INIT, "REPEATED_INIT"),
828   SOM_HOWTO (R_REPEATED_INIT, "REPEATED_INIT"),
829   SOM_HOWTO (R_REPEATED_INIT, "REPEATED_INIT"),
830   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
831   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
832   SOM_HOWTO (R_PCREL_CALL, "R_PCREL_CALL"),
833   SOM_HOWTO (R_PCREL_CALL, "R_PCREL_CALL"),
834   SOM_HOWTO (R_PCREL_CALL, "R_PCREL_CALL"),
835   SOM_HOWTO (R_PCREL_CALL, "R_PCREL_CALL"),
836   SOM_HOWTO (R_PCREL_CALL, "R_PCREL_CALL"),
837   SOM_HOWTO (R_PCREL_CALL, "R_PCREL_CALL"),
838   SOM_HOWTO (R_PCREL_CALL, "R_PCREL_CALL"),
839   SOM_HOWTO (R_PCREL_CALL, "R_PCREL_CALL"),
840   SOM_HOWTO (R_PCREL_CALL, "R_PCREL_CALL"),
841   SOM_HOWTO (R_PCREL_CALL, "R_PCREL_CALL"),
842   SOM_HOWTO (R_PCREL_CALL, "R_PCREL_CALL"),
843   SOM_HOWTO (R_PCREL_CALL, "R_PCREL_CALL"),
844   SOM_HOWTO (R_PCREL_CALL, "R_PCREL_CALL"),
845   SOM_HOWTO (R_PCREL_CALL, "R_PCREL_CALL"),
846   SOM_HOWTO (R_SHORT_PCREL_MODE, "R_SHORT_PCREL_MODE"),
847   SOM_HOWTO (R_LONG_PCREL_MODE, "R_LONG_PCREL_MODE"),
848   SOM_HOWTO (R_ABS_CALL, "R_ABS_CALL"),
849   SOM_HOWTO (R_ABS_CALL, "R_ABS_CALL"),
850   SOM_HOWTO (R_ABS_CALL, "R_ABS_CALL"),
851   SOM_HOWTO (R_ABS_CALL, "R_ABS_CALL"),
852   SOM_HOWTO (R_ABS_CALL, "R_ABS_CALL"),
853   SOM_HOWTO (R_ABS_CALL, "R_ABS_CALL"),
854   SOM_HOWTO (R_ABS_CALL, "R_ABS_CALL"),
855   SOM_HOWTO (R_ABS_CALL, "R_ABS_CALL"),
856   SOM_HOWTO (R_ABS_CALL, "R_ABS_CALL"),
857   SOM_HOWTO (R_ABS_CALL, "R_ABS_CALL"),
858   SOM_HOWTO (R_ABS_CALL, "R_ABS_CALL"),
859   SOM_HOWTO (R_ABS_CALL, "R_ABS_CALL"),
860   SOM_HOWTO (R_ABS_CALL, "R_ABS_CALL"),
861   SOM_HOWTO (R_ABS_CALL, "R_ABS_CALL"),
862   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
863   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
864   SOM_HOWTO (R_DP_RELATIVE, "R_DP_RELATIVE"),
865   SOM_HOWTO (R_DP_RELATIVE, "R_DP_RELATIVE"),
866   SOM_HOWTO (R_DP_RELATIVE, "R_DP_RELATIVE"),
867   SOM_HOWTO (R_DP_RELATIVE, "R_DP_RELATIVE"),
868   SOM_HOWTO (R_DP_RELATIVE, "R_DP_RELATIVE"),
869   SOM_HOWTO (R_DP_RELATIVE, "R_DP_RELATIVE"),
870   SOM_HOWTO (R_DP_RELATIVE, "R_DP_RELATIVE"),
871   SOM_HOWTO (R_DP_RELATIVE, "R_DP_RELATIVE"),
872   SOM_HOWTO (R_DP_RELATIVE, "R_DP_RELATIVE"),
873   SOM_HOWTO (R_DP_RELATIVE, "R_DP_RELATIVE"),
874   SOM_HOWTO (R_DP_RELATIVE, "R_DP_RELATIVE"),
875   SOM_HOWTO (R_DP_RELATIVE, "R_DP_RELATIVE"),
876   SOM_HOWTO (R_DP_RELATIVE, "R_DP_RELATIVE"),
877   SOM_HOWTO (R_DP_RELATIVE, "R_DP_RELATIVE"),
878   SOM_HOWTO (R_DP_RELATIVE, "R_DP_RELATIVE"),
879   SOM_HOWTO (R_DP_RELATIVE, "R_DP_RELATIVE"),
880   SOM_HOWTO (R_DP_RELATIVE, "R_DP_RELATIVE"),
881   SOM_HOWTO (R_DP_RELATIVE, "R_DP_RELATIVE"),
882   SOM_HOWTO (R_DP_RELATIVE, "R_DP_RELATIVE"),
883   SOM_HOWTO (R_DP_RELATIVE, "R_DP_RELATIVE"),
884   SOM_HOWTO (R_DP_RELATIVE, "R_DP_RELATIVE"),
885   SOM_HOWTO (R_DP_RELATIVE, "R_DP_RELATIVE"),
886   SOM_HOWTO (R_DP_RELATIVE, "R_DP_RELATIVE"),
887   SOM_HOWTO (R_DP_RELATIVE, "R_DP_RELATIVE"),
888   SOM_HOWTO (R_DP_RELATIVE, "R_DP_RELATIVE"),
889   SOM_HOWTO (R_DP_RELATIVE, "R_DP_RELATIVE"),
890   SOM_HOWTO (R_DP_RELATIVE, "R_DP_RELATIVE"),
891   SOM_HOWTO (R_DP_RELATIVE, "R_DP_RELATIVE"),
892   SOM_HOWTO (R_DP_RELATIVE, "R_DP_RELATIVE"),
893   SOM_HOWTO (R_DP_RELATIVE, "R_DP_RELATIVE"),
894   SOM_HOWTO (R_DP_RELATIVE, "R_DP_RELATIVE"),
895   SOM_HOWTO (R_DP_RELATIVE, "R_DP_RELATIVE"),
896   SOM_HOWTO (R_DP_RELATIVE, "R_DP_RELATIVE"),
897   SOM_HOWTO (R_DP_RELATIVE, "R_DP_RELATIVE"),
898   SOM_HOWTO (R_DP_RELATIVE, "R_DP_RELATIVE"),
899   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
900   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
901   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
902   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
903   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
904   SOM_HOWTO (R_DLT_REL, "R_DLT_REL"),
905   SOM_HOWTO (R_DLT_REL, "R_DLT_REL"),
906   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
907   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
908   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
909   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
910   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
911   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
912   SOM_HOWTO (R_CODE_ONE_SYMBOL, "R_CODE_ONE_SYMBOL"),
913   SOM_HOWTO (R_CODE_ONE_SYMBOL, "R_CODE_ONE_SYMBOL"),
914   SOM_HOWTO (R_CODE_ONE_SYMBOL, "R_CODE_ONE_SYMBOL"),
915   SOM_HOWTO (R_CODE_ONE_SYMBOL, "R_CODE_ONE_SYMBOL"),
916   SOM_HOWTO (R_CODE_ONE_SYMBOL, "R_CODE_ONE_SYMBOL"),
917   SOM_HOWTO (R_CODE_ONE_SYMBOL, "R_CODE_ONE_SYMBOL"),
918   SOM_HOWTO (R_CODE_ONE_SYMBOL, "R_CODE_ONE_SYMBOL"),
919   SOM_HOWTO (R_CODE_ONE_SYMBOL, "R_CODE_ONE_SYMBOL"),
920   SOM_HOWTO (R_CODE_ONE_SYMBOL, "R_CODE_ONE_SYMBOL"),
921   SOM_HOWTO (R_CODE_ONE_SYMBOL, "R_CODE_ONE_SYMBOL"),
922   SOM_HOWTO (R_CODE_ONE_SYMBOL, "R_CODE_ONE_SYMBOL"),
923   SOM_HOWTO (R_CODE_ONE_SYMBOL, "R_CODE_ONE_SYMBOL"),
924   SOM_HOWTO (R_CODE_ONE_SYMBOL, "R_CODE_ONE_SYMBOL"),
925   SOM_HOWTO (R_CODE_ONE_SYMBOL, "R_CODE_ONE_SYMBOL"),
926   SOM_HOWTO (R_CODE_ONE_SYMBOL, "R_CODE_ONE_SYMBOL"),
927   SOM_HOWTO (R_CODE_ONE_SYMBOL, "R_CODE_ONE_SYMBOL"),
928   SOM_HOWTO (R_CODE_ONE_SYMBOL, "R_CODE_ONE_SYMBOL"),
929   SOM_HOWTO (R_CODE_ONE_SYMBOL, "R_CODE_ONE_SYMBOL"),
930   SOM_HOWTO (R_CODE_ONE_SYMBOL, "R_CODE_ONE_SYMBOL"),
931   SOM_HOWTO (R_CODE_ONE_SYMBOL, "R_CODE_ONE_SYMBOL"),
932   SOM_HOWTO (R_CODE_ONE_SYMBOL, "R_CODE_ONE_SYMBOL"),
933   SOM_HOWTO (R_CODE_ONE_SYMBOL, "R_CODE_ONE_SYMBOL"),
934   SOM_HOWTO (R_CODE_ONE_SYMBOL, "R_CODE_ONE_SYMBOL"),
935   SOM_HOWTO (R_CODE_ONE_SYMBOL, "R_CODE_ONE_SYMBOL"),
936   SOM_HOWTO (R_CODE_ONE_SYMBOL, "R_CODE_ONE_SYMBOL"),
937   SOM_HOWTO (R_CODE_ONE_SYMBOL, "R_CODE_ONE_SYMBOL"),
938   SOM_HOWTO (R_CODE_ONE_SYMBOL, "R_CODE_ONE_SYMBOL"),
939   SOM_HOWTO (R_CODE_ONE_SYMBOL, "R_CODE_ONE_SYMBOL"),
940   SOM_HOWTO (R_CODE_ONE_SYMBOL, "R_CODE_ONE_SYMBOL"),
941   SOM_HOWTO (R_CODE_ONE_SYMBOL, "R_CODE_ONE_SYMBOL"),
942   SOM_HOWTO (R_CODE_ONE_SYMBOL, "R_CODE_ONE_SYMBOL"),
943   SOM_HOWTO (R_CODE_ONE_SYMBOL, "R_CODE_ONE_SYMBOL"),
944   SOM_HOWTO (R_CODE_ONE_SYMBOL, "R_CODE_ONE_SYMBOL"),
945   SOM_HOWTO (R_CODE_ONE_SYMBOL, "R_CODE_ONE_SYMBOL"),
946   SOM_HOWTO (R_CODE_ONE_SYMBOL, "R_CODE_ONE_SYMBOL"),
947   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
948   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
949   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
950   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
951   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
952   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
953   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
954   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
955   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
956   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
957   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
958   SOM_HOWTO (R_MILLI_REL, "R_MILLI_REL"),
959   SOM_HOWTO (R_MILLI_REL, "R_MILLI_REL"),
960   SOM_HOWTO (R_CODE_PLABEL, "R_CODE_PLABEL"),
961   SOM_HOWTO (R_CODE_PLABEL, "R_CODE_PLABEL"),
962   SOM_HOWTO (R_BREAKPOINT, "R_BREAKPOINT"),
963   SOM_HOWTO (R_ENTRY, "R_ENTRY"),
964   SOM_HOWTO (R_ENTRY, "R_ENTRY"),
965   SOM_HOWTO (R_ALT_ENTRY, "R_ALT_ENTRY"),
966   SOM_HOWTO (R_EXIT, "R_EXIT"),
967   SOM_HOWTO (R_BEGIN_TRY, "R_BEGIN_TRY"),
968   SOM_HOWTO (R_END_TRY, "R_END_TRY"),
969   SOM_HOWTO (R_END_TRY, "R_END_TRY"),
970   SOM_HOWTO (R_END_TRY, "R_END_TRY"),
971   SOM_HOWTO (R_BEGIN_BRTAB, "R_BEGIN_BRTAB"),
972   SOM_HOWTO (R_END_BRTAB, "R_END_BRTAB"),
973   SOM_HOWTO (R_STATEMENT, "R_STATEMENT"),
974   SOM_HOWTO (R_STATEMENT, "R_STATEMENT"),
975   SOM_HOWTO (R_STATEMENT, "R_STATEMENT"),
976   SOM_HOWTO (R_DATA_EXPR, "R_DATA_EXPR"),
977   SOM_HOWTO (R_CODE_EXPR, "R_CODE_EXPR"),
978   SOM_HOWTO (R_FSEL, "R_FSEL"),
979   SOM_HOWTO (R_LSEL, "R_LSEL"),
980   SOM_HOWTO (R_RSEL, "R_RSEL"),
981   SOM_HOWTO (R_N_MODE, "R_N_MODE"),
982   SOM_HOWTO (R_S_MODE, "R_S_MODE"),
983   SOM_HOWTO (R_D_MODE, "R_D_MODE"),
984   SOM_HOWTO (R_R_MODE, "R_R_MODE"),
985   SOM_HOWTO (R_DATA_OVERRIDE, "R_DATA_OVERRIDE"),
986   SOM_HOWTO (R_DATA_OVERRIDE, "R_DATA_OVERRIDE"),
987   SOM_HOWTO (R_DATA_OVERRIDE, "R_DATA_OVERRIDE"),
988   SOM_HOWTO (R_DATA_OVERRIDE, "R_DATA_OVERRIDE"),
989   SOM_HOWTO (R_DATA_OVERRIDE, "R_DATA_OVERRIDE"),
990   SOM_HOWTO (R_TRANSLATED, "R_TRANSLATED"),
991   SOM_HOWTO (R_AUX_UNWIND, "R_AUX_UNWIND"),
992   SOM_HOWTO (R_COMP1, "R_COMP1"),
993   SOM_HOWTO (R_COMP2, "R_COMP2"),
994   SOM_HOWTO (R_COMP3, "R_COMP3"),
995   SOM_HOWTO (R_PREV_FIXUP, "R_PREV_FIXUP"),
996   SOM_HOWTO (R_PREV_FIXUP, "R_PREV_FIXUP"),
997   SOM_HOWTO (R_PREV_FIXUP, "R_PREV_FIXUP"),
998   SOM_HOWTO (R_PREV_FIXUP, "R_PREV_FIXUP"),
999   SOM_HOWTO (R_SEC_STMT, "R_SEC_STMT"),
1000   SOM_HOWTO (R_N0SEL, "R_N0SEL"),
1001   SOM_HOWTO (R_N1SEL, "R_N1SEL"),
1002   SOM_HOWTO (R_LINETAB, "R_LINETAB"),
1003   SOM_HOWTO (R_LINETAB_ESC, "R_LINETAB_ESC"),
1004   SOM_HOWTO (R_LTP_OVERRIDE, "R_LTP_OVERRIDE"),
1005   SOM_HOWTO (R_COMMENT, "R_COMMENT"),
1006   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
1007   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
1008   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
1009   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
1010   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
1011   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
1012   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
1013   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
1014   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
1015   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
1016   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
1017   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
1018   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
1019   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
1020   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
1021   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
1022   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
1023   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
1024   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
1025   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
1026   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
1027   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
1028   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
1029   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
1030   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
1031   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
1032   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
1033   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
1034   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
1035   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
1036   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
1037   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
1038   SOM_HOWTO (R_RESERVED, "R_RESERVED"),
1039   SOM_HOWTO (R_RESERVED, "R_RESERVED")
1040 };
1041
1042 /* Initialize the SOM relocation queue.  By definition the queue holds
1043    the last four multibyte fixups.  */
1044
1045 static void
1046 som_initialize_reloc_queue (queue)
1047      struct reloc_queue *queue;
1048 {
1049   queue[0].reloc = NULL;
1050   queue[0].size = 0;
1051   queue[1].reloc = NULL;
1052   queue[1].size = 0;
1053   queue[2].reloc = NULL;
1054   queue[2].size = 0;
1055   queue[3].reloc = NULL;
1056   queue[3].size = 0;
1057 }
1058
1059 /* Insert a new relocation into the relocation queue.  */
1060
1061 static void
1062 som_reloc_queue_insert (p, size, queue)
1063      unsigned char *p;
1064      unsigned int size;
1065      struct reloc_queue *queue;
1066 {
1067   queue[3].reloc = queue[2].reloc;
1068   queue[3].size = queue[2].size;
1069   queue[2].reloc = queue[1].reloc;
1070   queue[2].size = queue[1].size;
1071   queue[1].reloc = queue[0].reloc;
1072   queue[1].size = queue[0].size;
1073   queue[0].reloc = p;
1074   queue[0].size = size;
1075 }
1076
1077 /* When an entry in the relocation queue is reused, the entry moves
1078    to the front of the queue.  */
1079
1080 static void
1081 som_reloc_queue_fix (queue, index)
1082      struct reloc_queue *queue;
1083      unsigned int index;
1084 {
1085   if (index == 0)
1086     return;
1087
1088   if (index == 1)
1089     {
1090       unsigned char *tmp1 = queue[0].reloc;
1091       unsigned int tmp2 = queue[0].size;
1092       queue[0].reloc = queue[1].reloc;
1093       queue[0].size = queue[1].size;
1094       queue[1].reloc = tmp1;
1095       queue[1].size = tmp2;
1096       return;
1097     }
1098
1099   if (index == 2)
1100     {
1101       unsigned char *tmp1 = queue[0].reloc;
1102       unsigned int tmp2 = queue[0].size;
1103       queue[0].reloc = queue[2].reloc;
1104       queue[0].size = queue[2].size;
1105       queue[2].reloc = queue[1].reloc;
1106       queue[2].size = queue[1].size;
1107       queue[1].reloc = tmp1;
1108       queue[1].size = tmp2;
1109       return;
1110     }
1111
1112   if (index == 3)
1113     {
1114       unsigned char *tmp1 = queue[0].reloc;
1115       unsigned int tmp2 = queue[0].size;
1116       queue[0].reloc = queue[3].reloc;
1117       queue[0].size = queue[3].size;
1118       queue[3].reloc = queue[2].reloc;
1119       queue[3].size = queue[2].size;
1120       queue[2].reloc = queue[1].reloc;
1121       queue[2].size = queue[1].size;
1122       queue[1].reloc = tmp1;
1123       queue[1].size = tmp2;
1124       return;
1125     }
1126   abort ();
1127 }
1128
1129 /* Search for a particular relocation in the relocation queue.  */
1130
1131 static int
1132 som_reloc_queue_find (p, size, queue)
1133      unsigned char *p;
1134      unsigned int size;
1135      struct reloc_queue *queue;
1136 {
1137   if (queue[0].reloc && !memcmp (p, queue[0].reloc, size)
1138       && size == queue[0].size)
1139     return 0;
1140   if (queue[1].reloc && !memcmp (p, queue[1].reloc, size)
1141       && size == queue[1].size)
1142     return 1;
1143   if (queue[2].reloc && !memcmp (p, queue[2].reloc, size)
1144       && size == queue[2].size)
1145     return 2;
1146   if (queue[3].reloc && !memcmp (p, queue[3].reloc, size)
1147       && size == queue[3].size)
1148     return 3;
1149   return -1;
1150 }
1151
1152 static unsigned char *
1153 try_prev_fixup (abfd, subspace_reloc_sizep, p, size, queue)
1154      bfd *abfd ATTRIBUTE_UNUSED;
1155      int *subspace_reloc_sizep;
1156      unsigned char *p;
1157      unsigned int size;
1158      struct reloc_queue *queue;
1159 {
1160   int queue_index = som_reloc_queue_find (p, size, queue);
1161
1162   if (queue_index != -1)
1163     {
1164       /* Found this in a previous fixup.  Undo the fixup we
1165          just built and use R_PREV_FIXUP instead.  We saved
1166          a total of size - 1 bytes in the fixup stream.  */
1167       bfd_put_8 (abfd, R_PREV_FIXUP + queue_index, p);
1168       p += 1;
1169       *subspace_reloc_sizep += 1;
1170       som_reloc_queue_fix (queue, queue_index);
1171     }
1172   else
1173     {
1174       som_reloc_queue_insert (p, size, queue);
1175       *subspace_reloc_sizep += size;
1176       p += size;
1177     }
1178   return p;
1179 }
1180
1181 /* Emit the proper R_NO_RELOCATION fixups to map the next SKIP
1182    bytes without any relocation.  Update the size of the subspace
1183    relocation stream via SUBSPACE_RELOC_SIZE_P; also return the
1184    current pointer into the relocation stream.  */
1185
1186 static unsigned char *
1187 som_reloc_skip (abfd, skip, p, subspace_reloc_sizep, queue)
1188      bfd *abfd;
1189      unsigned int skip;
1190      unsigned char *p;
1191      unsigned int *subspace_reloc_sizep;
1192      struct reloc_queue *queue;
1193 {
1194   /* Use a 4 byte R_NO_RELOCATION entry with a maximal value
1195      then R_PREV_FIXUPs to get the difference down to a
1196      reasonable size.  */
1197   if (skip >= 0x1000000)
1198     {
1199       skip -= 0x1000000;
1200       bfd_put_8 (abfd, R_NO_RELOCATION + 31, p);
1201       bfd_put_8 (abfd, 0xff, p + 1);
1202       bfd_put_16 (abfd, (bfd_vma) 0xffff, p + 2);
1203       p = try_prev_fixup (abfd, subspace_reloc_sizep, p, 4, queue);
1204       while (skip >= 0x1000000)
1205         {
1206           skip -= 0x1000000;
1207           bfd_put_8 (abfd, R_PREV_FIXUP, p);
1208           p++;
1209           *subspace_reloc_sizep += 1;
1210           /* No need to adjust queue here since we are repeating the
1211              most recent fixup.  */
1212         }
1213     }
1214
1215   /* The difference must be less than 0x1000000.  Use one
1216      more R_NO_RELOCATION entry to get to the right difference.  */
1217   if ((skip & 3) == 0 && skip <= 0xc0000 && skip > 0)
1218     {
1219       /* Difference can be handled in a simple single-byte
1220          R_NO_RELOCATION entry.  */
1221       if (skip <= 0x60)
1222         {
1223           bfd_put_8 (abfd, R_NO_RELOCATION + (skip >> 2) - 1, p);
1224           *subspace_reloc_sizep += 1;
1225           p++;
1226         }
1227       /* Handle it with a two byte R_NO_RELOCATION entry.  */
1228       else if (skip <= 0x1000)
1229         {
1230           bfd_put_8 (abfd, R_NO_RELOCATION + 24 + (((skip >> 2) - 1) >> 8), p);
1231           bfd_put_8 (abfd, (skip >> 2) - 1, p + 1);
1232           p = try_prev_fixup (abfd, subspace_reloc_sizep, p, 2, queue);
1233         }
1234       /* Handle it with a three byte R_NO_RELOCATION entry.  */
1235       else
1236         {
1237           bfd_put_8 (abfd, R_NO_RELOCATION + 28 + (((skip >> 2) - 1) >> 16), p);
1238           bfd_put_16 (abfd, (bfd_vma) (skip >> 2) - 1, p + 1);
1239           p = try_prev_fixup (abfd, subspace_reloc_sizep, p, 3, queue);
1240         }
1241     }
1242   /* Ugh.  Punt and use a 4 byte entry.  */
1243   else if (skip > 0)
1244     {
1245       bfd_put_8 (abfd, R_NO_RELOCATION + 31, p);
1246       bfd_put_8 (abfd, (skip - 1) >> 16, p + 1);
1247       bfd_put_16 (abfd, (bfd_vma) skip - 1, p + 2);
1248       p = try_prev_fixup (abfd, subspace_reloc_sizep, p, 4, queue);
1249     }
1250   return p;
1251 }
1252
1253 /* Emit the proper R_DATA_OVERRIDE fixups to handle a nonzero addend
1254    from a BFD relocation.  Update the size of the subspace relocation
1255    stream via SUBSPACE_RELOC_SIZE_P; also return the current pointer
1256    into the relocation stream.  */
1257
1258 static unsigned char *
1259 som_reloc_addend (abfd, addend, p, subspace_reloc_sizep, queue)
1260      bfd *abfd;
1261      bfd_vma addend;
1262      unsigned char *p;
1263      unsigned int *subspace_reloc_sizep;
1264      struct reloc_queue *queue;
1265 {
1266   if (addend + 0x80 < 0x100)
1267     {
1268       bfd_put_8 (abfd, R_DATA_OVERRIDE + 1, p);
1269       bfd_put_8 (abfd, addend, p + 1);
1270       p = try_prev_fixup (abfd, subspace_reloc_sizep, p, 2, queue);
1271     }
1272   else if (addend + 0x8000 < 0x10000)
1273     {
1274       bfd_put_8 (abfd, R_DATA_OVERRIDE + 2, p);
1275       bfd_put_16 (abfd, addend, p + 1);
1276       p = try_prev_fixup (abfd, subspace_reloc_sizep, p, 3, queue);
1277     }
1278   else if (addend + 0x800000 < 0x1000000)
1279     {
1280       bfd_put_8 (abfd, R_DATA_OVERRIDE + 3, p);
1281       bfd_put_8 (abfd, addend >> 16, p + 1);
1282       bfd_put_16 (abfd, addend, p + 2);
1283       p = try_prev_fixup (abfd, subspace_reloc_sizep, p, 4, queue);
1284     }
1285   else
1286     {
1287       bfd_put_8 (abfd, R_DATA_OVERRIDE + 4, p);
1288       bfd_put_32 (abfd, addend, p + 1);
1289       p = try_prev_fixup (abfd, subspace_reloc_sizep, p, 5, queue);
1290     }
1291   return p;
1292 }
1293
1294 /* Handle a single function call relocation.  */
1295
1296 static unsigned char *
1297 som_reloc_call (abfd, p, subspace_reloc_sizep, bfd_reloc, sym_num, queue)
1298      bfd *abfd;
1299      unsigned char *p;
1300      unsigned int *subspace_reloc_sizep;
1301      arelent *bfd_reloc;
1302      int sym_num;
1303      struct reloc_queue *queue;
1304 {
1305   int arg_bits = HPPA_R_ARG_RELOC (bfd_reloc->addend);
1306   int rtn_bits = arg_bits & 0x3;
1307   int type, done = 0;
1308
1309   /* You'll never believe all this is necessary to handle relocations
1310      for function calls.  Having to compute and pack the argument
1311      relocation bits is the real nightmare.
1312
1313      If you're interested in how this works, just forget it.  You really
1314      do not want to know about this braindamage.  */
1315
1316   /* First see if this can be done with a "simple" relocation.  Simple
1317      relocations have a symbol number < 0x100 and have simple encodings
1318      of argument relocations.  */
1319
1320   if (sym_num < 0x100)
1321     {
1322       switch (arg_bits)
1323         {
1324         case 0:
1325         case 1:
1326           type = 0;
1327           break;
1328         case 1 << 8:
1329         case 1 << 8 | 1:
1330           type = 1;
1331           break;
1332         case 1 << 8 | 1 << 6:
1333         case 1 << 8 | 1 << 6 | 1:
1334           type = 2;
1335           break;
1336         case 1 << 8 | 1 << 6 | 1 << 4:
1337         case 1 << 8 | 1 << 6 | 1 << 4 | 1:
1338           type = 3;
1339           break;
1340         case 1 << 8 | 1 << 6 | 1 << 4 | 1 << 2:
1341         case 1 << 8 | 1 << 6 | 1 << 4 | 1 << 2 | 1:
1342           type = 4;
1343           break;
1344         default:
1345           /* Not one of the easy encodings.  This will have to be
1346              handled by the more complex code below.  */
1347           type = -1;
1348           break;
1349         }
1350       if (type != -1)
1351         {
1352           /* Account for the return value too.  */
1353           if (rtn_bits)
1354             type += 5;
1355
1356           /* Emit a 2 byte relocation.  Then see if it can be handled
1357              with a relocation which is already in the relocation queue.  */
1358           bfd_put_8 (abfd, bfd_reloc->howto->type + type, p);
1359           bfd_put_8 (abfd, sym_num, p + 1);
1360           p = try_prev_fixup (abfd, subspace_reloc_sizep, p, 2, queue);
1361           done = 1;
1362         }
1363     }
1364
1365   /* If this could not be handled with a simple relocation, then do a hard
1366      one.  Hard relocations occur if the symbol number was too high or if
1367      the encoding of argument relocation bits is too complex.  */
1368   if (! done)
1369     {
1370       /* Don't ask about these magic sequences.  I took them straight
1371          from gas-1.36 which took them from the a.out man page.  */
1372       type = rtn_bits;
1373       if ((arg_bits >> 6 & 0xf) == 0xe)
1374         type += 9 * 40;
1375       else
1376         type += (3 * (arg_bits >> 8 & 3) + (arg_bits >> 6 & 3)) * 40;
1377       if ((arg_bits >> 2 & 0xf) == 0xe)
1378         type += 9 * 4;
1379       else
1380         type += (3 * (arg_bits >> 4 & 3) + (arg_bits >> 2 & 3)) * 4;
1381
1382       /* Output the first two bytes of the relocation.  These describe
1383          the length of the relocation and encoding style.  */
1384       bfd_put_8 (abfd, bfd_reloc->howto->type + 10
1385                  + 2 * (sym_num >= 0x100) + (type >= 0x100),
1386                  p);
1387       bfd_put_8 (abfd, type, p + 1);
1388
1389       /* Now output the symbol index and see if this bizarre relocation
1390          just happened to be in the relocation queue.  */
1391       if (sym_num < 0x100)
1392         {
1393           bfd_put_8 (abfd, sym_num, p + 2);
1394           p = try_prev_fixup (abfd, subspace_reloc_sizep, p, 3, queue);
1395         }
1396       else
1397         {
1398           bfd_put_8 (abfd, sym_num >> 16, p + 2);
1399           bfd_put_16 (abfd, (bfd_vma) sym_num, p + 3);
1400           p = try_prev_fixup (abfd, subspace_reloc_sizep, p, 5, queue);
1401         }
1402     }
1403   return p;
1404 }
1405
1406 /* Return the logarithm of X, base 2, considering X unsigned.
1407    Abort -1 if X is not a power or two or is zero.  */
1408
1409 static int
1410 log2 (x)
1411      unsigned int x;
1412 {
1413   int log = 0;
1414
1415   /* Test for 0 or a power of 2.  */
1416   if (x == 0 || x != (x & -x))
1417     return -1;
1418
1419   while ((x >>= 1) != 0)
1420     log++;
1421   return log;
1422 }
1423
1424 static bfd_reloc_status_type
1425 hppa_som_reloc (abfd, reloc_entry, symbol_in, data,
1426                 input_section, output_bfd, error_message)
1427      bfd *abfd ATTRIBUTE_UNUSED;
1428      arelent *reloc_entry;
1429      asymbol *symbol_in ATTRIBUTE_UNUSED;
1430      PTR data ATTRIBUTE_UNUSED;
1431      asection *input_section;
1432      bfd *output_bfd;
1433      char **error_message ATTRIBUTE_UNUSED;
1434 {
1435   if (output_bfd)
1436     {
1437       reloc_entry->address += input_section->output_offset;
1438       return bfd_reloc_ok;
1439     }
1440   return bfd_reloc_ok;
1441 }
1442
1443 /* Given a generic HPPA relocation type, the instruction format,
1444    and a field selector, return one or more appropriate SOM relocations.  */
1445
1446 int **
1447 hppa_som_gen_reloc_type (abfd, base_type, format, field, sym_diff, sym)
1448      bfd *abfd;
1449      int base_type;
1450      int format;
1451      enum hppa_reloc_field_selector_type_alt field;
1452      int sym_diff;
1453      asymbol *sym;
1454 {
1455   int *final_type, **final_types;
1456
1457   final_types = (int **) bfd_alloc (abfd, (bfd_size_type) sizeof (int *) * 6);
1458   final_type = (int *) bfd_alloc (abfd, (bfd_size_type) sizeof (int));
1459   if (!final_types || !final_type)
1460     return NULL;
1461
1462   /* The field selector may require additional relocations to be
1463      generated.  It's impossible to know at this moment if additional
1464      relocations will be needed, so we make them.  The code to actually
1465      write the relocation/fixup stream is responsible for removing
1466      any redundant relocations.  */
1467   switch (field)
1468     {
1469     case e_fsel:
1470     case e_psel:
1471     case e_lpsel:
1472     case e_rpsel:
1473       final_types[0] = final_type;
1474       final_types[1] = NULL;
1475       final_types[2] = NULL;
1476       *final_type = base_type;
1477       break;
1478
1479     case e_tsel:
1480     case e_ltsel:
1481     case e_rtsel:
1482       final_types[0] = (int *) bfd_alloc (abfd, (bfd_size_type) sizeof (int));
1483       if (!final_types[0])
1484         return NULL;
1485       if (field == e_tsel)
1486         *final_types[0] = R_FSEL;
1487       else if (field == e_ltsel)
1488         *final_types[0] = R_LSEL;
1489       else
1490         *final_types[0] = R_RSEL;
1491       final_types[1] = final_type;
1492       final_types[2] = NULL;
1493       *final_type = base_type;
1494       break;
1495
1496     case e_lssel:
1497     case e_rssel:
1498       final_types[0] = (int *) bfd_alloc (abfd, (bfd_size_type) sizeof (int));
1499       if (!final_types[0])
1500         return NULL;
1501       *final_types[0] = R_S_MODE;
1502       final_types[1] = final_type;
1503       final_types[2] = NULL;
1504       *final_type = base_type;
1505       break;
1506
1507     case e_lsel:
1508     case e_rsel:
1509       final_types[0] = (int *) bfd_alloc (abfd, (bfd_size_type) sizeof (int));
1510       if (!final_types[0])
1511         return NULL;
1512       *final_types[0] = R_N_MODE;
1513       final_types[1] = final_type;
1514       final_types[2] = NULL;
1515       *final_type = base_type;
1516       break;
1517
1518     case e_ldsel:
1519     case e_rdsel:
1520       final_types[0] = (int *) bfd_alloc (abfd, (bfd_size_type) sizeof (int));
1521       if (!final_types[0])
1522         return NULL;
1523       *final_types[0] = R_D_MODE;
1524       final_types[1] = final_type;
1525       final_types[2] = NULL;
1526       *final_type = base_type;
1527       break;
1528
1529     case e_lrsel:
1530     case e_rrsel:
1531       final_types[0] = (int *) bfd_alloc (abfd, (bfd_size_type) sizeof (int));
1532       if (!final_types[0])
1533         return NULL;
1534       *final_types[0] = R_R_MODE;
1535       final_types[1] = final_type;
1536       final_types[2] = NULL;
1537       *final_type = base_type;
1538       break;
1539
1540     case e_nsel:
1541       final_types[0] = (int *) bfd_alloc (abfd, (bfd_size_type) sizeof (int));
1542       if (!final_types[0])
1543         return NULL;
1544       *final_types[0] = R_N1SEL;
1545       final_types[1] = final_type;
1546       final_types[2] = NULL;
1547       *final_type = base_type;
1548       break;
1549
1550     case e_nlsel:
1551     case e_nlrsel:
1552       final_types[0] = (int *) bfd_alloc (abfd, (bfd_size_type) sizeof (int));
1553       if (!final_types[0])
1554         return NULL;
1555       *final_types[0] = R_N0SEL;
1556       final_types[1] = (int *) bfd_alloc (abfd, (bfd_size_type) sizeof (int));
1557       if (!final_types[1])
1558         return NULL;
1559       if (field == e_nlsel)
1560         *final_types[1] = R_N_MODE;
1561       else
1562         *final_types[1] = R_R_MODE;
1563       final_types[2] = final_type;
1564       final_types[3] = NULL;
1565       *final_type = base_type;
1566       break;
1567     }
1568
1569   switch (base_type)
1570     {
1571     case R_HPPA:
1572       /* The difference of two symbols needs *very* special handling.  */
1573       if (sym_diff)
1574         {
1575           bfd_size_type amt = sizeof (int);
1576           final_types[0] = (int *) bfd_alloc (abfd, amt);
1577           final_types[1] = (int *) bfd_alloc (abfd, amt);
1578           final_types[2] = (int *) bfd_alloc (abfd, amt);
1579           final_types[3] = (int *) bfd_alloc (abfd, amt);
1580           if (!final_types[0] || !final_types[1] || !final_types[2])
1581             return NULL;
1582           if (field == e_fsel)
1583             *final_types[0] = R_FSEL;
1584           else if (field == e_rsel)
1585             *final_types[0] = R_RSEL;
1586           else if (field == e_lsel)
1587             *final_types[0] = R_LSEL;
1588           *final_types[1] = R_COMP2;
1589           *final_types[2] = R_COMP2;
1590           *final_types[3] = R_COMP1;
1591           final_types[4] = final_type;
1592           if (format == 32)
1593             *final_types[4] = R_DATA_EXPR;
1594           else
1595             *final_types[4] = R_CODE_EXPR;
1596           final_types[5] = NULL;
1597           break;
1598         }
1599       /* PLABELs get their own relocation type.  */
1600       else if (field == e_psel
1601                || field == e_lpsel
1602                || field == e_rpsel)
1603         {
1604           /* A PLABEL relocation that has a size of 32 bits must
1605              be a R_DATA_PLABEL.  All others are R_CODE_PLABELs.  */
1606           if (format == 32)
1607             *final_type = R_DATA_PLABEL;
1608           else
1609             *final_type = R_CODE_PLABEL;
1610         }
1611       /* PIC stuff.  */
1612       else if (field == e_tsel
1613                || field == e_ltsel
1614                || field == e_rtsel)
1615         *final_type = R_DLT_REL;
1616       /* A relocation in the data space is always a full 32bits.  */
1617       else if (format == 32)
1618         {
1619           *final_type = R_DATA_ONE_SYMBOL;
1620
1621           /* If there's no SOM symbol type associated with this BFD
1622              symbol, then set the symbol type to ST_DATA.
1623
1624              Only do this if the type is going to default later when
1625              we write the object file.
1626
1627              This is done so that the linker never encounters an
1628              R_DATA_ONE_SYMBOL reloc involving an ST_CODE symbol.
1629
1630              This allows the compiler to generate exception handling
1631              tables.
1632
1633              Note that one day we may need to also emit BEGIN_BRTAB and
1634              END_BRTAB to prevent the linker from optimizing away insns
1635              in exception handling regions.  */
1636           if (som_symbol_data (sym)->som_type == SYMBOL_TYPE_UNKNOWN
1637               && (sym->flags & BSF_SECTION_SYM) == 0
1638               && (sym->flags & BSF_FUNCTION) == 0
1639               && ! bfd_is_com_section (sym->section))
1640             som_symbol_data (sym)->som_type = SYMBOL_TYPE_DATA;
1641         }
1642       break;
1643
1644     case R_HPPA_GOTOFF:
1645       /* More PLABEL special cases.  */
1646       if (field == e_psel
1647           || field == e_lpsel
1648           || field == e_rpsel)
1649         *final_type = R_DATA_PLABEL;
1650       break;
1651
1652     case R_HPPA_COMPLEX:
1653       /* The difference of two symbols needs *very* special handling.  */
1654       if (sym_diff)
1655         {
1656           bfd_size_type amt = sizeof (int);
1657           final_types[0] = (int *) bfd_alloc (abfd, amt);
1658           final_types[1] = (int *) bfd_alloc (abfd, amt);
1659           final_types[2] = (int *) bfd_alloc (abfd, amt);
1660           final_types[3] = (int *) bfd_alloc (abfd, amt);
1661           if (!final_types[0] || !final_types[1] || !final_types[2])
1662             return NULL;
1663           if (field == e_fsel)
1664             *final_types[0] = R_FSEL;
1665           else if (field == e_rsel)
1666             *final_types[0] = R_RSEL;
1667           else if (field == e_lsel)
1668             *final_types[0] = R_LSEL;
1669           *final_types[1] = R_COMP2;
1670           *final_types[2] = R_COMP2;
1671           *final_types[3] = R_COMP1;
1672           final_types[4] = final_type;
1673           if (format == 32)
1674             *final_types[4] = R_DATA_EXPR;
1675           else
1676             *final_types[4] = R_CODE_EXPR;
1677           final_types[5] = NULL;
1678           break;
1679         }
1680       else
1681         break;
1682
1683     case R_HPPA_NONE:
1684     case R_HPPA_ABS_CALL:
1685       /* Right now we can default all these.  */
1686       break;
1687
1688     case R_HPPA_PCREL_CALL:
1689       {
1690 #ifndef NO_PCREL_MODES
1691         /* If we have short and long pcrel modes, then generate the proper
1692            mode selector, then the pcrel relocation.  Redundant selectors
1693            will be eliminted as the relocs are sized and emitted.  */
1694         bfd_size_type amt = sizeof (int);
1695         final_types[0] = (int *) bfd_alloc (abfd, amt);
1696         if (!final_types[0])
1697           return NULL;
1698         if (format == 17)
1699           *final_types[0] = R_SHORT_PCREL_MODE;
1700         else
1701           *final_types[0] = R_LONG_PCREL_MODE;
1702         final_types[1] = final_type;
1703         final_types[2] = NULL;
1704         *final_type = base_type;
1705 #endif
1706         break;
1707       }
1708     }
1709   return final_types;
1710 }
1711
1712 /* Return the address of the correct entry in the PA SOM relocation
1713    howto table.  */
1714
1715 static reloc_howto_type *
1716 som_bfd_reloc_type_lookup (abfd, code)
1717      bfd *abfd ATTRIBUTE_UNUSED;
1718      bfd_reloc_code_real_type code;
1719 {
1720   if ((int) code < (int) R_NO_RELOCATION + 255)
1721     {
1722       BFD_ASSERT ((int) som_hppa_howto_table[(int) code].type == (int) code);
1723       return &som_hppa_howto_table[(int) code];
1724     }
1725
1726   return (reloc_howto_type *) 0;
1727 }
1728
1729 /* Perform some initialization for an object.  Save results of this
1730    initialization in the BFD.  */
1731
1732 static const bfd_target *
1733 som_object_setup (abfd, file_hdrp, aux_hdrp, current_offset)
1734      bfd *abfd;
1735      struct header *file_hdrp;
1736      struct som_exec_auxhdr *aux_hdrp;
1737      unsigned long current_offset;
1738 {
1739   asection *section;
1740   int found;
1741
1742   /* som_mkobject will set bfd_error if som_mkobject fails.  */
1743   if (som_mkobject (abfd) != true)
1744     return 0;
1745
1746   /* Set BFD flags based on what information is available in the SOM.  */
1747   abfd->flags = BFD_NO_FLAGS;
1748   if (file_hdrp->symbol_total)
1749     abfd->flags |= HAS_LINENO | HAS_DEBUG | HAS_SYMS | HAS_LOCALS;
1750
1751   switch (file_hdrp->a_magic)
1752     {
1753     case DEMAND_MAGIC:
1754       abfd->flags |= (D_PAGED | WP_TEXT | EXEC_P);
1755       break;
1756     case SHARE_MAGIC:
1757       abfd->flags |= (WP_TEXT | EXEC_P);
1758       break;
1759     case EXEC_MAGIC:
1760       abfd->flags |= (EXEC_P);
1761       break;
1762     case RELOC_MAGIC:
1763       abfd->flags |= HAS_RELOC;
1764       break;
1765 #ifdef SHL_MAGIC
1766     case SHL_MAGIC:
1767 #endif
1768 #ifdef DL_MAGIC
1769     case DL_MAGIC:
1770 #endif
1771       abfd->flags |= DYNAMIC;
1772       break;
1773
1774     default:
1775       break;
1776     }
1777
1778   /* Allocate space to hold the saved exec header information.  */
1779   obj_som_exec_data (abfd) = (struct som_exec_data *)
1780     bfd_zalloc (abfd, (bfd_size_type) sizeof (struct som_exec_data));
1781   if (obj_som_exec_data (abfd) == NULL)
1782     return NULL;
1783
1784   /* The braindamaged OSF1 linker switched exec_flags and exec_entry!
1785
1786      We used to identify OSF1 binaries based on NEW_VERSION_ID, but
1787      apparently the latest HPUX linker is using NEW_VERSION_ID now.
1788
1789      It's about time, OSF has used the new id since at least 1992;
1790      HPUX didn't start till nearly 1995!.
1791
1792      The new approach examines the entry field.  If it's zero or not 4
1793      byte aligned then it's not a proper code address and we guess it's
1794      really the executable flags.  */
1795   found = 0;
1796   for (section = abfd->sections; section; section = section->next)
1797     {
1798       if ((section->flags & SEC_CODE) == 0)
1799         continue;
1800       if (aux_hdrp->exec_entry >= section->vma
1801           && aux_hdrp->exec_entry < section->vma + section->_cooked_size)
1802         found = 1;
1803     }
1804   if (aux_hdrp->exec_entry == 0
1805       || (aux_hdrp->exec_entry & 0x3) != 0
1806       || ! found)
1807     {
1808       bfd_get_start_address (abfd) = aux_hdrp->exec_flags;
1809       obj_som_exec_data (abfd)->exec_flags = aux_hdrp->exec_entry;
1810     }
1811   else
1812     {
1813       bfd_get_start_address (abfd) = aux_hdrp->exec_entry + current_offset;
1814       obj_som_exec_data (abfd)->exec_flags = aux_hdrp->exec_flags;
1815     }
1816
1817   obj_som_exec_data (abfd)->version_id = file_hdrp->version_id;
1818
1819   bfd_default_set_arch_mach (abfd, bfd_arch_hppa, pa10);
1820   bfd_get_symcount (abfd) = file_hdrp->symbol_total;
1821
1822   /* Initialize the saved symbol table and string table to NULL.
1823      Save important offsets and sizes from the SOM header into
1824      the BFD.  */
1825   obj_som_stringtab (abfd) = (char *) NULL;
1826   obj_som_symtab (abfd) = (som_symbol_type *) NULL;
1827   obj_som_sorted_syms (abfd) = NULL;
1828   obj_som_stringtab_size (abfd) = file_hdrp->symbol_strings_size;
1829   obj_som_sym_filepos (abfd) = file_hdrp->symbol_location + current_offset;
1830   obj_som_str_filepos (abfd) = (file_hdrp->symbol_strings_location
1831                                 + current_offset);
1832   obj_som_reloc_filepos (abfd) = (file_hdrp->fixup_request_location
1833                                   + current_offset);
1834   obj_som_exec_data (abfd)->system_id = file_hdrp->system_id;
1835
1836   return abfd->xvec;
1837 }
1838
1839 /* Convert all of the space and subspace info into BFD sections.  Each space
1840    contains a number of subspaces, which in turn describe the mapping between
1841    regions of the exec file, and the address space that the program runs in.
1842    BFD sections which correspond to spaces will overlap the sections for the
1843    associated subspaces.  */
1844
1845 static boolean
1846 setup_sections (abfd, file_hdr, current_offset)
1847      bfd *abfd;
1848      struct header *file_hdr;
1849      unsigned long current_offset;
1850 {
1851   char *space_strings;
1852   unsigned int space_index, i;
1853   unsigned int total_subspaces = 0;
1854   asection **subspace_sections, *section;
1855   bfd_size_type amt;
1856
1857   /* First, read in space names.  */
1858
1859   amt = file_hdr->space_strings_size;
1860   space_strings = bfd_malloc (amt);
1861   if (!space_strings && amt != 0)
1862     goto error_return;
1863
1864   if (bfd_seek (abfd, current_offset + file_hdr->space_strings_location,
1865                 SEEK_SET) != 0)
1866     goto error_return;
1867   if (bfd_bread (space_strings, amt, abfd) != amt)
1868     goto error_return;
1869
1870   /* Loop over all of the space dictionaries, building up sections.  */
1871   for (space_index = 0; space_index < file_hdr->space_total; space_index++)
1872     {
1873       struct space_dictionary_record space;
1874       struct subspace_dictionary_record subspace, save_subspace;
1875       int subspace_index;
1876       asection *space_asect;
1877       char *newname;
1878
1879       /* Read the space dictionary element.  */
1880       if (bfd_seek (abfd,
1881                     (current_offset + file_hdr->space_location
1882                      + space_index * sizeof space),
1883                     SEEK_SET) != 0)
1884         goto error_return;
1885       amt = sizeof space;
1886       if (bfd_bread (&space, amt, abfd) != amt)
1887         goto error_return;
1888
1889       /* Setup the space name string.  */
1890       space.name.n_name = space.name.n_strx + space_strings;
1891
1892       /* Make a section out of it.  */
1893       amt = strlen (space.name.n_name) + 1;
1894       newname = bfd_alloc (abfd, amt);
1895       if (!newname)
1896         goto error_return;
1897       strcpy (newname, space.name.n_name);
1898
1899       space_asect = bfd_make_section_anyway (abfd, newname);
1900       if (!space_asect)
1901         goto error_return;
1902
1903       if (space.is_loadable == 0)
1904         space_asect->flags |= SEC_DEBUGGING;
1905
1906       /* Set up all the attributes for the space.  */
1907       if (bfd_som_set_section_attributes (space_asect, space.is_defined,
1908                                           space.is_private, space.sort_key,
1909                                           space.space_number) == false)
1910         goto error_return;
1911
1912       /* If the space has no subspaces, then we're done.  */
1913       if (space.subspace_quantity == 0)
1914         continue;
1915
1916       /* Now, read in the first subspace for this space.  */
1917       if (bfd_seek (abfd,
1918                     (current_offset + file_hdr->subspace_location
1919                      + space.subspace_index * sizeof subspace),
1920                     SEEK_SET) != 0)
1921         goto error_return;
1922       amt = sizeof subspace;
1923       if (bfd_bread (&subspace, amt, abfd) != amt)
1924         goto error_return;
1925       /* Seek back to the start of the subspaces for loop below.  */
1926       if (bfd_seek (abfd,
1927                     (current_offset + file_hdr->subspace_location
1928                      + space.subspace_index * sizeof subspace),
1929                     SEEK_SET) != 0)
1930         goto error_return;
1931
1932       /* Setup the start address and file loc from the first subspace
1933          record.  */
1934       space_asect->vma = subspace.subspace_start;
1935       space_asect->filepos = subspace.file_loc_init_value + current_offset;
1936       space_asect->alignment_power = log2 (subspace.alignment);
1937       if (space_asect->alignment_power == (unsigned) -1)
1938         goto error_return;
1939
1940       /* Initialize save_subspace so we can reliably determine if this
1941          loop placed any useful values into it.  */
1942       memset (&save_subspace, 0, sizeof (struct subspace_dictionary_record));
1943
1944       /* Loop over the rest of the subspaces, building up more sections.  */
1945       for (subspace_index = 0; subspace_index < space.subspace_quantity;
1946            subspace_index++)
1947         {
1948           asection *subspace_asect;
1949
1950           /* Read in the next subspace.  */
1951           amt = sizeof subspace;
1952           if (bfd_bread (&subspace, amt, abfd) != amt)
1953             goto error_return;
1954
1955           /* Setup the subspace name string.  */
1956           subspace.name.n_name = subspace.name.n_strx + space_strings;
1957
1958           amt = strlen (subspace.name.n_name) + 1;
1959           newname = bfd_alloc (abfd, amt);
1960           if (!newname)
1961             goto error_return;
1962           strcpy (newname, subspace.name.n_name);
1963
1964           /* Make a section out of this subspace.  */
1965           subspace_asect = bfd_make_section_anyway (abfd, newname);
1966           if (!subspace_asect)
1967             goto error_return;
1968
1969           /* Store private information about the section.  */
1970           if (bfd_som_set_subsection_attributes (subspace_asect, space_asect,
1971                                                  subspace.access_control_bits,
1972                                                  subspace.sort_key,
1973                                                  subspace.quadrant) == false)
1974             goto error_return;
1975
1976           /* Keep an easy mapping between subspaces and sections.
1977              Note we do not necessarily read the subspaces in the
1978              same order in which they appear in the object file.
1979
1980              So to make the target index come out correctly, we
1981              store the location of the subspace header in target
1982              index, then sort using the location of the subspace
1983              header as the key.  Then we can assign correct
1984              subspace indices.  */
1985           total_subspaces++;
1986           subspace_asect->target_index = bfd_tell (abfd) - sizeof (subspace);
1987
1988           /* Set SEC_READONLY and SEC_CODE/SEC_DATA as specified
1989              by the access_control_bits in the subspace header.  */
1990           switch (subspace.access_control_bits >> 4)
1991             {
1992             /* Readonly data.  */
1993             case 0x0:
1994               subspace_asect->flags |= SEC_DATA | SEC_READONLY;
1995               break;
1996
1997             /* Normal data.  */
1998             case 0x1:
1999               subspace_asect->flags |= SEC_DATA;
2000               break;
2001
2002             /* Readonly code and the gateways.
2003                Gateways have other attributes which do not map
2004                into anything BFD knows about.  */
2005             case 0x2:
2006             case 0x4:
2007             case 0x5:
2008             case 0x6:
2009             case 0x7:
2010               subspace_asect->flags |= SEC_CODE | SEC_READONLY;
2011               break;
2012
2013             /* dynamic (writable) code.  */
2014             case 0x3:
2015               subspace_asect->flags |= SEC_CODE;
2016               break;
2017             }
2018
2019           if (subspace.dup_common || subspace.is_common)
2020             subspace_asect->flags |= SEC_IS_COMMON;
2021           else if (subspace.subspace_length > 0)
2022             subspace_asect->flags |= SEC_HAS_CONTENTS;
2023
2024           if (subspace.is_loadable)
2025             subspace_asect->flags |= SEC_ALLOC | SEC_LOAD;
2026           else
2027             subspace_asect->flags |= SEC_DEBUGGING;
2028
2029           if (subspace.code_only)
2030             subspace_asect->flags |= SEC_CODE;
2031
2032           /* Both file_loc_init_value and initialization_length will
2033              be zero for a BSS like subspace.  */
2034           if (subspace.file_loc_init_value == 0
2035               && subspace.initialization_length == 0)
2036             subspace_asect->flags &= ~(SEC_DATA | SEC_LOAD | SEC_HAS_CONTENTS);
2037
2038           /* This subspace has relocations.
2039              The fixup_request_quantity is a byte count for the number of
2040              entries in the relocation stream; it is not the actual number
2041              of relocations in the subspace.  */
2042           if (subspace.fixup_request_quantity != 0)
2043             {
2044               subspace_asect->flags |= SEC_RELOC;
2045               subspace_asect->rel_filepos = subspace.fixup_request_index;
2046               som_section_data (subspace_asect)->reloc_size
2047                 = subspace.fixup_request_quantity;
2048               /* We can not determine this yet.  When we read in the
2049                  relocation table the correct value will be filled in.  */
2050               subspace_asect->reloc_count = (unsigned) -1;
2051             }
2052
2053           /* Update save_subspace if appropriate.  */
2054           if (subspace.file_loc_init_value > save_subspace.file_loc_init_value)
2055             save_subspace = subspace;
2056
2057           subspace_asect->vma = subspace.subspace_start;
2058           subspace_asect->_cooked_size = subspace.subspace_length;
2059           subspace_asect->_raw_size = subspace.subspace_length;
2060           subspace_asect->filepos = (subspace.file_loc_init_value
2061                                      + current_offset);
2062           subspace_asect->alignment_power = log2 (subspace.alignment);
2063           if (subspace_asect->alignment_power == (unsigned) -1)
2064             goto error_return;
2065         }
2066
2067       /* This can happen for a .o which defines symbols in otherwise
2068          empty subspaces.  */
2069       if (!save_subspace.file_loc_init_value)
2070         {
2071           space_asect->_cooked_size = 0;
2072           space_asect->_raw_size = 0;
2073         }
2074       else
2075         {
2076           /* Setup the sizes for the space section based upon the info in the
2077              last subspace of the space.  */
2078           space_asect->_cooked_size = (save_subspace.subspace_start
2079                                        - space_asect->vma
2080                                        + save_subspace.subspace_length);
2081           space_asect->_raw_size = (save_subspace.file_loc_init_value
2082                                     - space_asect->filepos
2083                                     + save_subspace.initialization_length);
2084         }
2085     }
2086   /* Now that we've read in all the subspace records, we need to assign
2087      a target index to each subspace.  */
2088   amt = total_subspaces;
2089   amt *= sizeof (asection *);
2090   subspace_sections = (asection **) bfd_malloc (amt);
2091   if (subspace_sections == NULL)
2092     goto error_return;
2093
2094   for (i = 0, section = abfd->sections; section; section = section->next)
2095     {
2096       if (!som_is_subspace (section))
2097         continue;
2098
2099       subspace_sections[i] = section;
2100       i++;
2101     }
2102   qsort (subspace_sections, total_subspaces,
2103          sizeof (asection *), compare_subspaces);
2104
2105   /* subspace_sections is now sorted in the order in which the subspaces
2106      appear in the object file.  Assign an index to each one now.  */
2107   for (i = 0; i < total_subspaces; i++)
2108     subspace_sections[i]->target_index = i;
2109
2110   if (space_strings != NULL)
2111     free (space_strings);
2112
2113   if (subspace_sections != NULL)
2114     free (subspace_sections);
2115
2116   return true;
2117
2118  error_return:
2119   if (space_strings != NULL)
2120     free (space_strings);
2121
2122   if (subspace_sections != NULL)
2123     free (subspace_sections);
2124   return false;
2125 }
2126
2127 /* Read in a SOM object and make it into a BFD.  */
2128
2129 static const bfd_target *
2130 som_object_p (abfd)
2131      bfd *abfd;
2132 {
2133   struct header file_hdr;
2134   struct som_exec_auxhdr aux_hdr;
2135   unsigned long current_offset = 0;
2136   struct lst_header lst_header;
2137   struct som_entry som_entry;
2138   bfd_size_type amt;
2139 #define ENTRY_SIZE sizeof (struct som_entry)
2140
2141   amt = FILE_HDR_SIZE;
2142   if (bfd_bread ((PTR) &file_hdr, amt, abfd) != amt)
2143     {
2144       if (bfd_get_error () != bfd_error_system_call)
2145         bfd_set_error (bfd_error_wrong_format);
2146       return 0;
2147     }
2148
2149   if (!_PA_RISC_ID (file_hdr.system_id))
2150     {
2151       bfd_set_error (bfd_error_wrong_format);
2152       return 0;
2153     }
2154
2155   switch (file_hdr.a_magic)
2156     {
2157     case RELOC_MAGIC:
2158     case EXEC_MAGIC:
2159     case SHARE_MAGIC:
2160     case DEMAND_MAGIC:
2161 #ifdef DL_MAGIC
2162     case DL_MAGIC:
2163 #endif
2164 #ifdef SHL_MAGIC
2165     case SHL_MAGIC:
2166 #endif
2167 #ifdef SHARED_MAGIC_CNX
2168     case SHARED_MAGIC_CNX:
2169 #endif
2170       break;
2171
2172 #ifdef EXECLIBMAGIC
2173     case EXECLIBMAGIC:
2174       /* Read the lst header and determine where the SOM directory begins.  */
2175
2176       if (bfd_seek (abfd, (file_ptr) 0, SEEK_SET) != 0)
2177         {
2178           if (bfd_get_error () != bfd_error_system_call)
2179             bfd_set_error (bfd_error_wrong_format);
2180           return 0;
2181         }
2182
2183       amt = SLSTHDR;
2184       if (bfd_bread ((PTR) &lst_header, amt, abfd) != amt)
2185         {
2186           if (bfd_get_error () != bfd_error_system_call)
2187             bfd_set_error (bfd_error_wrong_format);
2188           return 0;
2189         }
2190
2191       /* Position to and read the first directory entry.  */
2192
2193       if (bfd_seek (abfd, lst_header.dir_loc, SEEK_SET) != 0)
2194         {
2195           if (bfd_get_error () != bfd_error_system_call)
2196             bfd_set_error (bfd_error_wrong_format);
2197           return 0;
2198         }
2199
2200       amt = ENTRY_SIZE;
2201       if (bfd_bread ((PTR) &som_entry, amt, abfd) != amt)
2202         {
2203           if (bfd_get_error () != bfd_error_system_call)
2204             bfd_set_error (bfd_error_wrong_format);
2205           return 0;
2206         }
2207
2208       /* Now position to the first SOM.  */
2209
2210       if (bfd_seek (abfd, som_entry.location, SEEK_SET) != 0)
2211         {
2212           if (bfd_get_error () != bfd_error_system_call)
2213             bfd_set_error (bfd_error_wrong_format);
2214           return 0;
2215         }
2216
2217       current_offset = som_entry.location;
2218
2219       /* And finally, re-read the som header.  */
2220       amt = FILE_HDR_SIZE;
2221       if (bfd_bread ((PTR) &file_hdr, amt, abfd) != amt)
2222         {
2223           if (bfd_get_error () != bfd_error_system_call)
2224             bfd_set_error (bfd_error_wrong_format);
2225           return 0;
2226         }
2227
2228       break;
2229 #endif
2230
2231     default:
2232       bfd_set_error (bfd_error_wrong_format);
2233       return 0;
2234     }
2235
2236   if (file_hdr.version_id != VERSION_ID
2237       && file_hdr.version_id != NEW_VERSION_ID)
2238     {
2239       bfd_set_error (bfd_error_wrong_format);
2240       return 0;
2241     }
2242
2243   /* If the aux_header_size field in the file header is zero, then this
2244      object is an incomplete executable (a .o file).  Do not try to read
2245      a non-existant auxiliary header.  */
2246   memset (&aux_hdr, 0, sizeof (struct som_exec_auxhdr));
2247   if (file_hdr.aux_header_size != 0)
2248     {
2249       amt = AUX_HDR_SIZE;
2250       if (bfd_bread ((PTR) &aux_hdr, amt, abfd) != amt)
2251         {
2252           if (bfd_get_error () != bfd_error_system_call)
2253             bfd_set_error (bfd_error_wrong_format);
2254           return 0;
2255         }
2256     }
2257
2258   if (!setup_sections (abfd, &file_hdr, current_offset))
2259     {
2260       /* setup_sections does not bubble up a bfd error code.  */
2261       bfd_set_error (bfd_error_bad_value);
2262       return 0;
2263     }
2264
2265   /* This appears to be a valid SOM object.  Do some initialization.  */
2266   return som_object_setup (abfd, &file_hdr, &aux_hdr, current_offset);
2267 }
2268
2269 /* Create a SOM object.  */
2270
2271 static boolean
2272 som_mkobject (abfd)
2273      bfd *abfd;
2274 {
2275   /* Allocate memory to hold backend information.  */
2276   abfd->tdata.som_data = (struct som_data_struct *)
2277     bfd_zalloc (abfd, (bfd_size_type) sizeof (struct som_data_struct));
2278   if (abfd->tdata.som_data == NULL)
2279     return false;
2280   return true;
2281 }
2282
2283 /* Initialize some information in the file header.  This routine makes
2284    not attempt at doing the right thing for a full executable; it
2285    is only meant to handle relocatable objects.  */
2286
2287 static boolean
2288 som_prep_headers (abfd)
2289      bfd *abfd;
2290 {
2291   struct header *file_hdr;
2292   asection *section;
2293   bfd_size_type amt = sizeof (struct header);
2294
2295   /* Make and attach a file header to the BFD.  */
2296   file_hdr = (struct header *) bfd_zalloc (abfd, amt);
2297   if (file_hdr == NULL)
2298     return false;
2299   obj_som_file_hdr (abfd) = file_hdr;
2300
2301   if (abfd->flags & (EXEC_P | DYNAMIC))
2302     {
2303
2304       /* Make and attach an exec header to the BFD.  */
2305       amt = sizeof (struct som_exec_auxhdr);
2306       obj_som_exec_hdr (abfd) =
2307         (struct som_exec_auxhdr *) bfd_zalloc (abfd, amt);
2308       if (obj_som_exec_hdr (abfd) == NULL)
2309         return false;
2310
2311       if (abfd->flags & D_PAGED)
2312         file_hdr->a_magic = DEMAND_MAGIC;
2313       else if (abfd->flags & WP_TEXT)
2314         file_hdr->a_magic = SHARE_MAGIC;
2315 #ifdef SHL_MAGIC
2316       else if (abfd->flags & DYNAMIC)
2317         file_hdr->a_magic = SHL_MAGIC;
2318 #endif
2319       else
2320         file_hdr->a_magic = EXEC_MAGIC;
2321     }
2322   else
2323     file_hdr->a_magic = RELOC_MAGIC;
2324
2325   /* These fields are optional, and embedding timestamps is not always
2326      a wise thing to do, it makes comparing objects during a multi-stage
2327      bootstrap difficult.  */
2328   file_hdr->file_time.secs = 0;
2329   file_hdr->file_time.nanosecs = 0;
2330
2331   file_hdr->entry_space = 0;
2332   file_hdr->entry_subspace = 0;
2333   file_hdr->entry_offset = 0;
2334   file_hdr->presumed_dp = 0;
2335
2336   /* Now iterate over the sections translating information from
2337      BFD sections to SOM spaces/subspaces.  */
2338
2339   for (section = abfd->sections; section != NULL; section = section->next)
2340     {
2341       /* Ignore anything which has not been marked as a space or
2342          subspace.  */
2343       if (!som_is_space (section) && !som_is_subspace (section))
2344         continue;
2345
2346       if (som_is_space (section))
2347         {
2348           /* Allocate space for the space dictionary.  */
2349           amt = sizeof (struct space_dictionary_record);
2350           som_section_data (section)->space_dict =
2351             (struct space_dictionary_record *) bfd_zalloc (abfd, amt);
2352           if (som_section_data (section)->space_dict == NULL)
2353             return false;
2354           /* Set space attributes.  Note most attributes of SOM spaces
2355              are set based on the subspaces it contains.  */
2356           som_section_data (section)->space_dict->loader_fix_index = -1;
2357           som_section_data (section)->space_dict->init_pointer_index = -1;
2358
2359           /* Set more attributes that were stuffed away in private data.  */
2360           som_section_data (section)->space_dict->sort_key =
2361             som_section_data (section)->copy_data->sort_key;
2362           som_section_data (section)->space_dict->is_defined =
2363             som_section_data (section)->copy_data->is_defined;
2364           som_section_data (section)->space_dict->is_private =
2365             som_section_data (section)->copy_data->is_private;
2366           som_section_data (section)->space_dict->space_number =
2367             som_section_data (section)->copy_data->space_number;
2368         }
2369       else
2370         {
2371           /* Allocate space for the subspace dictionary.  */
2372           amt = sizeof (struct subspace_dictionary_record);
2373           som_section_data (section)->subspace_dict =
2374             (struct subspace_dictionary_record *) bfd_zalloc (abfd, amt);
2375           if (som_section_data (section)->subspace_dict == NULL)
2376             return false;
2377
2378           /* Set subspace attributes.  Basic stuff is done here, additional
2379              attributes are filled in later as more information becomes
2380              available.  */
2381           if (section->flags & SEC_IS_COMMON)
2382             {
2383               som_section_data (section)->subspace_dict->dup_common = 1;
2384               som_section_data (section)->subspace_dict->is_common = 1;
2385             }
2386
2387           if (section->flags & SEC_ALLOC)
2388             som_section_data (section)->subspace_dict->is_loadable = 1;
2389
2390           if (section->flags & SEC_CODE)
2391             som_section_data (section)->subspace_dict->code_only = 1;
2392
2393           som_section_data (section)->subspace_dict->subspace_start =
2394             section->vma;
2395           som_section_data (section)->subspace_dict->subspace_length =
2396             bfd_section_size (abfd, section);
2397           som_section_data (section)->subspace_dict->initialization_length =
2398             bfd_section_size (abfd, section);
2399           som_section_data (section)->subspace_dict->alignment =
2400             1 << section->alignment_power;
2401
2402           /* Set more attributes that were stuffed away in private data.  */
2403           som_section_data (section)->subspace_dict->sort_key =
2404             som_section_data (section)->copy_data->sort_key;
2405           som_section_data (section)->subspace_dict->access_control_bits =
2406             som_section_data (section)->copy_data->access_control_bits;
2407           som_section_data (section)->subspace_dict->quadrant =
2408             som_section_data (section)->copy_data->quadrant;
2409         }
2410     }
2411   return true;
2412 }
2413
2414 /* Return true if the given section is a SOM space, false otherwise.  */
2415
2416 static boolean
2417 som_is_space (section)
2418      asection *section;
2419 {
2420   /* If no copy data is available, then it's neither a space nor a
2421      subspace.  */
2422   if (som_section_data (section)->copy_data == NULL)
2423     return false;
2424
2425   /* If the containing space isn't the same as the given section,
2426      then this isn't a space.  */
2427   if (som_section_data (section)->copy_data->container != section
2428       && (som_section_data (section)->copy_data->container->output_section
2429           != section))
2430     return false;
2431
2432   /* OK.  Must be a space.  */
2433   return true;
2434 }
2435
2436 /* Return true if the given section is a SOM subspace, false otherwise.  */
2437
2438 static boolean
2439 som_is_subspace (section)
2440      asection *section;
2441 {
2442   /* If no copy data is available, then it's neither a space nor a
2443      subspace.  */
2444   if (som_section_data (section)->copy_data == NULL)
2445     return false;
2446
2447   /* If the containing space is the same as the given section,
2448      then this isn't a subspace.  */
2449   if (som_section_data (section)->copy_data->container == section
2450       || (som_section_data (section)->copy_data->container->output_section
2451           == section))
2452     return false;
2453
2454   /* OK.  Must be a subspace.  */
2455   return true;
2456 }
2457
2458 /* Return true if the given space containins the given subspace.  It
2459    is safe to assume space really is a space, and subspace really
2460    is a subspace.  */
2461
2462 static boolean
2463 som_is_container (space, subspace)
2464      asection *space, *subspace;
2465 {
2466   return (som_section_data (subspace)->copy_data->container == space
2467           || (som_section_data (subspace)->copy_data->container->output_section
2468               == space));
2469 }
2470
2471 /* Count and return the number of spaces attached to the given BFD.  */
2472
2473 static unsigned long
2474 som_count_spaces (abfd)
2475      bfd *abfd;
2476 {
2477   int count = 0;
2478   asection *section;
2479
2480   for (section = abfd->sections; section != NULL; section = section->next)
2481     count += som_is_space (section);
2482
2483   return count;
2484 }
2485
2486 /* Count the number of subspaces attached to the given BFD.  */
2487
2488 static unsigned long
2489 som_count_subspaces (abfd)
2490      bfd *abfd;
2491 {
2492   int count = 0;
2493   asection *section;
2494
2495   for (section = abfd->sections; section != NULL; section = section->next)
2496     count += som_is_subspace (section);
2497
2498   return count;
2499 }
2500
2501 /* Return -1, 0, 1 indicating the relative ordering of sym1 and sym2.
2502
2503    We desire symbols to be ordered starting with the symbol with the
2504    highest relocation count down to the symbol with the lowest relocation
2505    count.  Doing so compacts the relocation stream.  */
2506
2507 static int
2508 compare_syms (arg1, arg2)
2509      const PTR arg1;
2510      const PTR arg2;
2511
2512 {
2513   asymbol **sym1 = (asymbol **) arg1;
2514   asymbol **sym2 = (asymbol **) arg2;
2515   unsigned int count1, count2;
2516
2517   /* Get relocation count for each symbol.  Note that the count
2518      is stored in the udata pointer for section symbols!  */
2519   if ((*sym1)->flags & BSF_SECTION_SYM)
2520     count1 = (*sym1)->udata.i;
2521   else
2522     count1 = som_symbol_data (*sym1)->reloc_count;
2523
2524   if ((*sym2)->flags & BSF_SECTION_SYM)
2525     count2 = (*sym2)->udata.i;
2526   else
2527     count2 = som_symbol_data (*sym2)->reloc_count;
2528
2529   /* Return the appropriate value.  */
2530   if (count1 < count2)
2531     return 1;
2532   else if (count1 > count2)
2533     return -1;
2534   return 0;
2535 }
2536
2537 /* Return -1, 0, 1 indicating the relative ordering of subspace1
2538    and subspace.  */
2539
2540 static int
2541 compare_subspaces (arg1, arg2)
2542      const PTR arg1;
2543      const PTR arg2;
2544
2545 {
2546   asection **subspace1 = (asection **) arg1;
2547   asection **subspace2 = (asection **) arg2;
2548
2549   if ((*subspace1)->target_index < (*subspace2)->target_index)
2550     return -1;
2551   else if ((*subspace2)->target_index < (*subspace1)->target_index)
2552     return 1;
2553   else
2554     return 0;
2555 }
2556
2557 /* Perform various work in preparation for emitting the fixup stream.  */
2558
2559 static void
2560 som_prep_for_fixups (abfd, syms, num_syms)
2561      bfd *abfd;
2562      asymbol **syms;
2563      unsigned long num_syms;
2564 {
2565   unsigned long i;
2566   asection *section;
2567   asymbol **sorted_syms;
2568   bfd_size_type amt;
2569
2570   /* Most SOM relocations involving a symbol have a length which is
2571      dependent on the index of the symbol.  So symbols which are
2572      used often in relocations should have a small index.  */
2573
2574   /* First initialize the counters for each symbol.  */
2575   for (i = 0; i < num_syms; i++)
2576     {
2577       /* Handle a section symbol; these have no pointers back to the
2578          SOM symbol info.  So we just use the udata field to hold the
2579          relocation count.  */
2580       if (som_symbol_data (syms[i]) == NULL
2581           || syms[i]->flags & BSF_SECTION_SYM)
2582         {
2583           syms[i]->flags |= BSF_SECTION_SYM;
2584           syms[i]->udata.i = 0;
2585         }
2586       else
2587         som_symbol_data (syms[i])->reloc_count = 0;
2588     }
2589
2590   /* Now that the counters are initialized, make a weighted count
2591      of how often a given symbol is used in a relocation.  */
2592   for (section = abfd->sections; section != NULL; section = section->next)
2593     {
2594       int j;
2595
2596       /* Does this section have any relocations?  */
2597       if ((int) section->reloc_count <= 0)
2598         continue;
2599
2600       /* Walk through each relocation for this section.  */
2601       for (j = 1; j < (int) section->reloc_count; j++)
2602         {
2603           arelent *reloc = section->orelocation[j];
2604           int scale;
2605
2606           /* A relocation against a symbol in the *ABS* section really
2607              does not have a symbol.  Likewise if the symbol isn't associated
2608              with any section.  */
2609           if (reloc->sym_ptr_ptr == NULL
2610               || bfd_is_abs_section ((*reloc->sym_ptr_ptr)->section))
2611             continue;
2612
2613           /* Scaling to encourage symbols involved in R_DP_RELATIVE
2614              and R_CODE_ONE_SYMBOL relocations to come first.  These
2615              two relocations have single byte versions if the symbol
2616              index is very small.  */
2617           if (reloc->howto->type == R_DP_RELATIVE
2618               || reloc->howto->type == R_CODE_ONE_SYMBOL)
2619             scale = 2;
2620           else
2621             scale = 1;
2622
2623           /* Handle section symbols by storing the count in the udata
2624              field.  It will not be used and the count is very important
2625              for these symbols.  */
2626           if ((*reloc->sym_ptr_ptr)->flags & BSF_SECTION_SYM)
2627             {
2628               (*reloc->sym_ptr_ptr)->udata.i =
2629                 (*reloc->sym_ptr_ptr)->udata.i + scale;
2630               continue;
2631             }
2632
2633           /* A normal symbol.  Increment the count.  */
2634           som_symbol_data (*reloc->sym_ptr_ptr)->reloc_count += scale;
2635         }
2636     }
2637
2638   /* Sort a copy of the symbol table, rather than the canonical
2639      output symbol table.  */
2640   amt = num_syms;
2641   amt *= sizeof (asymbol *);
2642   sorted_syms = (asymbol **) bfd_zalloc (abfd, amt);
2643   memcpy (sorted_syms, syms, num_syms * sizeof (asymbol *));
2644   qsort (sorted_syms, num_syms, sizeof (asymbol *), compare_syms);
2645   obj_som_sorted_syms (abfd) = sorted_syms;
2646
2647   /* Compute the symbol indexes, they will be needed by the relocation
2648      code.  */
2649   for (i = 0; i < num_syms; i++)
2650     {
2651       /* A section symbol.  Again, there is no pointer to backend symbol
2652          information, so we reuse the udata field again.  */
2653       if (sorted_syms[i]->flags & BSF_SECTION_SYM)
2654         sorted_syms[i]->udata.i = i;
2655       else
2656         som_symbol_data (sorted_syms[i])->index = i;
2657     }
2658 }
2659
2660 static boolean
2661 som_write_fixups (abfd, current_offset, total_reloc_sizep)
2662      bfd *abfd;
2663      unsigned long current_offset;
2664      unsigned int *total_reloc_sizep;
2665 {
2666   unsigned int i, j;
2667   /* Chunk of memory that we can use as buffer space, then throw
2668      away.  */
2669   unsigned char tmp_space[SOM_TMP_BUFSIZE];
2670   unsigned char *p;
2671   unsigned int total_reloc_size = 0;
2672   unsigned int subspace_reloc_size = 0;
2673   unsigned int num_spaces = obj_som_file_hdr (abfd)->space_total;
2674   asection *section = abfd->sections;
2675   bfd_size_type amt;
2676
2677   memset (tmp_space, 0, SOM_TMP_BUFSIZE);
2678   p = tmp_space;
2679
2680   /* All the fixups for a particular subspace are emitted in a single
2681      stream.  All the subspaces for a particular space are emitted
2682      as a single stream.
2683
2684      So, to get all the locations correct one must iterate through all the
2685      spaces, for each space iterate through its subspaces and output a
2686      fixups stream.  */
2687   for (i = 0; i < num_spaces; i++)
2688     {
2689       asection *subsection;
2690
2691       /* Find a space.  */
2692       while (!som_is_space (section))
2693         section = section->next;
2694
2695       /* Now iterate through each of its subspaces.  */
2696       for (subsection = abfd->sections;
2697            subsection != NULL;
2698            subsection = subsection->next)
2699         {
2700           int reloc_offset;
2701           unsigned int current_rounding_mode;
2702 #ifndef NO_PCREL_MODES
2703           int current_call_mode;
2704 #endif
2705
2706           /* Find a subspace of this space.  */
2707           if (!som_is_subspace (subsection)
2708               || !som_is_container (section, subsection))
2709             continue;
2710
2711           /* If this subspace does not have real data, then we are
2712              finised with it.  */
2713           if ((subsection->flags & SEC_HAS_CONTENTS) == 0)
2714             {
2715               som_section_data (subsection)->subspace_dict->fixup_request_index
2716                 = -1;
2717               continue;
2718             }
2719
2720           /* This subspace has some relocations.  Put the relocation stream
2721              index into the subspace record.  */
2722           som_section_data (subsection)->subspace_dict->fixup_request_index
2723             = total_reloc_size;
2724
2725           /* To make life easier start over with a clean slate for
2726              each subspace.  Seek to the start of the relocation stream
2727              for this subspace in preparation for writing out its fixup
2728              stream.  */
2729           if (bfd_seek (abfd, current_offset + total_reloc_size, SEEK_SET) != 0)
2730             return false;
2731
2732           /* Buffer space has already been allocated.  Just perform some
2733              initialization here.  */
2734           p = tmp_space;
2735           subspace_reloc_size = 0;
2736           reloc_offset = 0;
2737           som_initialize_reloc_queue (reloc_queue);
2738           current_rounding_mode = R_N_MODE;
2739 #ifndef NO_PCREL_MODES
2740           current_call_mode = R_SHORT_PCREL_MODE;
2741 #endif
2742
2743           /* Translate each BFD relocation into one or more SOM
2744              relocations.  */
2745           for (j = 0; j < subsection->reloc_count; j++)
2746             {
2747               arelent *bfd_reloc = subsection->orelocation[j];
2748               unsigned int skip;
2749               int sym_num;
2750
2751               /* Get the symbol number.  Remember it's stored in a
2752                  special place for section symbols.  */
2753               if ((*bfd_reloc->sym_ptr_ptr)->flags & BSF_SECTION_SYM)
2754                 sym_num = (*bfd_reloc->sym_ptr_ptr)->udata.i;
2755               else
2756                 sym_num = som_symbol_data (*bfd_reloc->sym_ptr_ptr)->index;
2757
2758               /* If there is not enough room for the next couple relocations,
2759                  then dump the current buffer contents now.  Also reinitialize
2760                  the relocation queue.
2761
2762                  No single BFD relocation could ever translate into more
2763                  than 100 bytes of SOM relocations (20bytes is probably the
2764                  upper limit, but leave lots of space for growth).  */
2765               if (p - tmp_space + 100 > SOM_TMP_BUFSIZE)
2766                 {
2767                   amt = p - tmp_space;
2768                   if (bfd_bwrite ((PTR) tmp_space, amt, abfd) != amt)
2769                     return false;
2770
2771                   p = tmp_space;
2772                   som_initialize_reloc_queue (reloc_queue);
2773                 }
2774
2775               /* Emit R_NO_RELOCATION fixups to map any bytes which were
2776                  skipped.  */
2777               skip = bfd_reloc->address - reloc_offset;
2778               p = som_reloc_skip (abfd, skip, p,
2779                                   &subspace_reloc_size, reloc_queue);
2780
2781               /* Update reloc_offset for the next iteration.
2782
2783                  Many relocations do not consume input bytes.  They
2784                  are markers, or set state necessary to perform some
2785                  later relocation.  */
2786               switch (bfd_reloc->howto->type)
2787                 {
2788                 case R_ENTRY:
2789                 case R_ALT_ENTRY:
2790                 case R_EXIT:
2791                 case R_N_MODE:
2792                 case R_S_MODE:
2793                 case R_D_MODE:
2794                 case R_R_MODE:
2795                 case R_FSEL:
2796                 case R_LSEL:
2797                 case R_RSEL:
2798                 case R_COMP1:
2799                 case R_COMP2:
2800                 case R_BEGIN_BRTAB:
2801                 case R_END_BRTAB:
2802                 case R_BEGIN_TRY:
2803                 case R_END_TRY:
2804                 case R_N0SEL:
2805                 case R_N1SEL:
2806 #ifndef NO_PCREL_MODES
2807                 case R_SHORT_PCREL_MODE:
2808                 case R_LONG_PCREL_MODE:
2809 #endif
2810                   reloc_offset = bfd_reloc->address;
2811                   break;
2812
2813                 default:
2814                   reloc_offset = bfd_reloc->address + 4;
2815                   break;
2816                 }
2817
2818               /* Now the actual relocation we care about.  */
2819               switch (bfd_reloc->howto->type)
2820                 {
2821                 case R_PCREL_CALL:
2822                 case R_ABS_CALL:
2823                   p = som_reloc_call (abfd, p, &subspace_reloc_size,
2824                                       bfd_reloc, sym_num, reloc_queue);
2825                   break;
2826
2827                 case R_CODE_ONE_SYMBOL:
2828                 case R_DP_RELATIVE:
2829                   /* Account for any addend.  */
2830                   if (bfd_reloc->addend)
2831                     p = som_reloc_addend (abfd, bfd_reloc->addend, p,
2832                                           &subspace_reloc_size, reloc_queue);
2833
2834                   if (sym_num < 0x20)
2835                     {
2836                       bfd_put_8 (abfd, bfd_reloc->howto->type + sym_num, p);
2837                       subspace_reloc_size += 1;
2838                       p += 1;
2839                     }
2840                   else if (sym_num < 0x100)
2841                     {
2842                       bfd_put_8 (abfd, bfd_reloc->howto->type + 32, p);
2843                       bfd_put_8 (abfd, sym_num, p + 1);
2844                       p = try_prev_fixup (abfd, &subspace_reloc_size, p,
2845                                           2, reloc_queue);
2846                     }
2847                   else if (sym_num < 0x10000000)
2848                     {
2849                       bfd_put_8 (abfd, bfd_reloc->howto->type + 33, p);
2850                       bfd_put_8 (abfd, sym_num >> 16, p + 1);
2851                       bfd_put_16 (abfd, (bfd_vma) sym_num, p + 2);
2852                       p = try_prev_fixup (abfd, &subspace_reloc_size,
2853                                           p, 4, reloc_queue);
2854                     }
2855                   else
2856                     abort ();
2857                   break;
2858
2859                 case R_DATA_ONE_SYMBOL:
2860                 case R_DATA_PLABEL:
2861                 case R_CODE_PLABEL:
2862                 case R_DLT_REL:
2863                   /* Account for any addend using R_DATA_OVERRIDE.  */
2864                   if (bfd_reloc->howto->type != R_DATA_ONE_SYMBOL
2865                       && bfd_reloc->addend)
2866                     p = som_reloc_addend (abfd, bfd_reloc->addend, p,
2867                                           &subspace_reloc_size, reloc_queue);
2868
2869                   if (sym_num < 0x100)
2870                     {
2871                       bfd_put_8 (abfd, bfd_reloc->howto->type, p);
2872                       bfd_put_8 (abfd, sym_num, p + 1);
2873                       p = try_prev_fixup (abfd, &subspace_reloc_size, p,
2874                                           2, reloc_queue);
2875                     }
2876                   else if (sym_num < 0x10000000)
2877                     {
2878                       bfd_put_8 (abfd, bfd_reloc->howto->type + 1, p);
2879                       bfd_put_8 (abfd, sym_num >> 16, p + 1);
2880                       bfd_put_16 (abfd, (bfd_vma) sym_num, p + 2);
2881                       p = try_prev_fixup (abfd, &subspace_reloc_size,
2882                                           p, 4, reloc_queue);
2883                     }
2884                   else
2885                     abort ();
2886                   break;
2887
2888                 case R_ENTRY:
2889                   {
2890                     unsigned int tmp;
2891                     arelent *tmp_reloc = NULL;
2892                     bfd_put_8 (abfd, R_ENTRY, p);
2893
2894                     /* R_ENTRY relocations have 64 bits of associated
2895                        data.  Unfortunately the addend field of a bfd
2896                        relocation is only 32 bits.  So, we split up
2897                        the 64bit unwind information and store part in
2898                        the R_ENTRY relocation, and the rest in the R_EXIT
2899                        relocation.  */
2900                     bfd_put_32 (abfd, bfd_reloc->addend, p + 1);
2901
2902                     /* Find the next R_EXIT relocation.  */
2903                     for (tmp = j; tmp < subsection->reloc_count; tmp++)
2904                       {
2905                         tmp_reloc = subsection->orelocation[tmp];
2906                         if (tmp_reloc->howto->type == R_EXIT)
2907                           break;
2908                       }
2909
2910                     if (tmp == subsection->reloc_count)
2911                       abort ();
2912
2913                     bfd_put_32 (abfd, tmp_reloc->addend, p + 5);
2914                     p = try_prev_fixup (abfd, &subspace_reloc_size,
2915                                         p, 9, reloc_queue);
2916                     break;
2917                   }
2918
2919                 case R_N_MODE:
2920                 case R_S_MODE:
2921                 case R_D_MODE:
2922                 case R_R_MODE:
2923                   /* If this relocation requests the current rounding
2924                      mode, then it is redundant.  */
2925                   if (bfd_reloc->howto->type != current_rounding_mode)
2926                     {
2927                       bfd_put_8 (abfd, bfd_reloc->howto->type, p);
2928                       subspace_reloc_size += 1;
2929                       p += 1;
2930                       current_rounding_mode = bfd_reloc->howto->type;
2931                     }
2932                   break;
2933
2934 #ifndef NO_PCREL_MODES
2935                 case R_LONG_PCREL_MODE:
2936                 case R_SHORT_PCREL_MODE:
2937                   if (bfd_reloc->howto->type != current_call_mode)
2938                     {
2939                       bfd_put_8 (abfd, bfd_reloc->howto->type, p);
2940                       subspace_reloc_size += 1;
2941                       p += 1;
2942                       current_call_mode = bfd_reloc->howto->type;
2943                     }
2944                   break;
2945 #endif
2946
2947                 case R_EXIT:
2948                 case R_ALT_ENTRY:
2949                 case R_FSEL:
2950                 case R_LSEL:
2951                 case R_RSEL:
2952                 case R_BEGIN_BRTAB:
2953                 case R_END_BRTAB:
2954                 case R_BEGIN_TRY:
2955                 case R_N0SEL:
2956                 case R_N1SEL:
2957                   bfd_put_8 (abfd, bfd_reloc->howto->type, p);
2958                   subspace_reloc_size += 1;
2959                   p += 1;
2960                   break;
2961
2962                 case R_END_TRY:
2963                   /* The end of an exception handling region.  The reloc's
2964                      addend contains the offset of the exception handling
2965                      code.  */
2966                   if (bfd_reloc->addend == 0)
2967                     bfd_put_8 (abfd, bfd_reloc->howto->type, p);
2968                   else if (bfd_reloc->addend < 1024)
2969                     {
2970                       bfd_put_8 (abfd, bfd_reloc->howto->type + 1, p);
2971                       bfd_put_8 (abfd, bfd_reloc->addend / 4, p + 1);
2972                       p = try_prev_fixup (abfd, &subspace_reloc_size,
2973                                           p, 2, reloc_queue);
2974                     }
2975                   else
2976                     {
2977                       bfd_put_8 (abfd, bfd_reloc->howto->type + 2, p);
2978                       bfd_put_8 (abfd, (bfd_reloc->addend / 4) >> 16, p + 1);
2979                       bfd_put_16 (abfd, bfd_reloc->addend / 4, p + 2);
2980                       p = try_prev_fixup (abfd, &subspace_reloc_size,
2981                                           p, 4, reloc_queue);
2982                     }
2983                   break;
2984
2985                 case R_COMP1:
2986                   /* The only time we generate R_COMP1, R_COMP2 and
2987                      R_CODE_EXPR relocs is for the difference of two
2988                      symbols.  Hence we can cheat here.  */
2989                   bfd_put_8 (abfd, bfd_reloc->howto->type, p);
2990                   bfd_put_8 (abfd, 0x44, p + 1);
2991                   p = try_prev_fixup (abfd, &subspace_reloc_size,
2992                                       p, 2, reloc_queue);
2993                   break;
2994
2995                 case R_COMP2:
2996                   /* The only time we generate R_COMP1, R_COMP2 and
2997                      R_CODE_EXPR relocs is for the difference of two
2998                      symbols.  Hence we can cheat here.  */
2999                   bfd_put_8 (abfd, bfd_reloc->howto->type, p);
3000                   bfd_put_8 (abfd, 0x80, p + 1);
3001                   bfd_put_8 (abfd, sym_num >> 16, p + 2);
3002                   bfd_put_16 (abfd, (bfd_vma) sym_num, p + 3);
3003                   p = try_prev_fixup (abfd, &subspace_reloc_size,
3004                                       p, 5, reloc_queue);
3005                   break;
3006
3007                 case R_CODE_EXPR:
3008                 case R_DATA_EXPR:
3009                   /* The only time we generate R_COMP1, R_COMP2 and
3010                      R_CODE_EXPR relocs is for the difference of two
3011                      symbols.  Hence we can cheat here.  */
3012                   bfd_put_8 (abfd, bfd_reloc->howto->type, p);
3013                   subspace_reloc_size += 1;
3014                   p += 1;
3015                   break;
3016
3017                 /* Put a "R_RESERVED" relocation in the stream if
3018                    we hit something we do not understand.  The linker
3019                    will complain loudly if this ever happens.  */
3020                 default:
3021                   bfd_put_8 (abfd, 0xff, p);
3022                   subspace_reloc_size += 1;
3023                   p += 1;
3024                   break;
3025                 }
3026             }
3027
3028           /* Last BFD relocation for a subspace has been processed.
3029              Map the rest of the subspace with R_NO_RELOCATION fixups.  */
3030           p = som_reloc_skip (abfd, bfd_section_size (abfd, subsection)
3031                                       - reloc_offset,
3032                               p, &subspace_reloc_size, reloc_queue);
3033
3034           /* Scribble out the relocations.  */
3035           amt = p - tmp_space;
3036           if (bfd_bwrite ((PTR) tmp_space, amt, abfd) != amt)
3037             return false;
3038           p = tmp_space;
3039
3040           total_reloc_size += subspace_reloc_size;
3041           som_section_data (subsection)->subspace_dict->fixup_request_quantity
3042             = subspace_reloc_size;
3043         }
3044       section = section->next;
3045     }
3046   *total_reloc_sizep = total_reloc_size;
3047   return true;
3048 }
3049
3050 /* Write out the space/subspace string table.  */
3051
3052 static boolean
3053 som_write_space_strings (abfd, current_offset, string_sizep)
3054      bfd *abfd;
3055      unsigned long current_offset;
3056      unsigned int *string_sizep;
3057 {
3058   /* Chunk of memory that we can use as buffer space, then throw
3059      away.  */
3060   size_t tmp_space_size = SOM_TMP_BUFSIZE;
3061   unsigned char *tmp_space = alloca (tmp_space_size);
3062   unsigned char *p = tmp_space;
3063   unsigned int strings_size = 0;
3064   asection *section;
3065   bfd_size_type amt;
3066
3067   /* Seek to the start of the space strings in preparation for writing
3068      them out.  */
3069   if (bfd_seek (abfd, (file_ptr) current_offset, SEEK_SET) != 0)
3070     return false;
3071
3072   /* Walk through all the spaces and subspaces (order is not important)
3073      building up and writing string table entries for their names.  */
3074   for (section = abfd->sections; section != NULL; section = section->next)
3075     {
3076       size_t length;
3077
3078       /* Only work with space/subspaces; avoid any other sections
3079          which might have been made (.text for example).  */
3080       if (!som_is_space (section) && !som_is_subspace (section))
3081         continue;
3082
3083       /* Get the length of the space/subspace name.  */
3084       length = strlen (section->name);
3085
3086       /* If there is not enough room for the next entry, then dump the
3087          current buffer contents now and maybe allocate a larger
3088          buffer.  Each entry will take 4 bytes to hold the string
3089          length + the string itself + null terminator.  */
3090       if (p - tmp_space + 5 + length > tmp_space_size)
3091         {
3092           /* Flush buffer before refilling or reallocating.  */
3093           amt = p - tmp_space;
3094           if (bfd_bwrite ((PTR) &tmp_space[0], amt, abfd) != amt)
3095             return false;
3096
3097           /* Reallocate if now empty buffer still too small.  */
3098           if (5 + length > tmp_space_size)
3099             {
3100               /* Ensure a minimum growth factor to avoid O(n**2) space
3101                  consumption for n strings.  The optimal minimum
3102                  factor seems to be 2, as no other value can guarantee
3103                  wasting less then 50% space.  (Note that we cannot
3104                  deallocate space allocated by `alloca' without
3105                  returning from this function.)  The same technique is
3106                  used a few more times below when a buffer is
3107                  reallocated.  */
3108               tmp_space_size = MAX (2 * tmp_space_size, 5 + length);
3109               tmp_space = alloca (tmp_space_size);
3110             }
3111
3112           /* Reset to beginning of the (possibly new) buffer space.  */
3113           p = tmp_space;
3114         }
3115
3116       /* First element in a string table entry is the length of the
3117          string.  Alignment issues are already handled.  */
3118       bfd_put_32 (abfd, (bfd_vma) length, p);
3119       p += 4;
3120       strings_size += 4;
3121
3122       /* Record the index in the space/subspace records.  */
3123       if (som_is_space (section))
3124         som_section_data (section)->space_dict->name.n_strx = strings_size;
3125       else
3126         som_section_data (section)->subspace_dict->name.n_strx = strings_size;
3127
3128       /* Next comes the string itself + a null terminator.  */
3129       strcpy (p, section->name);
3130       p += length + 1;
3131       strings_size += length + 1;
3132
3133       /* Always align up to the next word boundary.  */
3134       while (strings_size % 4)
3135         {
3136           bfd_put_8 (abfd, 0, p);
3137           p++;
3138           strings_size++;
3139         }
3140     }
3141
3142   /* Done with the space/subspace strings.  Write out any information
3143      contained in a partial block.  */
3144   amt = p - tmp_space;
3145   if (bfd_bwrite ((PTR) &tmp_space[0], amt, abfd) != amt)
3146     return false;
3147   *string_sizep = strings_size;
3148   return true;
3149 }
3150
3151 /* Write out the symbol string table.  */
3152
3153 static boolean
3154 som_write_symbol_strings (abfd, current_offset, syms, num_syms, string_sizep,
3155                           compilation_unit)
3156      bfd *abfd;
3157      unsigned long current_offset;
3158      asymbol **syms;
3159      unsigned int num_syms;
3160      unsigned int *string_sizep;
3161      COMPUNIT *compilation_unit;
3162 {
3163   unsigned int i;
3164
3165   /* Chunk of memory that we can use as buffer space, then throw
3166      away.  */
3167   size_t tmp_space_size = SOM_TMP_BUFSIZE;
3168   unsigned char *tmp_space = alloca (tmp_space_size);
3169   unsigned char *p = tmp_space;
3170
3171   unsigned int strings_size = 0;
3172   unsigned char *comp[4];
3173   bfd_size_type amt;
3174
3175   /* This gets a bit gruesome because of the compilation unit.  The
3176      strings within the compilation unit are part of the symbol
3177      strings, but don't have symbol_dictionary entries.  So, manually
3178      write them and update the compliation unit header.  On input, the
3179      compilation unit header contains local copies of the strings.
3180      Move them aside.  */
3181   if (compilation_unit)
3182     {
3183       comp[0] = compilation_unit->name.n_name;
3184       comp[1] = compilation_unit->language_name.n_name;
3185       comp[2] = compilation_unit->product_id.n_name;
3186       comp[3] = compilation_unit->version_id.n_name;
3187     }
3188
3189   /* Seek to the start of the space strings in preparation for writing
3190      them out.  */
3191   if (bfd_seek (abfd, (file_ptr) current_offset, SEEK_SET) != 0)
3192     return false;
3193
3194   if (compilation_unit)
3195     {
3196       for (i = 0; i < 4; i++)
3197         {
3198           size_t length = strlen (comp[i]);
3199
3200           /* If there is not enough room for the next entry, then dump
3201              the current buffer contents now and maybe allocate a
3202              larger buffer.  */
3203           if (p - tmp_space + 5 + length > tmp_space_size)
3204             {
3205               /* Flush buffer before refilling or reallocating.  */
3206               amt = p - tmp_space;
3207               if (bfd_bwrite ((PTR) &tmp_space[0], amt, abfd) != amt)
3208                 return false;
3209
3210               /* Reallocate if now empty buffer still too small.  */
3211               if (5 + length > tmp_space_size)
3212                 {
3213                   /* See alloca above for discussion of new size.  */
3214                   tmp_space_size = MAX (2 * tmp_space_size, 5 + length);
3215                   tmp_space = alloca (tmp_space_size);
3216                 }
3217
3218               /* Reset to beginning of the (possibly new) buffer
3219                  space.  */
3220               p = tmp_space;
3221             }
3222
3223           /* First element in a string table entry is the length of
3224              the string.  This must always be 4 byte aligned.  This is
3225              also an appropriate time to fill in the string index
3226              field in the symbol table entry.  */
3227           bfd_put_32 (abfd, (bfd_vma) length, p);
3228           strings_size += 4;
3229           p += 4;
3230
3231           /* Next comes the string itself + a null terminator.  */
3232           strcpy (p, comp[i]);
3233
3234           switch (i)
3235             {
3236             case 0:
3237               obj_som_compilation_unit (abfd)->name.n_strx = strings_size;
3238               break;
3239             case 1:
3240               obj_som_compilation_unit (abfd)->language_name.n_strx =
3241                 strings_size;
3242               break;
3243             case 2:
3244               obj_som_compilation_unit (abfd)->product_id.n_strx =
3245                 strings_size;
3246               break;
3247             case 3:
3248               obj_som_compilation_unit (abfd)->version_id.n_strx =
3249                 strings_size;
3250               break;
3251             }
3252
3253           p += length + 1;
3254           strings_size += length + 1;
3255
3256           /* Always align up to the next word boundary.  */
3257           while (strings_size % 4)
3258             {
3259               bfd_put_8 (abfd, 0, p);
3260               strings_size++;
3261               p++;
3262             }
3263         }
3264     }
3265
3266   for (i = 0; i < num_syms; i++)
3267     {
3268       size_t length = strlen (syms[i]->name);
3269
3270       /* If there is not enough room for the next entry, then dump the
3271          current buffer contents now and maybe allocate a larger buffer.  */
3272      if (p - tmp_space + 5 + length > tmp_space_size)
3273         {
3274           /* Flush buffer before refilling or reallocating.  */
3275           amt = p - tmp_space;
3276           if (bfd_bwrite ((PTR) &tmp_space[0], amt, abfd) != amt)
3277             return false;
3278
3279           /* Reallocate if now empty buffer still too small.  */
3280           if (5 + length > tmp_space_size)
3281             {
3282               /* See alloca above for discussion of new size.  */
3283               tmp_space_size = MAX (2 * tmp_space_size, 5 + length);
3284               tmp_space = alloca (tmp_space_size);
3285             }
3286
3287           /* Reset to beginning of the (possibly new) buffer space.  */
3288           p = tmp_space;
3289         }
3290
3291       /* First element in a string table entry is the length of the
3292          string.  This must always be 4 byte aligned.  This is also
3293          an appropriate time to fill in the string index field in the
3294          symbol table entry.  */
3295       bfd_put_32 (abfd, (bfd_vma) length, p);
3296       strings_size += 4;
3297       p += 4;
3298
3299       /* Next comes the string itself + a null terminator.  */
3300       strcpy (p, syms[i]->name);
3301
3302       som_symbol_data (syms[i])->stringtab_offset = strings_size;
3303       p += length + 1;
3304       strings_size += length + 1;
3305
3306       /* Always align up to the next word boundary.  */
3307       while (strings_size % 4)
3308         {
3309           bfd_put_8 (abfd, 0, p);
3310           strings_size++;
3311           p++;
3312         }
3313     }
3314
3315   /* Scribble out any partial block.  */
3316   amt = p - tmp_space;
3317   if (bfd_bwrite ((PTR) &tmp_space[0], amt, abfd) != amt)
3318     return false;
3319
3320   *string_sizep = strings_size;
3321   return true;
3322 }
3323
3324 /* Compute variable information to be placed in the SOM headers,
3325    space/subspace dictionaries, relocation streams, etc.  Begin
3326    writing parts of the object file.  */
3327
3328 static boolean
3329 som_begin_writing (abfd)
3330      bfd *abfd;
3331 {
3332   unsigned long current_offset = 0;
3333   int strings_size = 0;
3334   unsigned long num_spaces, num_subspaces, i;
3335   asection *section;
3336   unsigned int total_subspaces = 0;
3337   struct som_exec_auxhdr *exec_header = NULL;
3338
3339   /* The file header will always be first in an object file,
3340      everything else can be in random locations.  To keep things
3341      "simple" BFD will lay out the object file in the manner suggested
3342      by the PRO ABI for PA-RISC Systems.  */
3343
3344   /* Before any output can really begin offsets for all the major
3345      portions of the object file must be computed.  So, starting
3346      with the initial file header compute (and sometimes write)
3347      each portion of the object file.  */
3348
3349   /* Make room for the file header, it's contents are not complete
3350      yet, so it can not be written at this time.  */
3351   current_offset += sizeof (struct header);
3352
3353   /* Any auxiliary headers will follow the file header.  Right now
3354      we support only the copyright and version headers.  */
3355   obj_som_file_hdr (abfd)->aux_header_location = current_offset;
3356   obj_som_file_hdr (abfd)->aux_header_size = 0;
3357   if (abfd->flags & (EXEC_P | DYNAMIC))
3358     {
3359       /* Parts of the exec header will be filled in later, so
3360          delay writing the header itself.  Fill in the defaults,
3361          and write it later.  */
3362       current_offset += sizeof (struct som_exec_auxhdr);
3363       obj_som_file_hdr (abfd)->aux_header_size
3364         += sizeof (struct som_exec_auxhdr);
3365       exec_header = obj_som_exec_hdr (abfd);
3366       exec_header->som_auxhdr.type = EXEC_AUX_ID;
3367       exec_header->som_auxhdr.length = 40;
3368     }
3369   if (obj_som_version_hdr (abfd) != NULL)
3370     {
3371       bfd_size_type len;
3372
3373       if (bfd_seek (abfd, (file_ptr) current_offset, SEEK_SET) != 0)
3374         return false;
3375
3376       /* Write the aux_id structure and the string length.  */
3377       len = sizeof (struct aux_id) + sizeof (unsigned int);
3378       obj_som_file_hdr (abfd)->aux_header_size += len;
3379       current_offset += len;
3380       if (bfd_bwrite ((PTR) obj_som_version_hdr (abfd), len, abfd) != len)
3381         return false;
3382
3383       /* Write the version string.  */
3384       len = obj_som_version_hdr (abfd)->header_id.length - sizeof (int);
3385       obj_som_file_hdr (abfd)->aux_header_size += len;
3386       current_offset += len;
3387       if (bfd_bwrite ((PTR) obj_som_version_hdr (abfd)->user_string, len, abfd)
3388           != len)
3389         return false;
3390     }
3391
3392   if (obj_som_copyright_hdr (abfd) != NULL)
3393     {
3394       bfd_size_type len;
3395
3396       if (bfd_seek (abfd, (file_ptr) current_offset, SEEK_SET) != 0)
3397         return false;
3398
3399       /* Write the aux_id structure and the string length.  */
3400       len = sizeof (struct aux_id) + sizeof (unsigned int);
3401       obj_som_file_hdr (abfd)->aux_header_size += len;
3402       current_offset += len;
3403       if (bfd_bwrite ((PTR) obj_som_copyright_hdr (abfd), len, abfd) != len)
3404         return false;
3405
3406       /* Write the copyright string.  */
3407       len = obj_som_copyright_hdr (abfd)->header_id.length - sizeof (int);
3408       obj_som_file_hdr (abfd)->aux_header_size += len;
3409       current_offset += len;
3410       if (bfd_bwrite ((PTR) obj_som_copyright_hdr (abfd)->copyright, len, abfd)
3411           != len)
3412         return false;
3413     }
3414
3415   /* Next comes the initialization pointers; we have no initialization
3416      pointers, so current offset does not change.  */
3417   obj_som_file_hdr (abfd)->init_array_location = current_offset;
3418   obj_som_file_hdr (abfd)->init_array_total = 0;
3419
3420   /* Next are the space records.  These are fixed length records.
3421
3422      Count the number of spaces to determine how much room is needed
3423      in the object file for the space records.
3424
3425      The names of the spaces are stored in a separate string table,
3426      and the index for each space into the string table is computed
3427      below.  Therefore, it is not possible to write the space headers
3428      at this time.  */
3429   num_spaces = som_count_spaces (abfd);
3430   obj_som_file_hdr (abfd)->space_location = current_offset;
3431   obj_som_file_hdr (abfd)->space_total = num_spaces;
3432   current_offset += num_spaces * sizeof (struct space_dictionary_record);
3433
3434   /* Next are the subspace records.  These are fixed length records.
3435
3436      Count the number of subspaes to determine how much room is needed
3437      in the object file for the subspace records.
3438
3439      A variety if fields in the subspace record are still unknown at
3440      this time (index into string table, fixup stream location/size, etc).  */
3441   num_subspaces = som_count_subspaces (abfd);
3442   obj_som_file_hdr (abfd)->subspace_location = current_offset;
3443   obj_som_file_hdr (abfd)->subspace_total = num_subspaces;
3444   current_offset += num_subspaces * sizeof (struct subspace_dictionary_record);
3445
3446   /* Next is the string table for the space/subspace names.  We will
3447      build and write the string table on the fly.  At the same time
3448      we will fill in the space/subspace name index fields.  */
3449
3450   /* The string table needs to be aligned on a word boundary.  */
3451   if (current_offset % 4)
3452     current_offset += (4 - (current_offset % 4));
3453
3454   /* Mark the offset of the space/subspace string table in the
3455      file header.  */
3456   obj_som_file_hdr (abfd)->space_strings_location = current_offset;
3457
3458   /* Scribble out the space strings.  */
3459   if (som_write_space_strings (abfd, current_offset, &strings_size) == false)
3460     return false;
3461
3462   /* Record total string table size in the header and update the
3463      current offset.  */
3464   obj_som_file_hdr (abfd)->space_strings_size = strings_size;
3465   current_offset += strings_size;
3466
3467   /* Next is the compilation unit.  */
3468   obj_som_file_hdr (abfd)->compiler_location = current_offset;
3469   obj_som_file_hdr (abfd)->compiler_total = 0;
3470   if (obj_som_compilation_unit (abfd))
3471     {
3472       obj_som_file_hdr (abfd)->compiler_total = 1;
3473       current_offset += COMPUNITSZ;
3474     }
3475
3476   /* Now compute the file positions for the loadable subspaces, taking
3477      care to make sure everything stays properly aligned.  */
3478
3479   section = abfd->sections;
3480   for (i = 0; i < num_spaces; i++)
3481     {
3482       asection *subsection;
3483       int first_subspace;
3484       unsigned int subspace_offset = 0;
3485
3486       /* Find a space.  */
3487       while (!som_is_space (section))
3488         section = section->next;
3489
3490       first_subspace = 1;
3491       /* Now look for all its subspaces.  */
3492       for (subsection = abfd->sections;
3493            subsection != NULL;
3494            subsection = subsection->next)
3495         {
3496
3497           if (!som_is_subspace (subsection)
3498               || !som_is_container (section, subsection)
3499               || (subsection->flags & SEC_ALLOC) == 0)
3500             continue;
3501
3502           /* If this is the first subspace in the space, and we are
3503              building an executable, then take care to make sure all
3504              the alignments are correct and update the exec header.  */
3505           if (first_subspace
3506               && (abfd->flags & (EXEC_P | DYNAMIC)))
3507             {
3508               /* Demand paged executables have each space aligned to a
3509                  page boundary.  Sharable executables (write-protected
3510                  text) have just the private (aka data & bss) space aligned
3511                  to a page boundary.  Ugh.  Not true for HPUX.
3512
3513                  The HPUX kernel requires the text to always be page aligned
3514                  within the file regardless of the executable's type.  */
3515               if (abfd->flags & (D_PAGED | DYNAMIC)
3516                   || (subsection->flags & SEC_CODE)
3517                   || ((abfd->flags & WP_TEXT)
3518                       && (subsection->flags & SEC_DATA)))
3519                 current_offset = SOM_ALIGN (current_offset, PA_PAGESIZE);
3520
3521               /* Update the exec header.  */
3522               if (subsection->flags & SEC_CODE && exec_header->exec_tfile == 0)
3523                 {
3524                   exec_header->exec_tmem = section->vma;
3525                   exec_header->exec_tfile = current_offset;
3526                 }
3527               if (subsection->flags & SEC_DATA && exec_header->exec_dfile == 0)
3528                 {
3529                   exec_header->exec_dmem = section->vma;
3530                   exec_header->exec_dfile = current_offset;
3531                 }
3532
3533               /* Keep track of exactly where we are within a particular
3534                  space.  This is necessary as the braindamaged HPUX
3535                  loader will create holes between subspaces *and*
3536                  subspace alignments are *NOT* preserved.  What a crock.  */
3537               subspace_offset = subsection->vma;
3538
3539               /* Only do this for the first subspace within each space.  */
3540               first_subspace = 0;
3541             }
3542           else if (abfd->flags & (EXEC_P | DYNAMIC))
3543             {
3544               /* The braindamaged HPUX loader may have created a hole
3545                  between two subspaces.  It is *not* sufficient to use
3546                  the alignment specifications within the subspaces to
3547                  account for these holes -- I've run into at least one
3548                  case where the loader left one code subspace unaligned
3549                  in a final executable.
3550
3551                  To combat this we keep a current offset within each space,
3552                  and use the subspace vma fields to detect and preserve
3553                  holes.  What a crock!
3554
3555                  ps.  This is not necessary for unloadable space/subspaces.  */
3556               current_offset += subsection->vma - subspace_offset;
3557               if (subsection->flags & SEC_CODE)
3558                 exec_header->exec_tsize += subsection->vma - subspace_offset;
3559               else
3560                 exec_header->exec_dsize += subsection->vma - subspace_offset;
3561               subspace_offset += subsection->vma - subspace_offset;
3562             }
3563
3564           subsection->target_index = total_subspaces++;
3565           /* This is real data to be loaded from the file.  */
3566           if (subsection->flags & SEC_LOAD)
3567             {
3568               /* Update the size of the code & data.  */
3569               if (abfd->flags & (EXEC_P | DYNAMIC)
3570                   && subsection->flags & SEC_CODE)
3571                 exec_header->exec_tsize += subsection->_cooked_size;
3572               else if (abfd->flags & (EXEC_P | DYNAMIC)
3573                        && subsection->flags & SEC_DATA)
3574                 exec_header->exec_dsize += subsection->_cooked_size;
3575               som_section_data (subsection)->subspace_dict->file_loc_init_value
3576                 = current_offset;
3577               subsection->filepos = current_offset;
3578               current_offset += bfd_section_size (abfd, subsection);
3579               subspace_offset += bfd_section_size (abfd, subsection);
3580             }
3581           /* Looks like uninitialized data.  */
3582           else
3583             {
3584               /* Update the size of the bss section.  */
3585               if (abfd->flags & (EXEC_P | DYNAMIC))
3586                 exec_header->exec_bsize += subsection->_cooked_size;
3587
3588               som_section_data (subsection)->subspace_dict->file_loc_init_value
3589                 = 0;
3590               som_section_data (subsection)->subspace_dict->
3591                 initialization_length = 0;
3592             }
3593         }
3594       /* Goto the next section.  */
3595       section = section->next;
3596     }
3597
3598   /* Finally compute the file positions for unloadable subspaces.
3599      If building an executable, start the unloadable stuff on its
3600      own page.  */
3601
3602   if (abfd->flags & (EXEC_P | DYNAMIC))
3603     current_offset = SOM_ALIGN (current_offset, PA_PAGESIZE);
3604
3605   obj_som_file_hdr (abfd)->unloadable_sp_location = current_offset;
3606   section = abfd->sections;
3607   for (i = 0; i < num_spaces; i++)
3608     {
3609       asection *subsection;
3610
3611       /* Find a space.  */
3612       while (!som_is_space (section))
3613         section = section->next;
3614
3615       if (abfd->flags & (EXEC_P | DYNAMIC))
3616         current_offset = SOM_ALIGN (current_offset, PA_PAGESIZE);
3617
3618       /* Now look for all its subspaces.  */
3619       for (subsection = abfd->sections;
3620            subsection != NULL;
3621            subsection = subsection->next)
3622         {
3623
3624           if (!som_is_subspace (subsection)
3625               || !som_is_container (section, subsection)
3626               || (subsection->flags & SEC_ALLOC) != 0)
3627             continue;
3628
3629           subsection->target_index = total_subspaces++;
3630           /* This is real data to be loaded from the file.  */
3631           if ((subsection->flags & SEC_LOAD) == 0)
3632             {
3633               som_section_data (subsection)->subspace_dict->file_loc_init_value
3634                 = current_offset;
3635               subsection->filepos = current_offset;
3636               current_offset += bfd_section_size (abfd, subsection);
3637             }
3638           /* Looks like uninitialized data.  */
3639           else
3640             {
3641               som_section_data (subsection)->subspace_dict->file_loc_init_value
3642                 = 0;
3643               som_section_data (subsection)->subspace_dict->
3644                 initialization_length = bfd_section_size (abfd, subsection);
3645             }
3646         }
3647       /* Goto the next section.  */
3648       section = section->next;
3649     }
3650
3651   /* If building an executable, then make sure to seek to and write
3652      one byte at the end of the file to make sure any necessary
3653      zeros are filled in.  Ugh.  */
3654   if (abfd->flags & (EXEC_P | DYNAMIC))
3655     current_offset = SOM_ALIGN (current_offset, PA_PAGESIZE);
3656   if (bfd_seek (abfd, (file_ptr) current_offset - 1, SEEK_SET) != 0)
3657     return false;
3658   if (bfd_bwrite ((PTR) "", (bfd_size_type) 1, abfd) != 1)
3659     return false;
3660
3661   obj_som_file_hdr (abfd)->unloadable_sp_size
3662     = current_offset - obj_som_file_hdr (abfd)->unloadable_sp_location;
3663
3664   /* Loader fixups are not supported in any way shape or form.  */
3665   obj_som_file_hdr (abfd)->loader_fixup_location = 0;
3666   obj_som_file_hdr (abfd)->loader_fixup_total = 0;
3667
3668   /* Done.  Store the total size of the SOM so far.  */
3669   obj_som_file_hdr (abfd)->som_length = current_offset;
3670
3671   return true;
3672 }
3673
3674 /* Finally, scribble out the various headers to the disk.  */
3675
3676 static boolean
3677 som_finish_writing (abfd)
3678      bfd *abfd;
3679 {
3680   int num_spaces = som_count_spaces (abfd);
3681   asymbol **syms = bfd_get_outsymbols (abfd);
3682   int i, num_syms, strings_size;
3683   int subspace_index = 0;
3684   file_ptr location;
3685   asection *section;
3686   unsigned long current_offset;
3687   unsigned int total_reloc_size;
3688   bfd_size_type amt;
3689
3690   /* We must set up the version identifier here as objcopy/strip copy
3691      private BFD data too late for us to handle this in som_begin_writing.  */
3692   if (obj_som_exec_data (abfd)
3693       && obj_som_exec_data (abfd)->version_id)
3694     obj_som_file_hdr (abfd)->version_id = obj_som_exec_data (abfd)->version_id;
3695   else
3696     obj_som_file_hdr (abfd)->version_id = NEW_VERSION_ID;
3697
3698   /* Next is the symbol table.  These are fixed length records.
3699
3700      Count the number of symbols to determine how much room is needed
3701      in the object file for the symbol table.
3702
3703      The names of the symbols are stored in a separate string table,
3704      and the index for each symbol name into the string table is computed
3705      below.  Therefore, it is not possible to write the symbol table
3706      at this time.
3707
3708      These used to be output before the subspace contents, but they
3709      were moved here to work around a stupid bug in the hpux linker
3710      (fixed in hpux10).  */
3711   current_offset = obj_som_file_hdr (abfd)->som_length;
3712
3713   /* Make sure we're on a word boundary.  */
3714   if (current_offset % 4)
3715     current_offset += (4 - (current_offset % 4));
3716
3717   num_syms = bfd_get_symcount (abfd);
3718   obj_som_file_hdr (abfd)->symbol_location = current_offset;
3719   obj_som_file_hdr (abfd)->symbol_total = num_syms;
3720   current_offset += num_syms * sizeof (struct symbol_dictionary_record);
3721
3722   /* Next are the symbol strings.
3723      Align them to a word boundary.  */
3724   if (current_offset % 4)
3725     current_offset += (4 - (current_offset % 4));
3726   obj_som_file_hdr (abfd)->symbol_strings_location = current_offset;
3727
3728   /* Scribble out the symbol strings.  */
3729   if (som_write_symbol_strings (abfd, current_offset, syms,
3730                                 num_syms, &strings_size,
3731                                 obj_som_compilation_unit (abfd))
3732       == false)
3733     return false;
3734
3735   /* Record total string table size in header and update the
3736      current offset.  */
3737   obj_som_file_hdr (abfd)->symbol_strings_size = strings_size;
3738   current_offset += strings_size;
3739
3740   /* Do prep work before handling fixups.  */
3741   som_prep_for_fixups (abfd,
3742                        bfd_get_outsymbols (abfd),
3743                        bfd_get_symcount (abfd));
3744
3745   /* At the end of the file is the fixup stream which starts on a
3746      word boundary.  */
3747   if (current_offset % 4)
3748     current_offset += (4 - (current_offset % 4));
3749   obj_som_file_hdr (abfd)->fixup_request_location = current_offset;
3750
3751   /* Write the fixups and update fields in subspace headers which
3752      relate to the fixup stream.  */
3753   if (som_write_fixups (abfd, current_offset, &total_reloc_size) == false)
3754     return false;
3755
3756   /* Record the total size of the fixup stream in the file header.  */
3757   obj_som_file_hdr (abfd)->fixup_request_total = total_reloc_size;
3758
3759   /* Done.  Store the total size of the SOM.  */
3760   obj_som_file_hdr (abfd)->som_length = current_offset + total_reloc_size;
3761
3762   /* Now that the symbol table information is complete, build and
3763      write the symbol table.  */
3764   if (som_build_and_write_symbol_table (abfd) == false)
3765     return false;
3766
3767   /* Subspaces are written first so that we can set up information
3768      about them in their containing spaces as the subspace is written.  */
3769
3770   /* Seek to the start of the subspace dictionary records.  */
3771   location = obj_som_file_hdr (abfd)->subspace_location;
3772   if (bfd_seek (abfd, location, SEEK_SET) != 0)
3773     return false;
3774
3775   section = abfd->sections;
3776   /* Now for each loadable space write out records for its subspaces.  */
3777   for (i = 0; i < num_spaces; i++)
3778     {
3779       asection *subsection;
3780
3781       /* Find a space.  */
3782       while (!som_is_space (section))
3783         section = section->next;
3784
3785       /* Now look for all its subspaces.  */
3786       for (subsection = abfd->sections;
3787            subsection != NULL;
3788            subsection = subsection->next)
3789         {
3790
3791           /* Skip any section which does not correspond to a space
3792              or subspace.  Or does not have SEC_ALLOC set (and therefore
3793              has no real bits on the disk).  */
3794           if (!som_is_subspace (subsection)
3795               || !som_is_container (section, subsection)
3796               || (subsection->flags & SEC_ALLOC) == 0)
3797             continue;
3798
3799           /* If this is the first subspace for this space, then save
3800              the index of the subspace in its containing space.  Also
3801              set "is_loadable" in the containing space.  */
3802
3803           if (som_section_data (section)->space_dict->subspace_quantity == 0)
3804             {
3805               som_section_data (section)->space_dict->is_loadable = 1;
3806               som_section_data (section)->space_dict->subspace_index
3807                 = subspace_index;
3808             }
3809
3810           /* Increment the number of subspaces seen and the number of
3811              subspaces contained within the current space.  */
3812           subspace_index++;
3813           som_section_data (section)->space_dict->subspace_quantity++;
3814
3815           /* Mark the index of the current space within the subspace's
3816              dictionary record.  */
3817           som_section_data (subsection)->subspace_dict->space_index = i;
3818
3819           /* Dump the current subspace header.  */
3820           amt = sizeof (struct subspace_dictionary_record);
3821           if (bfd_bwrite ((PTR) som_section_data (subsection)->subspace_dict,
3822                          amt, abfd) != amt)
3823             return false;
3824         }
3825       /* Goto the next section.  */
3826       section = section->next;
3827     }
3828
3829   /* Now repeat the process for unloadable subspaces.  */
3830   section = abfd->sections;
3831   /* Now for each space write out records for its subspaces.  */
3832   for (i = 0; i < num_spaces; i++)
3833     {
3834       asection *subsection;
3835
3836       /* Find a space.  */
3837       while (!som_is_space (section))
3838         section = section->next;
3839
3840       /* Now look for all its subspaces.  */
3841       for (subsection = abfd->sections;
3842            subsection != NULL;
3843            subsection = subsection->next)
3844         {
3845
3846           /* Skip any section which does not correspond to a space or
3847              subspace, or which SEC_ALLOC set (and therefore handled
3848              in the loadable spaces/subspaces code above).  */
3849
3850           if (!som_is_subspace (subsection)
3851               || !som_is_container (section, subsection)
3852               || (subsection->flags & SEC_ALLOC) != 0)
3853             continue;
3854
3855           /* If this is the first subspace for this space, then save
3856              the index of the subspace in its containing space.  Clear
3857              "is_loadable".  */
3858
3859           if (som_section_data (section)->space_dict->subspace_quantity == 0)
3860             {
3861               som_section_data (section)->space_dict->is_loadable = 0;
3862               som_section_data (section)->space_dict->subspace_index
3863                 = subspace_index;
3864             }
3865
3866           /* Increment the number of subspaces seen and the number of
3867              subspaces contained within the current space.  */
3868           som_section_data (section)->space_dict->subspace_quantity++;
3869           subspace_index++;
3870
3871           /* Mark the index of the current space within the subspace's
3872              dictionary record.  */
3873           som_section_data (subsection)->subspace_dict->space_index = i;
3874
3875           /* Dump this subspace header.  */
3876           amt = sizeof (struct subspace_dictionary_record);
3877           if (bfd_bwrite ((PTR) som_section_data (subsection)->subspace_dict,
3878                          amt, abfd) != amt)
3879             return false;
3880         }
3881       /* Goto the next section.  */
3882       section = section->next;
3883     }
3884
3885   /* All the subspace dictiondary records are written, and all the
3886      fields are set up in the space dictionary records.
3887
3888      Seek to the right location and start writing the space
3889      dictionary records.  */
3890   location = obj_som_file_hdr (abfd)->space_location;
3891   if (bfd_seek (abfd, location, SEEK_SET) != 0)
3892     return false;
3893
3894   section = abfd->sections;
3895   for (i = 0; i < num_spaces; i++)
3896     {
3897       /* Find a space.  */
3898       while (!som_is_space (section))
3899         section = section->next;
3900
3901       /* Dump its header.  */
3902       amt = sizeof (struct space_dictionary_record);
3903       if (bfd_bwrite ((PTR) som_section_data (section)->space_dict,
3904                      amt, abfd) != amt)
3905         return false;
3906
3907       /* Goto the next section.  */
3908       section = section->next;
3909     }
3910
3911   /* Write the compilation unit record if there is one.  */
3912   if (obj_som_compilation_unit (abfd))
3913     {
3914       location = obj_som_file_hdr (abfd)->compiler_location;
3915       if (bfd_seek (abfd, location, SEEK_SET) != 0)
3916         return false;
3917
3918       amt = COMPUNITSZ;
3919       if (bfd_bwrite ((PTR) obj_som_compilation_unit (abfd), amt, abfd) != amt)
3920         return false;
3921     }
3922
3923   /* Setting of the system_id has to happen very late now that copying of
3924      BFD private data happens *after* section contents are set.  */
3925   if (abfd->flags & (EXEC_P | DYNAMIC))
3926     obj_som_file_hdr (abfd)->system_id = obj_som_exec_data (abfd)->system_id;
3927   else if (bfd_get_mach (abfd) == pa20)
3928     obj_som_file_hdr (abfd)->system_id = CPU_PA_RISC2_0;
3929   else if (bfd_get_mach (abfd) == pa11)
3930     obj_som_file_hdr (abfd)->system_id = CPU_PA_RISC1_1;
3931   else
3932     obj_som_file_hdr (abfd)->system_id = CPU_PA_RISC1_0;
3933
3934   /* Compute the checksum for the file header just before writing
3935      the header to disk.  */
3936   obj_som_file_hdr (abfd)->checksum = som_compute_checksum (abfd);
3937
3938   /* Only thing left to do is write out the file header.  It is always
3939      at location zero.  Seek there and write it.  */
3940   if (bfd_seek (abfd, (file_ptr) 0, SEEK_SET) != 0)
3941     return false;
3942   amt = sizeof (struct header);
3943   if (bfd_bwrite ((PTR) obj_som_file_hdr (abfd), amt, abfd) != amt)
3944     return false;
3945
3946   /* Now write the exec header.  */
3947   if (abfd->flags & (EXEC_P | DYNAMIC))
3948     {
3949       long tmp, som_length;
3950       struct som_exec_auxhdr *exec_header;
3951
3952       exec_header = obj_som_exec_hdr (abfd);
3953       exec_header->exec_entry = bfd_get_start_address (abfd);
3954       exec_header->exec_flags = obj_som_exec_data (abfd)->exec_flags;
3955
3956       /* Oh joys.  Ram some of the BSS data into the DATA section
3957          to be compatable with how the hp linker makes objects
3958          (saves memory space).  */
3959       tmp = exec_header->exec_dsize;
3960       tmp = SOM_ALIGN (tmp, PA_PAGESIZE);
3961       exec_header->exec_bsize -= (tmp - exec_header->exec_dsize);
3962       if (exec_header->exec_bsize < 0)
3963         exec_header->exec_bsize = 0;
3964       exec_header->exec_dsize = tmp;
3965
3966       /* Now perform some sanity checks.  The idea is to catch bogons now and
3967          inform the user, instead of silently generating a bogus file.  */
3968       som_length = obj_som_file_hdr (abfd)->som_length;
3969       if (exec_header->exec_tfile + exec_header->exec_tsize > som_length
3970           || exec_header->exec_dfile + exec_header->exec_dsize > som_length)
3971         {
3972           bfd_set_error (bfd_error_bad_value);
3973           return false;
3974         }
3975
3976       if (bfd_seek (abfd, obj_som_file_hdr (abfd)->aux_header_location,
3977                     SEEK_SET) != 0)
3978         return false;
3979
3980       amt = AUX_HDR_SIZE;
3981       if (bfd_bwrite ((PTR) exec_header, amt, abfd) != amt)
3982         return false;
3983     }
3984   return true;
3985 }
3986
3987 /* Compute and return the checksum for a SOM file header.  */
3988
3989 static unsigned long
3990 som_compute_checksum (abfd)
3991      bfd *abfd;
3992 {
3993   unsigned long checksum, count, i;
3994   unsigned long *buffer = (unsigned long *) obj_som_file_hdr (abfd);
3995
3996   checksum = 0;
3997   count = sizeof (struct header) / sizeof (unsigned long);
3998   for (i = 0; i < count; i++)
3999     checksum ^= *(buffer + i);
4000
4001   return checksum;
4002 }
4003
4004 static void
4005 som_bfd_derive_misc_symbol_info (abfd, sym, info)
4006      bfd *abfd ATTRIBUTE_UNUSED;
4007      asymbol *sym;
4008      struct som_misc_symbol_info *info;
4009 {
4010   /* Initialize.  */
4011   memset (info, 0, sizeof (struct som_misc_symbol_info));
4012
4013   /* The HP SOM linker requires detailed type information about
4014      all symbols (including undefined symbols!).  Unfortunately,
4015      the type specified in an import/export statement does not
4016      always match what the linker wants.  Severe braindamage.  */
4017
4018   /* Section symbols will not have a SOM symbol type assigned to
4019      them yet.  Assign all section symbols type ST_DATA.  */
4020   if (sym->flags & BSF_SECTION_SYM)
4021     info->symbol_type = ST_DATA;
4022   else
4023     {
4024       /* Common symbols must have scope SS_UNSAT and type
4025          ST_STORAGE or the linker will choke.  */
4026       if (bfd_is_com_section (sym->section))
4027         {
4028           info->symbol_scope = SS_UNSAT;
4029           info->symbol_type = ST_STORAGE;
4030         }
4031
4032       /* It is possible to have a symbol without an associated
4033          type.  This happens if the user imported the symbol
4034          without a type and the symbol was never defined
4035          locally.  If BSF_FUNCTION is set for this symbol, then
4036          assign it type ST_CODE (the HP linker requires undefined
4037          external functions to have type ST_CODE rather than ST_ENTRY).  */
4038       else if ((som_symbol_data (sym)->som_type == SYMBOL_TYPE_UNKNOWN
4039                 || som_symbol_data (sym)->som_type == SYMBOL_TYPE_CODE)
4040                && bfd_is_und_section (sym->section)
4041                && sym->flags & BSF_FUNCTION)
4042         info->symbol_type = ST_CODE;
4043
4044       /* Handle function symbols which were defined in this file.
4045          They should have type ST_ENTRY.  Also retrieve the argument
4046          relocation bits from the SOM backend information.  */
4047       else if (som_symbol_data (sym)->som_type == SYMBOL_TYPE_ENTRY
4048                || (som_symbol_data (sym)->som_type == SYMBOL_TYPE_CODE
4049                    && (sym->flags & BSF_FUNCTION))
4050                || (som_symbol_data (sym)->som_type == SYMBOL_TYPE_UNKNOWN
4051                    && (sym->flags & BSF_FUNCTION)))
4052         {
4053           info->symbol_type = ST_ENTRY;
4054           info->arg_reloc = som_symbol_data (sym)->tc_data.ap.hppa_arg_reloc;
4055           info->priv_level= som_symbol_data (sym)->tc_data.ap.hppa_priv_level;
4056         }
4057
4058       /* For unknown symbols set the symbol's type based on the symbol's
4059          section (ST_DATA for DATA sections, ST_CODE for CODE sections).  */
4060       else if (som_symbol_data (sym)->som_type == SYMBOL_TYPE_UNKNOWN)
4061         {
4062           if (sym->section->flags & SEC_CODE)
4063             info->symbol_type = ST_CODE;
4064           else
4065             info->symbol_type = ST_DATA;
4066         }
4067
4068       else if (som_symbol_data (sym)->som_type == SYMBOL_TYPE_UNKNOWN)
4069         info->symbol_type = ST_DATA;
4070
4071       /* From now on it's a very simple mapping.  */
4072       else if (som_symbol_data (sym)->som_type == SYMBOL_TYPE_ABSOLUTE)
4073         info->symbol_type = ST_ABSOLUTE;
4074       else if (som_symbol_data (sym)->som_type == SYMBOL_TYPE_CODE)
4075         info->symbol_type = ST_CODE;
4076       else if (som_symbol_data (sym)->som_type == SYMBOL_TYPE_DATA)
4077         info->symbol_type = ST_DATA;
4078       else if (som_symbol_data (sym)->som_type == SYMBOL_TYPE_MILLICODE)
4079         info->symbol_type = ST_MILLICODE;
4080       else if (som_symbol_data (sym)->som_type == SYMBOL_TYPE_PLABEL)
4081         info->symbol_type = ST_PLABEL;
4082       else if (som_symbol_data (sym)->som_type == SYMBOL_TYPE_PRI_PROG)
4083         info->symbol_type = ST_PRI_PROG;
4084       else if (som_symbol_data (sym)->som_type == SYMBOL_TYPE_SEC_PROG)
4085         info->symbol_type = ST_SEC_PROG;
4086     }
4087
4088   /* Now handle the symbol's scope.  Exported data which is not
4089      in the common section has scope SS_UNIVERSAL.  Note scope
4090      of common symbols was handled earlier!  */
4091   if (bfd_is_und_section (sym->section))
4092     info->symbol_scope = SS_UNSAT;
4093   else if (sym->flags & (BSF_EXPORT | BSF_WEAK)
4094            && ! bfd_is_com_section (sym->section))
4095     info->symbol_scope = SS_UNIVERSAL;
4096   /* Anything else which is not in the common section has scope
4097      SS_LOCAL.  */
4098   else if (! bfd_is_com_section (sym->section))
4099     info->symbol_scope = SS_LOCAL;
4100
4101   /* Now set the symbol_info field.  It has no real meaning
4102      for undefined or common symbols, but the HP linker will
4103      choke if it's not set to some "reasonable" value.  We
4104      use zero as a reasonable value.  */
4105   if (bfd_is_com_section (sym->section)
4106       || bfd_is_und_section (sym->section)
4107       || bfd_is_abs_section (sym->section))
4108     info->symbol_info = 0;
4109   /* For all other symbols, the symbol_info field contains the
4110      subspace index of the space this symbol is contained in.  */
4111   else
4112     info->symbol_info = sym->section->target_index;
4113
4114   /* Set the symbol's value.  */
4115   info->symbol_value = sym->value + sym->section->vma;
4116
4117   /* The secondary_def field is for weak symbols.  */
4118   if (sym->flags & BSF_WEAK)
4119     info->secondary_def = true;
4120   else
4121     info->secondary_def = false;
4122
4123 }
4124
4125 /* Build and write, in one big chunk, the entire symbol table for
4126    this BFD.  */
4127
4128 static boolean
4129 som_build_and_write_symbol_table (abfd)
4130      bfd *abfd;
4131 {
4132   unsigned int num_syms = bfd_get_symcount (abfd);
4133   file_ptr symtab_location = obj_som_file_hdr (abfd)->symbol_location;
4134   asymbol **bfd_syms = obj_som_sorted_syms (abfd);
4135   struct symbol_dictionary_record *som_symtab = NULL;
4136   unsigned int i;
4137   bfd_size_type symtab_size;
4138
4139   /* Compute total symbol table size and allocate a chunk of memory
4140      to hold the symbol table as we build it.  */
4141   symtab_size = num_syms;
4142   symtab_size *= sizeof (struct symbol_dictionary_record);
4143   som_symtab = (struct symbol_dictionary_record *) bfd_malloc (symtab_size);
4144   if (som_symtab == NULL && symtab_size != 0)
4145     goto error_return;
4146   memset (som_symtab, 0, (size_t) symtab_size);
4147
4148   /* Walk over each symbol.  */
4149   for (i = 0; i < num_syms; i++)
4150     {
4151       struct som_misc_symbol_info info;
4152
4153       /* This is really an index into the symbol strings table.
4154          By the time we get here, the index has already been
4155          computed and stored into the name field in the BFD symbol.  */
4156       som_symtab[i].name.n_strx = som_symbol_data(bfd_syms[i])->stringtab_offset;
4157
4158       /* Derive SOM information from the BFD symbol.  */
4159       som_bfd_derive_misc_symbol_info (abfd, bfd_syms[i], &info);
4160
4161       /* Now use it.  */
4162       som_symtab[i].symbol_type = info.symbol_type;
4163       som_symtab[i].symbol_scope = info.symbol_scope;
4164       som_symtab[i].arg_reloc = info.arg_reloc;
4165       som_symtab[i].symbol_info = info.symbol_info;
4166       som_symtab[i].xleast = 3;
4167       som_symtab[i].symbol_value = info.symbol_value | info.priv_level;
4168       som_symtab[i].secondary_def = info.secondary_def;
4169     }
4170
4171   /* Everything is ready, seek to the right location and
4172      scribble out the symbol table.  */
4173   if (bfd_seek (abfd, symtab_location, SEEK_SET) != 0)
4174     return false;
4175
4176   if (bfd_bwrite ((PTR) som_symtab, symtab_size, abfd) != symtab_size)
4177     goto error_return;
4178
4179   if (som_symtab != NULL)
4180     free (som_symtab);
4181   return true;
4182  error_return:
4183   if (som_symtab != NULL)
4184     free (som_symtab);
4185   return false;
4186 }
4187
4188 /* Write an object in SOM format.  */
4189
4190 static boolean
4191 som_write_object_contents (abfd)
4192      bfd *abfd;
4193 {
4194   if (abfd->output_has_begun == false)
4195     {
4196       /* Set up fixed parts of the file, space, and subspace headers.
4197          Notify the world that output has begun.  */
4198       som_prep_headers (abfd);
4199       abfd->output_has_begun = true;
4200       /* Start writing the object file.  This include all the string
4201          tables, fixup streams, and other portions of the object file.  */
4202       som_begin_writing (abfd);
4203     }
4204
4205   return (som_finish_writing (abfd));
4206 }
4207 \f
4208 /* Read and save the string table associated with the given BFD.  */
4209
4210 static boolean
4211 som_slurp_string_table (abfd)
4212      bfd *abfd;
4213 {
4214   char *stringtab;
4215   bfd_size_type amt;
4216
4217   /* Use the saved version if its available.  */
4218   if (obj_som_stringtab (abfd) != NULL)
4219     return true;
4220
4221   /* I don't think this can currently happen, and I'm not sure it should
4222      really be an error, but it's better than getting unpredictable results
4223      from the host's malloc when passed a size of zero.  */
4224   if (obj_som_stringtab_size (abfd) == 0)
4225     {
4226       bfd_set_error (bfd_error_no_symbols);
4227       return false;
4228     }
4229
4230   /* Allocate and read in the string table.  */
4231   amt = obj_som_stringtab_size (abfd);
4232   stringtab = bfd_malloc (amt);
4233   if (stringtab == NULL)
4234     return false;
4235   memset (stringtab, 0, obj_som_stringtab_size (abfd));
4236
4237   if (bfd_seek (abfd, obj_som_str_filepos (abfd), SEEK_SET) != 0)
4238     return false;
4239
4240   if (bfd_bread (stringtab, amt, abfd) != amt)
4241     return false;
4242
4243   /* Save our results and return success.  */
4244   obj_som_stringtab (abfd) = stringtab;
4245   return true;
4246 }
4247
4248 /* Return the amount of data (in bytes) required to hold the symbol
4249    table for this object.  */
4250
4251 static long
4252 som_get_symtab_upper_bound (abfd)
4253      bfd *abfd;
4254 {
4255   if (!som_slurp_symbol_table (abfd))
4256     return -1;
4257
4258   return (bfd_get_symcount (abfd) + 1) * (sizeof (asymbol *));
4259 }
4260
4261 /* Convert from a SOM subspace index to a BFD section.  */
4262
4263 static asection *
4264 bfd_section_from_som_symbol (abfd, symbol)
4265      bfd *abfd;
4266      struct symbol_dictionary_record *symbol;
4267 {
4268   asection *section;
4269
4270   /* The meaning of the symbol_info field changes for functions
4271      within executables.  So only use the quick symbol_info mapping for
4272      incomplete objects and non-function symbols in executables.  */
4273   if ((abfd->flags & (EXEC_P | DYNAMIC)) == 0
4274       || (symbol->symbol_type != ST_ENTRY
4275           && symbol->symbol_type != ST_PRI_PROG
4276           && symbol->symbol_type != ST_SEC_PROG
4277           && symbol->symbol_type != ST_MILLICODE))
4278     {
4279       unsigned int index = symbol->symbol_info;
4280       for (section = abfd->sections; section != NULL; section = section->next)
4281         if (section->target_index == index && som_is_subspace (section))
4282           return section;
4283
4284       /* Could be a symbol from an external library (such as an OMOS
4285          shared library).  Don't abort.  */
4286       return bfd_abs_section_ptr;
4287
4288     }
4289   else
4290     {
4291       unsigned int value = symbol->symbol_value;
4292
4293       /* For executables we will have to use the symbol's address and
4294          find out what section would contain that address.   Yuk.  */
4295       for (section = abfd->sections; section; section = section->next)
4296         {
4297           if (value >= section->vma
4298               && value <= section->vma + section->_cooked_size
4299               && som_is_subspace (section))
4300             return section;
4301         }
4302
4303       /* Could be a symbol from an external library (such as an OMOS
4304          shared library).  Don't abort.  */
4305       return bfd_abs_section_ptr;
4306
4307     }
4308 }
4309
4310 /* Read and save the symbol table associated with the given BFD.  */
4311
4312 static unsigned int
4313 som_slurp_symbol_table (abfd)
4314      bfd *abfd;
4315 {
4316   int symbol_count = bfd_get_symcount (abfd);
4317   int symsize = sizeof (struct symbol_dictionary_record);
4318   char *stringtab;
4319   struct symbol_dictionary_record *buf = NULL, *bufp, *endbufp;
4320   som_symbol_type *sym, *symbase;
4321   bfd_size_type amt;
4322
4323   /* Return saved value if it exists.  */
4324   if (obj_som_symtab (abfd) != NULL)
4325     goto successful_return;
4326
4327   /* Special case.  This is *not* an error.  */
4328   if (symbol_count == 0)
4329     goto successful_return;
4330
4331   if (!som_slurp_string_table (abfd))
4332     goto error_return;
4333
4334   stringtab = obj_som_stringtab (abfd);
4335
4336   amt = symbol_count;
4337   amt *= sizeof (som_symbol_type);
4338   symbase = (som_symbol_type *) bfd_malloc (amt);
4339   if (symbase == NULL)
4340     goto error_return;
4341   memset (symbase, 0, symbol_count * sizeof (som_symbol_type));
4342
4343   /* Read in the external SOM representation.  */
4344   amt = symbol_count;
4345   amt *= symsize;
4346   buf = bfd_malloc (amt);
4347   if (buf == NULL && amt != 0)
4348     goto error_return;
4349   if (bfd_seek (abfd, obj_som_sym_filepos (abfd), SEEK_SET) != 0)
4350     goto error_return;
4351   if (bfd_bread (buf, amt, abfd) != amt)
4352     goto error_return;
4353
4354   /* Iterate over all the symbols and internalize them.  */
4355   endbufp = buf + symbol_count;
4356   for (bufp = buf, sym = symbase; bufp < endbufp; ++bufp)
4357     {
4358
4359       /* I don't think we care about these.  */
4360       if (bufp->symbol_type == ST_SYM_EXT
4361           || bufp->symbol_type == ST_ARG_EXT)
4362         continue;
4363
4364       /* Set some private data we care about.  */
4365       if (bufp->symbol_type == ST_NULL)
4366         som_symbol_data (sym)->som_type = SYMBOL_TYPE_UNKNOWN;
4367       else if (bufp->symbol_type == ST_ABSOLUTE)
4368         som_symbol_data (sym)->som_type = SYMBOL_TYPE_ABSOLUTE;
4369       else if (bufp->symbol_type == ST_DATA)
4370         som_symbol_data (sym)->som_type = SYMBOL_TYPE_DATA;
4371       else if (bufp->symbol_type == ST_CODE)
4372         som_symbol_data (sym)->som_type = SYMBOL_TYPE_CODE;
4373       else if (bufp->symbol_type == ST_PRI_PROG)
4374         som_symbol_data (sym)->som_type = SYMBOL_TYPE_PRI_PROG;
4375       else if (bufp->symbol_type == ST_SEC_PROG)
4376         som_symbol_data (sym)->som_type = SYMBOL_TYPE_SEC_PROG;
4377       else if (bufp->symbol_type == ST_ENTRY)
4378         som_symbol_data (sym)->som_type = SYMBOL_TYPE_ENTRY;
4379       else if (bufp->symbol_type == ST_MILLICODE)
4380         som_symbol_data (sym)->som_type = SYMBOL_TYPE_MILLICODE;
4381       else if (bufp->symbol_type == ST_PLABEL)
4382         som_symbol_data (sym)->som_type = SYMBOL_TYPE_PLABEL;
4383       else
4384         som_symbol_data (sym)->som_type = SYMBOL_TYPE_UNKNOWN;
4385       som_symbol_data (sym)->tc_data.ap.hppa_arg_reloc = bufp->arg_reloc;
4386
4387       /* Some reasonable defaults.  */
4388       sym->symbol.the_bfd = abfd;
4389       sym->symbol.name = bufp->name.n_strx + stringtab;
4390       sym->symbol.value = bufp->symbol_value;
4391       sym->symbol.section = 0;
4392       sym->symbol.flags = 0;
4393
4394       switch (bufp->symbol_type)
4395         {
4396         case ST_ENTRY:
4397         case ST_MILLICODE:
4398           sym->symbol.flags |= BSF_FUNCTION;
4399           som_symbol_data (sym)->tc_data.ap.hppa_priv_level =
4400             sym->symbol.value & 0x3;
4401           sym->symbol.value &= ~0x3;
4402           break;
4403
4404         case ST_STUB:
4405         case ST_CODE:
4406         case ST_PRI_PROG:
4407         case ST_SEC_PROG:
4408           som_symbol_data (sym)->tc_data.ap.hppa_priv_level =
4409             sym->symbol.value & 0x3;
4410           sym->symbol.value &= ~0x3;
4411           /* If the symbol's scope is SS_UNSAT, then these are
4412              undefined function symbols.  */
4413           if (bufp->symbol_scope == SS_UNSAT)
4414             sym->symbol.flags |= BSF_FUNCTION;
4415
4416         default:
4417           break;
4418         }
4419
4420       /* Handle scoping and section information.  */
4421       switch (bufp->symbol_scope)
4422         {
4423         /* symbol_info field is undefined for SS_EXTERNAL and SS_UNSAT symbols,
4424            so the section associated with this symbol can't be known.  */
4425         case SS_EXTERNAL:
4426           if (bufp->symbol_type != ST_STORAGE)
4427             sym->symbol.section = bfd_und_section_ptr;
4428           else
4429             sym->symbol.section = bfd_com_section_ptr;
4430           sym->symbol.flags |= (BSF_EXPORT | BSF_GLOBAL);
4431           break;
4432
4433         case SS_UNSAT:
4434           if (bufp->symbol_type != ST_STORAGE)
4435             sym->symbol.section = bfd_und_section_ptr;
4436           else
4437             sym->symbol.section = bfd_com_section_ptr;
4438           break;
4439
4440         case SS_UNIVERSAL:
4441           sym->symbol.flags |= (BSF_EXPORT | BSF_GLOBAL);
4442           sym->symbol.section = bfd_section_from_som_symbol (abfd, bufp);
4443           sym->symbol.value -= sym->symbol.section->vma;
4444           break;
4445
4446 #if 0
4447         /* SS_GLOBAL and SS_LOCAL are two names for the same thing.
4448            Sound dumb?  It is.  */
4449         case SS_GLOBAL:
4450 #endif
4451         case SS_LOCAL:
4452           sym->symbol.flags |= BSF_LOCAL;
4453           sym->symbol.section = bfd_section_from_som_symbol (abfd, bufp);
4454           sym->symbol.value -= sym->symbol.section->vma;
4455           break;
4456         }
4457
4458       /* Check for a weak symbol.  */
4459       if (bufp->secondary_def)
4460         sym->symbol.flags |= BSF_WEAK;
4461
4462       /* Mark section symbols and symbols used by the debugger.
4463          Note $START$ is a magic code symbol, NOT a section symbol.  */
4464       if (sym->symbol.name[0] == '$'
4465           && sym->symbol.name[strlen (sym->symbol.name) - 1] == '$'
4466           && !strcmp (sym->symbol.name, sym->symbol.section->name))
4467         sym->symbol.flags |= BSF_SECTION_SYM;
4468       else if (!strncmp (sym->symbol.name, "L$0\002", 4))
4469         {
4470           sym->symbol.flags |= BSF_SECTION_SYM;
4471           sym->symbol.name = sym->symbol.section->name;
4472         }
4473       else if (!strncmp (sym->symbol.name, "L$0\001", 4))
4474         sym->symbol.flags |= BSF_DEBUGGING;
4475
4476       /* Note increment at bottom of loop, since we skip some symbols
4477          we can not include it as part of the for statement.  */
4478       sym++;
4479     }
4480
4481   /* We modify the symbol count to record the number of BFD symbols we
4482      created.  */
4483   bfd_get_symcount (abfd) = sym - symbase;
4484
4485   /* Save our results and return success.  */
4486   obj_som_symtab (abfd) = symbase;
4487  successful_return:
4488   if (buf != NULL)
4489     free (buf);
4490   return (true);
4491
4492  error_return:
4493   if (buf != NULL)
4494     free (buf);
4495   return false;
4496 }
4497
4498 /* Canonicalize a SOM symbol table.  Return the number of entries
4499    in the symbol table.  */
4500
4501 static long
4502 som_get_symtab (abfd, location)
4503      bfd *abfd;
4504      asymbol **location;
4505 {
4506   int i;
4507   som_symbol_type *symbase;
4508
4509   if (!som_slurp_symbol_table (abfd))
4510     return -1;
4511
4512   i = bfd_get_symcount (abfd);
4513   symbase = obj_som_symtab (abfd);
4514
4515   for (; i > 0; i--, location++, symbase++)
4516     *location = &symbase->symbol;
4517
4518   /* Final null pointer.  */
4519   *location = 0;
4520   return (bfd_get_symcount (abfd));
4521 }
4522
4523 /* Make a SOM symbol.  There is nothing special to do here.  */
4524
4525 static asymbol *
4526 som_make_empty_symbol (abfd)
4527      bfd *abfd;
4528 {
4529   bfd_size_type amt = sizeof (som_symbol_type);
4530   som_symbol_type *new = (som_symbol_type *) bfd_zalloc (abfd, amt);
4531   if (new == NULL)
4532     return 0;
4533   new->symbol.the_bfd = abfd;
4534
4535   return &new->symbol;
4536 }
4537
4538 /* Print symbol information.  */
4539
4540 static void
4541 som_print_symbol (abfd, afile, symbol, how)
4542      bfd *abfd;
4543      PTR afile;
4544      asymbol *symbol;
4545      bfd_print_symbol_type how;
4546 {
4547   FILE *file = (FILE *) afile;
4548   switch (how)
4549     {
4550     case bfd_print_symbol_name:
4551       fprintf (file, "%s", symbol->name);
4552       break;
4553     case bfd_print_symbol_more:
4554       fprintf (file, "som ");
4555       fprintf_vma (file, symbol->value);
4556       fprintf (file, " %lx", (long) symbol->flags);
4557       break;
4558     case bfd_print_symbol_all:
4559       {
4560         const char *section_name;
4561         section_name = symbol->section ? symbol->section->name : "(*none*)";
4562         bfd_print_symbol_vandf (abfd, (PTR) file, symbol);
4563         fprintf (file, " %s\t%s", section_name, symbol->name);
4564         break;
4565       }
4566     }
4567 }
4568
4569 static boolean
4570 som_bfd_is_local_label_name (abfd, name)
4571      bfd *abfd ATTRIBUTE_UNUSED;
4572      const char *name;
4573 {
4574   return (name[0] == 'L' && name[1] == '$');
4575 }
4576
4577 /* Count or process variable-length SOM fixup records.
4578
4579    To avoid code duplication we use this code both to compute the number
4580    of relocations requested by a stream, and to internalize the stream.
4581
4582    When computing the number of relocations requested by a stream the
4583    variables rptr, section, and symbols have no meaning.
4584
4585    Return the number of relocations requested by the fixup stream.  When
4586    not just counting
4587
4588    This needs at least two or three more passes to get it cleaned up.  */
4589
4590 static unsigned int
4591 som_set_reloc_info (fixup, end, internal_relocs, section, symbols, just_count)
4592      unsigned char *fixup;
4593      unsigned int end;
4594      arelent *internal_relocs;
4595      asection *section;
4596      asymbol **symbols;
4597      boolean just_count;
4598 {
4599   unsigned int op, varname, deallocate_contents = 0;
4600   unsigned char *end_fixups = &fixup[end];
4601   const struct fixup_format *fp;
4602   const char *cp;
4603   unsigned char *save_fixup;
4604   int variables[26], stack[20], c, v, count, prev_fixup, *sp, saved_unwind_bits;
4605   const int *subop;
4606   arelent *rptr = internal_relocs;
4607   unsigned int offset = 0;
4608
4609 #define var(c)          variables[(c) - 'A']
4610 #define push(v)         (*sp++ = (v))
4611 #define pop()           (*--sp)
4612 #define emptystack()    (sp == stack)
4613
4614   som_initialize_reloc_queue (reloc_queue);
4615   memset (variables, 0, sizeof (variables));
4616   memset (stack, 0, sizeof (stack));
4617   count = 0;
4618   prev_fixup = 0;
4619   saved_unwind_bits = 0;
4620   sp = stack;
4621
4622   while (fixup < end_fixups)
4623     {
4624
4625       /* Save pointer to the start of this fixup.  We'll use
4626          it later to determine if it is necessary to put this fixup
4627          on the queue.  */
4628       save_fixup = fixup;
4629
4630       /* Get the fixup code and its associated format.  */
4631       op = *fixup++;
4632       fp = &som_fixup_formats[op];
4633
4634       /* Handle a request for a previous fixup.  */
4635       if (*fp->format == 'P')
4636         {
4637           /* Get pointer to the beginning of the prev fixup, move
4638              the repeated fixup to the head of the queue.  */
4639           fixup = reloc_queue[fp->D].reloc;
4640           som_reloc_queue_fix (reloc_queue, fp->D);
4641           prev_fixup = 1;
4642
4643           /* Get the fixup code and its associated format.  */
4644           op = *fixup++;
4645           fp = &som_fixup_formats[op];
4646         }
4647
4648       /* If this fixup will be passed to BFD, set some reasonable defaults.  */
4649       if (! just_count
4650           && som_hppa_howto_table[op].type != R_NO_RELOCATION
4651           && som_hppa_howto_table[op].type != R_DATA_OVERRIDE)
4652         {
4653           rptr->address = offset;
4654           rptr->howto = &som_hppa_howto_table[op];
4655           rptr->addend = 0;
4656           rptr->sym_ptr_ptr = bfd_abs_section_ptr->symbol_ptr_ptr;
4657         }
4658
4659       /* Set default input length to 0.  Get the opcode class index
4660          into D.  */
4661       var ('L') = 0;
4662       var ('D') = fp->D;
4663       var ('U') = saved_unwind_bits;
4664
4665       /* Get the opcode format.  */
4666       cp = fp->format;
4667
4668       /* Process the format string.  Parsing happens in two phases,
4669          parse RHS, then assign to LHS.  Repeat until no more
4670          characters in the format string.  */
4671       while (*cp)
4672         {
4673           /* The variable this pass is going to compute a value for.  */
4674           varname = *cp++;
4675
4676           /* Start processing RHS.  Continue until a NULL or '=' is found.  */
4677           do
4678             {
4679               c = *cp++;
4680
4681               /* If this is a variable, push it on the stack.  */
4682               if (ISUPPER (c))
4683                 push (var (c));
4684
4685               /* If this is a lower case letter, then it represents
4686                  additional data from the fixup stream to be pushed onto
4687                  the stack.  */
4688               else if (ISLOWER (c))
4689                 {
4690                   int bits = (c - 'a') * 8;
4691                   for (v = 0; c > 'a'; --c)
4692                     v = (v << 8) | *fixup++;
4693                   if (varname == 'V')
4694                     v = sign_extend (v, bits);
4695                   push (v);
4696                 }
4697
4698               /* A decimal constant.  Push it on the stack.  */
4699               else if (ISDIGIT (c))
4700                 {
4701                   v = c - '0';
4702                   while (ISDIGIT (*cp))
4703                     v = (v * 10) + (*cp++ - '0');
4704                   push (v);
4705                 }
4706               else
4707                 /* An operator.  Pop two two values from the stack and
4708                    use them as operands to the given operation.  Push
4709                    the result of the operation back on the stack.  */
4710                 switch (c)
4711                   {
4712                   case '+':
4713                     v = pop ();
4714                     v += pop ();
4715                     push (v);
4716                     break;
4717                   case '*':
4718                     v = pop ();
4719                     v *= pop ();
4720                     push (v);
4721                     break;
4722                   case '<':
4723                     v = pop ();
4724                     v = pop () << v;
4725                     push (v);
4726                     break;
4727                   default:
4728                     abort ();
4729                   }
4730             }
4731           while (*cp && *cp != '=');
4732
4733           /* Move over the equal operator.  */
4734           cp++;
4735
4736           /* Pop the RHS off the stack.  */
4737           c = pop ();
4738
4739           /* Perform the assignment.  */
4740           var (varname) = c;
4741
4742           /* Handle side effects. and special 'O' stack cases.  */
4743           switch (varname)
4744             {
4745             /* Consume some bytes from the input space.  */
4746             case 'L':
4747               offset += c;
4748               break;
4749             /* A symbol to use in the relocation.  Make a note
4750                of this if we are not just counting.  */
4751             case 'S':
4752               if (! just_count)
4753                 rptr->sym_ptr_ptr = &symbols[c];
4754               break;
4755             /* Argument relocation bits for a function call.  */
4756             case 'R':
4757               if (! just_count)
4758                 {
4759                   unsigned int tmp = var ('R');
4760                   rptr->addend = 0;
4761
4762                   if ((som_hppa_howto_table[op].type == R_PCREL_CALL
4763                        && R_PCREL_CALL + 10 > op)
4764                       || (som_hppa_howto_table[op].type == R_ABS_CALL
4765                           && R_ABS_CALL + 10 > op))
4766                     {
4767                       /* Simple encoding.  */
4768                       if (tmp > 4)
4769                         {
4770                           tmp -= 5;
4771                           rptr->addend |= 1;
4772                         }
4773                       if (tmp == 4)
4774                         rptr->addend |= 1 << 8 | 1 << 6 | 1 << 4 | 1 << 2;
4775                       else if (tmp == 3)
4776                         rptr->addend |= 1 << 8 | 1 << 6 | 1 << 4;
4777                       else if (tmp == 2)
4778                         rptr->addend |= 1 << 8 | 1 << 6;
4779                       else if (tmp == 1)
4780                         rptr->addend |= 1 << 8;
4781                     }
4782                   else
4783                     {
4784                       unsigned int tmp1, tmp2;
4785
4786                       /* First part is easy -- low order two bits are
4787                          directly copied, then shifted away.  */
4788                       rptr->addend = tmp & 0x3;
4789                       tmp >>= 2;
4790
4791                       /* Diving the result by 10 gives us the second
4792                          part.  If it is 9, then the first two words
4793                          are a double precision paramater, else it is
4794                          3 * the first arg bits + the 2nd arg bits.  */
4795                       tmp1 = tmp / 10;
4796                       tmp -= tmp1 * 10;
4797                       if (tmp1 == 9)
4798                         rptr->addend += (0xe << 6);
4799                       else
4800                         {
4801                           /* Get the two pieces.  */
4802                           tmp2 = tmp1 / 3;
4803                           tmp1 -= tmp2 * 3;
4804                           /* Put them in the addend.  */
4805                           rptr->addend += (tmp2 << 8) + (tmp1 << 6);
4806                         }
4807
4808                       /* What's left is the third part.  It's unpacked
4809                          just like the second.  */
4810                       if (tmp == 9)
4811                         rptr->addend += (0xe << 2);
4812                       else
4813                         {
4814                           tmp2 = tmp / 3;
4815                           tmp -= tmp2 * 3;
4816                           rptr->addend += (tmp2 << 4) + (tmp << 2);
4817                         }
4818                     }
4819                   rptr->addend = HPPA_R_ADDEND (rptr->addend, 0);
4820                 }
4821               break;
4822             /* Handle the linker expression stack.  */
4823             case 'O':
4824               switch (op)
4825                 {
4826                 case R_COMP1:
4827                   subop = comp1_opcodes;
4828                   break;
4829                 case R_COMP2:
4830                   subop = comp2_opcodes;
4831                   break;
4832                 case R_COMP3:
4833                   subop = comp3_opcodes;
4834                   break;
4835                 default:
4836                   abort ();
4837                 }
4838               while (*subop <= (unsigned char) c)
4839                 ++subop;
4840               --subop;
4841               break;
4842             /* The lower 32unwind bits must be persistent.  */
4843             case 'U':
4844               saved_unwind_bits = var ('U');
4845               break;
4846
4847             default:
4848               break;
4849             }
4850         }
4851
4852       /* If we used a previous fixup, clean up after it.  */
4853       if (prev_fixup)
4854         {
4855           fixup = save_fixup + 1;
4856           prev_fixup = 0;
4857         }
4858       /* Queue it.  */
4859       else if (fixup > save_fixup + 1)
4860         som_reloc_queue_insert (save_fixup, fixup - save_fixup, reloc_queue);
4861
4862       /* We do not pass R_DATA_OVERRIDE or R_NO_RELOCATION
4863          fixups to BFD.  */
4864       if (som_hppa_howto_table[op].type != R_DATA_OVERRIDE
4865           && som_hppa_howto_table[op].type != R_NO_RELOCATION)
4866         {
4867           /* Done with a single reloction. Loop back to the top.  */
4868           if (! just_count)
4869             {
4870               if (som_hppa_howto_table[op].type == R_ENTRY)
4871                 rptr->addend = var ('T');
4872               else if (som_hppa_howto_table[op].type == R_EXIT)
4873                 rptr->addend = var ('U');
4874               else if (som_hppa_howto_table[op].type == R_PCREL_CALL
4875                        || som_hppa_howto_table[op].type == R_ABS_CALL)
4876                 ;
4877               else if (som_hppa_howto_table[op].type == R_DATA_ONE_SYMBOL)
4878                 {
4879                   /* Try what was specified in R_DATA_OVERRIDE first
4880                      (if anything).  Then the hard way using the
4881                      section contents.  */
4882                   rptr->addend = var ('V');
4883
4884                   if (rptr->addend == 0 && !section->contents)
4885                     {
4886                       /* Got to read the damn contents first.  We don't
4887                          bother saving the contents (yet).  Add it one
4888                          day if the need arises.  */
4889                       section->contents = bfd_malloc (section->_raw_size);
4890                       if (section->contents == NULL)
4891                         return (unsigned) -1;
4892
4893                       deallocate_contents = 1;
4894                       bfd_get_section_contents (section->owner,
4895                                                 section,
4896                                                 section->contents,
4897                                                 (bfd_vma) 0,
4898                                                 section->_raw_size);
4899                     }
4900                   else if (rptr->addend == 0)
4901                     rptr->addend = bfd_get_32 (section->owner,
4902                                                (section->contents
4903                                                 + offset - var ('L')));
4904
4905                 }
4906               else
4907                 rptr->addend = var ('V');
4908               rptr++;
4909             }
4910           count++;
4911           /* Now that we've handled a "full" relocation, reset
4912              some state.  */
4913           memset (variables, 0, sizeof (variables));
4914           memset (stack, 0, sizeof (stack));
4915         }
4916     }
4917   if (deallocate_contents)
4918     free (section->contents);
4919
4920   return count;
4921
4922 #undef var
4923 #undef push
4924 #undef pop
4925 #undef emptystack
4926 }
4927
4928 /* Read in the relocs (aka fixups in SOM terms) for a section.
4929
4930    som_get_reloc_upper_bound calls this routine with JUST_COUNT
4931    set to true to indicate it only needs a count of the number
4932    of actual relocations.  */
4933
4934 static boolean
4935 som_slurp_reloc_table (abfd, section, symbols, just_count)
4936      bfd *abfd;
4937      asection *section;
4938      asymbol **symbols;
4939      boolean just_count;
4940 {
4941   char *external_relocs;
4942   unsigned int fixup_stream_size;
4943   arelent *internal_relocs;
4944   unsigned int num_relocs;
4945   bfd_size_type amt;
4946
4947   fixup_stream_size = som_section_data (section)->reloc_size;
4948   /* If there were no relocations, then there is nothing to do.  */
4949   if (section->reloc_count == 0)
4950     return true;
4951
4952   /* If reloc_count is -1, then the relocation stream has not been
4953      parsed.  We must do so now to know how many relocations exist.  */
4954   if (section->reloc_count == (unsigned) -1)
4955     {
4956       amt = fixup_stream_size;
4957       external_relocs = (char *) bfd_malloc (amt);
4958       if (external_relocs == (char *) NULL)
4959         return false;
4960       /* Read in the external forms.  */
4961       if (bfd_seek (abfd,
4962                     obj_som_reloc_filepos (abfd) + section->rel_filepos,
4963                     SEEK_SET)
4964           != 0)
4965         return false;
4966       if (bfd_bread (external_relocs, amt, abfd) != amt)
4967         return false;
4968
4969       /* Let callers know how many relocations found.
4970          also save the relocation stream as we will
4971          need it again.  */
4972       section->reloc_count = som_set_reloc_info (external_relocs,
4973                                                  fixup_stream_size,
4974                                                  NULL, NULL, NULL, true);
4975
4976       som_section_data (section)->reloc_stream = external_relocs;
4977     }
4978
4979   /* If the caller only wanted a count, then return now.  */
4980   if (just_count)
4981     return true;
4982
4983   num_relocs = section->reloc_count;
4984   external_relocs = som_section_data (section)->reloc_stream;
4985   /* Return saved information about the relocations if it is available.  */
4986   if (section->relocation != (arelent *) NULL)
4987     return true;
4988
4989   amt = num_relocs;
4990   amt *= sizeof (arelent);
4991   internal_relocs = (arelent *) bfd_zalloc (abfd, (amt));
4992   if (internal_relocs == (arelent *) NULL)
4993     return false;
4994
4995   /* Process and internalize the relocations.  */
4996   som_set_reloc_info (external_relocs, fixup_stream_size,
4997                       internal_relocs, section, symbols, false);
4998
4999   /* We're done with the external relocations.  Free them.  */
5000   free (external_relocs);
5001   som_section_data (section)->reloc_stream = NULL;
5002
5003   /* Save our results and return success.  */
5004   section->relocation = internal_relocs;
5005   return (true);
5006 }
5007
5008 /* Return the number of bytes required to store the relocation
5009    information associated with the given section.  */
5010
5011 static long
5012 som_get_reloc_upper_bound (abfd, asect)
5013      bfd *abfd;
5014      sec_ptr asect;
5015 {
5016   /* If section has relocations, then read in the relocation stream
5017      and parse it to determine how many relocations exist.  */
5018   if (asect->flags & SEC_RELOC)
5019     {
5020       if (! som_slurp_reloc_table (abfd, asect, NULL, true))
5021         return -1;
5022       return (asect->reloc_count + 1) * sizeof (arelent *);
5023     }
5024   /* There are no relocations.  */
5025   return 0;
5026 }
5027
5028 /* Convert relocations from SOM (external) form into BFD internal
5029    form.  Return the number of relocations.  */
5030
5031 static long
5032 som_canonicalize_reloc (abfd, section, relptr, symbols)
5033      bfd *abfd;
5034      sec_ptr section;
5035      arelent **relptr;
5036      asymbol **symbols;
5037 {
5038   arelent *tblptr;
5039   int count;
5040
5041   if (som_slurp_reloc_table (abfd, section, symbols, false) == false)
5042     return -1;
5043
5044   count = section->reloc_count;
5045   tblptr = section->relocation;
5046
5047   while (count--)
5048     *relptr++ = tblptr++;
5049
5050   *relptr = (arelent *) NULL;
5051   return section->reloc_count;
5052 }
5053
5054 extern const bfd_target som_vec;
5055
5056 /* A hook to set up object file dependent section information.  */
5057
5058 static boolean
5059 som_new_section_hook (abfd, newsect)
5060      bfd *abfd;
5061      asection *newsect;
5062 {
5063   bfd_size_type amt = sizeof (struct som_section_data_struct);
5064   newsect->used_by_bfd = (PTR) bfd_zalloc (abfd, amt);
5065   if (!newsect->used_by_bfd)
5066     return false;
5067   newsect->alignment_power = 3;
5068
5069   /* We allow more than three sections internally.  */
5070   return true;
5071 }
5072
5073 /* Copy any private info we understand from the input symbol
5074    to the output symbol.  */
5075
5076 static boolean
5077 som_bfd_copy_private_symbol_data (ibfd, isymbol, obfd, osymbol)
5078      bfd *ibfd;
5079      asymbol *isymbol;
5080      bfd *obfd;
5081      asymbol *osymbol;
5082 {
5083   struct som_symbol *input_symbol = (struct som_symbol *) isymbol;
5084   struct som_symbol *output_symbol = (struct som_symbol *) osymbol;
5085
5086   /* One day we may try to grok other private data.  */
5087   if (ibfd->xvec->flavour != bfd_target_som_flavour
5088       || obfd->xvec->flavour != bfd_target_som_flavour)
5089     return false;
5090
5091   /* The only private information we need to copy is the argument relocation
5092      bits.  */
5093   output_symbol->tc_data.ap.hppa_arg_reloc =
5094     input_symbol->tc_data.ap.hppa_arg_reloc;
5095
5096   return true;
5097 }
5098
5099 /* Copy any private info we understand from the input section
5100    to the output section.  */
5101
5102 static boolean
5103 som_bfd_copy_private_section_data (ibfd, isection, obfd, osection)
5104      bfd *ibfd;
5105      asection *isection;
5106      bfd *obfd;
5107      asection *osection;
5108 {
5109   bfd_size_type amt;
5110
5111   /* One day we may try to grok other private data.  */
5112   if (ibfd->xvec->flavour != bfd_target_som_flavour
5113       || obfd->xvec->flavour != bfd_target_som_flavour
5114       || (!som_is_space (isection) && !som_is_subspace (isection)))
5115     return true;
5116
5117   amt = sizeof (struct som_copyable_section_data_struct);
5118   som_section_data (osection)->copy_data =
5119     (struct som_copyable_section_data_struct *) bfd_zalloc (obfd, amt);
5120   if (som_section_data (osection)->copy_data == NULL)
5121     return false;
5122
5123   memcpy (som_section_data (osection)->copy_data,
5124           som_section_data (isection)->copy_data,
5125           sizeof (struct som_copyable_section_data_struct));
5126
5127   /* Reparent if necessary.  */
5128   if (som_section_data (osection)->copy_data->container)
5129     som_section_data (osection)->copy_data->container =
5130       som_section_data (osection)->copy_data->container->output_section;
5131
5132   return true;
5133 }
5134
5135 /* Copy any private info we understand from the input bfd
5136    to the output bfd.  */
5137
5138 static boolean
5139 som_bfd_copy_private_bfd_data (ibfd, obfd)
5140      bfd *ibfd, *obfd;
5141 {
5142   /* One day we may try to grok other private data.  */
5143   if (ibfd->xvec->flavour != bfd_target_som_flavour
5144       || obfd->xvec->flavour != bfd_target_som_flavour)
5145     return true;
5146
5147   /* Allocate some memory to hold the data we need.  */
5148   obj_som_exec_data (obfd) = (struct som_exec_data *)
5149     bfd_zalloc (obfd, (bfd_size_type) sizeof (struct som_exec_data));
5150   if (obj_som_exec_data (obfd) == NULL)
5151     return false;
5152
5153   /* Now copy the data.  */
5154   memcpy (obj_som_exec_data (obfd), obj_som_exec_data (ibfd),
5155           sizeof (struct som_exec_data));
5156
5157   return true;
5158 }
5159
5160 /* Set backend info for sections which can not be described
5161    in the BFD data structures.  */
5162
5163 boolean
5164 bfd_som_set_section_attributes (section, defined, private, sort_key, spnum)
5165      asection *section;
5166      int defined;
5167      int private;
5168      unsigned int sort_key;
5169      int spnum;
5170 {
5171   /* Allocate memory to hold the magic information.  */
5172   if (som_section_data (section)->copy_data == NULL)
5173     {
5174       bfd_size_type amt = sizeof (struct som_copyable_section_data_struct);
5175       som_section_data (section)->copy_data =
5176         (struct som_copyable_section_data_struct *) bfd_zalloc (section->owner,
5177                                                                 amt);
5178       if (som_section_data (section)->copy_data == NULL)
5179         return false;
5180     }
5181   som_section_data (section)->copy_data->sort_key = sort_key;
5182   som_section_data (section)->copy_data->is_defined = defined;
5183   som_section_data (section)->copy_data->is_private = private;
5184   som_section_data (section)->copy_data->container = section;
5185   som_section_data (section)->copy_data->space_number = spnum;
5186   return true;
5187 }
5188
5189 /* Set backend info for subsections which can not be described
5190    in the BFD data structures.  */
5191
5192 boolean
5193 bfd_som_set_subsection_attributes (section, container, access,
5194                                    sort_key, quadrant)
5195      asection *section;
5196      asection *container;
5197      int access;
5198      unsigned int sort_key;
5199      int quadrant;
5200 {
5201   /* Allocate memory to hold the magic information.  */
5202   if (som_section_data (section)->copy_data == NULL)
5203     {
5204       bfd_size_type amt = sizeof (struct som_copyable_section_data_struct);
5205       som_section_data (section)->copy_data =
5206         (struct som_copyable_section_data_struct *) bfd_zalloc (section->owner,
5207                                                                 amt);
5208       if (som_section_data (section)->copy_data == NULL)
5209         return false;
5210     }
5211   som_section_data (section)->copy_data->sort_key = sort_key;
5212   som_section_data (section)->copy_data->access_control_bits = access;
5213   som_section_data (section)->copy_data->quadrant = quadrant;
5214   som_section_data (section)->copy_data->container = container;
5215   return true;
5216 }
5217
5218 /* Set the full SOM symbol type.  SOM needs far more symbol information
5219    than any other object file format I'm aware of.  It is mandatory
5220    to be able to know if a symbol is an entry point, millicode, data,
5221    code, absolute, storage request, or procedure label.  If you get
5222    the symbol type wrong your program will not link.  */
5223
5224 void
5225 bfd_som_set_symbol_type (symbol, type)
5226      asymbol *symbol;
5227      unsigned int type;
5228 {
5229   som_symbol_data (symbol)->som_type = type;
5230 }
5231
5232 /* Attach an auxiliary header to the BFD backend so that it may be
5233    written into the object file.  */
5234
5235 boolean
5236 bfd_som_attach_aux_hdr (abfd, type, string)
5237      bfd *abfd;
5238      int type;
5239      char *string;
5240 {
5241   bfd_size_type amt;
5242
5243   if (type == VERSION_AUX_ID)
5244     {
5245       size_t len = strlen (string);
5246       int pad = 0;
5247
5248       if (len % 4)
5249         pad = (4 - (len % 4));
5250       amt = sizeof (struct aux_id) + sizeof (unsigned int) + len + pad;
5251       obj_som_version_hdr (abfd) =
5252         (struct user_string_aux_hdr *) bfd_zalloc (abfd, amt);
5253       if (!obj_som_version_hdr (abfd))
5254         return false;
5255       obj_som_version_hdr (abfd)->header_id.type = VERSION_AUX_ID;
5256       obj_som_version_hdr (abfd)->header_id.length = len + pad;
5257       obj_som_version_hdr (abfd)->header_id.length += sizeof (int);
5258       obj_som_version_hdr (abfd)->string_length = len;
5259       strncpy (obj_som_version_hdr (abfd)->user_string, string, len);
5260     }
5261   else if (type == COPYRIGHT_AUX_ID)
5262     {
5263       int len = strlen (string);
5264       int pad = 0;
5265
5266       if (len % 4)
5267         pad = (4 - (len % 4));
5268       amt = sizeof (struct aux_id) + sizeof (unsigned int) + len + pad;
5269       obj_som_copyright_hdr (abfd) =
5270         (struct copyright_aux_hdr *) bfd_zalloc (abfd, amt);
5271       if (!obj_som_copyright_hdr (abfd))
5272         return false;
5273       obj_som_copyright_hdr (abfd)->header_id.type = COPYRIGHT_AUX_ID;
5274       obj_som_copyright_hdr (abfd)->header_id.length = len + pad;
5275       obj_som_copyright_hdr (abfd)->header_id.length += sizeof (int);
5276       obj_som_copyright_hdr (abfd)->string_length = len;
5277       strcpy (obj_som_copyright_hdr (abfd)->copyright, string);
5278     }
5279   return true;
5280 }
5281
5282 /* Attach an compilation unit header to the BFD backend so that it may be
5283    written into the object file.  */
5284
5285 boolean
5286 bfd_som_attach_compilation_unit (abfd, name, language_name, product_id,
5287                                  version_id)
5288      bfd *abfd;
5289      const char *name;
5290      const char *language_name;
5291      const char *product_id;
5292      const char *version_id;
5293 {
5294   COMPUNIT *n = (COMPUNIT *) bfd_zalloc (abfd, (bfd_size_type) COMPUNITSZ);
5295   if (n == NULL)
5296     return false;
5297
5298 #define STRDUP(f) \
5299   if (f != NULL) \
5300     { \
5301       n->f.n_name = bfd_alloc (abfd, (bfd_size_type) strlen (f) + 1); \
5302       if (n->f.n_name == NULL) \
5303         return false; \
5304       strcpy (n->f.n_name, f); \
5305     }
5306
5307   STRDUP (name);
5308   STRDUP (language_name);
5309   STRDUP (product_id);
5310   STRDUP (version_id);
5311
5312 #undef STRDUP
5313
5314   obj_som_compilation_unit (abfd) = n;
5315
5316   return true;
5317 }
5318
5319 static boolean
5320 som_get_section_contents (abfd, section, location, offset, count)
5321      bfd *abfd;
5322      sec_ptr section;
5323      PTR location;
5324      file_ptr offset;
5325      bfd_size_type count;
5326 {
5327   if (count == 0 || ((section->flags & SEC_HAS_CONTENTS) == 0))
5328     return true;
5329   if ((bfd_size_type) (offset+count) > section->_raw_size
5330       || bfd_seek (abfd, (file_ptr) (section->filepos + offset), SEEK_SET) != 0
5331       || bfd_bread (location, count, abfd) != count)
5332     return (false); /* on error */
5333   return (true);
5334 }
5335
5336 static boolean
5337 som_set_section_contents (abfd, section, location, offset, count)
5338      bfd *abfd;
5339      sec_ptr section;
5340      PTR location;
5341      file_ptr offset;
5342      bfd_size_type count;
5343 {
5344   if (abfd->output_has_begun == false)
5345     {
5346       /* Set up fixed parts of the file, space, and subspace headers.
5347          Notify the world that output has begun.  */
5348       som_prep_headers (abfd);
5349       abfd->output_has_begun = true;
5350       /* Start writing the object file.  This include all the string
5351          tables, fixup streams, and other portions of the object file.  */
5352       som_begin_writing (abfd);
5353     }
5354
5355   /* Only write subspaces which have "real" contents (eg. the contents
5356      are not generated at run time by the OS).  */
5357   if (!som_is_subspace (section)
5358       || ((section->flags & SEC_HAS_CONTENTS) == 0))
5359     return true;
5360
5361   /* Seek to the proper offset within the object file and write the
5362      data.  */
5363   offset += som_section_data (section)->subspace_dict->file_loc_init_value;
5364   if (bfd_seek (abfd, offset, SEEK_SET) != 0)
5365     return false;
5366
5367   if (bfd_bwrite ((PTR) location, count, abfd) != count)
5368     return false;
5369   return true;
5370 }
5371
5372 static boolean
5373 som_set_arch_mach (abfd, arch, machine)
5374      bfd *abfd;
5375      enum bfd_architecture arch;
5376      unsigned long machine;
5377 {
5378   /* Allow any architecture to be supported by the SOM backend.  */
5379   return bfd_default_set_arch_mach (abfd, arch, machine);
5380 }
5381
5382 static boolean
5383 som_find_nearest_line (abfd, section, symbols, offset, filename_ptr,
5384                        functionname_ptr, line_ptr)
5385      bfd *abfd ATTRIBUTE_UNUSED;
5386      asection *section ATTRIBUTE_UNUSED;
5387      asymbol **symbols ATTRIBUTE_UNUSED;
5388      bfd_vma offset ATTRIBUTE_UNUSED;
5389      const char **filename_ptr ATTRIBUTE_UNUSED;
5390      const char **functionname_ptr ATTRIBUTE_UNUSED;
5391      unsigned int *line_ptr ATTRIBUTE_UNUSED;
5392 {
5393   return (false);
5394 }
5395
5396 static int
5397 som_sizeof_headers (abfd, reloc)
5398      bfd *abfd ATTRIBUTE_UNUSED;
5399      boolean reloc ATTRIBUTE_UNUSED;
5400 {
5401   (*_bfd_error_handler) (_("som_sizeof_headers unimplemented"));
5402   fflush (stderr);
5403   abort ();
5404   return (0);
5405 }
5406
5407 /* Return the single-character symbol type corresponding to
5408    SOM section S, or '?' for an unknown SOM section.  */
5409
5410 static char
5411 som_section_type (s)
5412      const char *s;
5413 {
5414   const struct section_to_type *t;
5415
5416   for (t = &stt[0]; t->section; t++)
5417     if (!strcmp (s, t->section))
5418       return t->type;
5419   return '?';
5420 }
5421
5422 static int
5423 som_decode_symclass (symbol)
5424      asymbol *symbol;
5425 {
5426   char c;
5427
5428   if (bfd_is_com_section (symbol->section))
5429     return 'C';
5430   if (bfd_is_und_section (symbol->section))
5431     return 'U';
5432   if (bfd_is_ind_section (symbol->section))
5433     return 'I';
5434   if (symbol->flags & BSF_WEAK)
5435     return 'W';
5436   if (!(symbol->flags & (BSF_GLOBAL | BSF_LOCAL)))
5437     return '?';
5438
5439   if (bfd_is_abs_section (symbol->section)
5440       || (som_symbol_data (symbol) != NULL
5441           && som_symbol_data (symbol)->som_type == SYMBOL_TYPE_ABSOLUTE))
5442     c = 'a';
5443   else if (symbol->section)
5444     c = som_section_type (symbol->section->name);
5445   else
5446     return '?';
5447   if (symbol->flags & BSF_GLOBAL)
5448     c = TOUPPER (c);
5449   return c;
5450 }
5451
5452 /* Return information about SOM symbol SYMBOL in RET.  */
5453
5454 static void
5455 som_get_symbol_info (ignore_abfd, symbol, ret)
5456      bfd *ignore_abfd ATTRIBUTE_UNUSED;
5457      asymbol *symbol;
5458      symbol_info *ret;
5459 {
5460   ret->type = som_decode_symclass (symbol);
5461   if (ret->type != 'U')
5462     ret->value = symbol->value + symbol->section->vma;
5463   else
5464     ret->value = 0;
5465   ret->name = symbol->name;
5466 }
5467
5468 /* Count the number of symbols in the archive symbol table.  Necessary
5469    so that we can allocate space for all the carsyms at once.  */
5470
5471 static boolean
5472 som_bfd_count_ar_symbols (abfd, lst_header, count)
5473      bfd *abfd;
5474      struct lst_header *lst_header;
5475      symindex *count;
5476 {
5477   unsigned int i;
5478   unsigned int *hash_table = NULL;
5479   bfd_size_type amt;
5480   file_ptr lst_filepos = bfd_tell (abfd) - sizeof (struct lst_header);
5481
5482   amt = lst_header->hash_size;
5483   amt *= sizeof (unsigned int);
5484   hash_table = (unsigned int *) bfd_malloc (amt);
5485   if (hash_table == NULL && lst_header->hash_size != 0)
5486     goto error_return;
5487
5488   /* Don't forget to initialize the counter!  */
5489   *count = 0;
5490
5491   /* Read in the hash table.  The has table is an array of 32bit file offsets
5492      which point to the hash chains.  */
5493   if (bfd_bread ((PTR) hash_table, amt, abfd) != amt)
5494     goto error_return;
5495
5496   /* Walk each chain counting the number of symbols found on that particular
5497      chain.  */
5498   for (i = 0; i < lst_header->hash_size; i++)
5499     {
5500       struct lst_symbol_record lst_symbol;
5501
5502       /* An empty chain has zero as it's file offset.  */
5503       if (hash_table[i] == 0)
5504         continue;
5505
5506       /* Seek to the first symbol in this hash chain.  */
5507       if (bfd_seek (abfd, lst_filepos + hash_table[i], SEEK_SET) != 0)
5508         goto error_return;
5509
5510       /* Read in this symbol and update the counter.  */
5511       amt = sizeof (lst_symbol);
5512       if (bfd_bread ((PTR) &lst_symbol, amt, abfd) != amt)
5513         goto error_return;
5514
5515       (*count)++;
5516
5517       /* Now iterate through the rest of the symbols on this chain.  */
5518       while (lst_symbol.next_entry)
5519         {
5520
5521           /* Seek to the next symbol.  */
5522           if (bfd_seek (abfd, lst_filepos + lst_symbol.next_entry, SEEK_SET)
5523               != 0)
5524             goto error_return;
5525
5526           /* Read the symbol in and update the counter.  */
5527           amt = sizeof (lst_symbol);
5528           if (bfd_bread ((PTR) &lst_symbol, amt, abfd) != amt)
5529             goto error_return;
5530
5531           (*count)++;
5532         }
5533     }
5534   if (hash_table != NULL)
5535     free (hash_table);
5536   return true;
5537
5538  error_return:
5539   if (hash_table != NULL)
5540     free (hash_table);
5541   return false;
5542 }
5543
5544 /* Fill in the canonical archive symbols (SYMS) from the archive described
5545    by ABFD and LST_HEADER.  */
5546
5547 static boolean
5548 som_bfd_fill_in_ar_symbols (abfd, lst_header, syms)
5549      bfd *abfd;
5550      struct lst_header *lst_header;
5551      carsym **syms;
5552 {
5553   unsigned int i, len;
5554   carsym *set = syms[0];
5555   unsigned int *hash_table = NULL;
5556   struct som_entry *som_dict = NULL;
5557   bfd_size_type amt;
5558   file_ptr lst_filepos = bfd_tell (abfd) - sizeof (struct lst_header);
5559
5560   amt = lst_header->hash_size;
5561   amt *= sizeof (unsigned int);
5562   hash_table = (unsigned int *) bfd_malloc (amt);
5563   if (hash_table == NULL && lst_header->hash_size != 0)
5564     goto error_return;
5565
5566   /* Read in the hash table.  The has table is an array of 32bit file offsets
5567      which point to the hash chains.  */
5568   if (bfd_bread ((PTR) hash_table, amt, abfd) != amt)
5569     goto error_return;
5570
5571   /* Seek to and read in the SOM dictionary.  We will need this to fill
5572      in the carsym's filepos field.  */
5573   if (bfd_seek (abfd, lst_filepos + lst_header->dir_loc, SEEK_SET) != 0)
5574     goto error_return;
5575
5576   amt = lst_header->module_count;
5577   amt *= sizeof (struct som_entry);
5578   som_dict = (struct som_entry *) bfd_malloc (amt);
5579   if (som_dict == NULL && lst_header->module_count != 0)
5580     goto error_return;
5581
5582   if (bfd_bread ((PTR) som_dict, amt, abfd) != amt)
5583     goto error_return;
5584
5585   /* Walk each chain filling in the carsyms as we go along.  */
5586   for (i = 0; i < lst_header->hash_size; i++)
5587     {
5588       struct lst_symbol_record lst_symbol;
5589
5590       /* An empty chain has zero as it's file offset.  */
5591       if (hash_table[i] == 0)
5592         continue;
5593
5594       /* Seek to and read the first symbol on the chain.  */
5595       if (bfd_seek (abfd, lst_filepos + hash_table[i], SEEK_SET) != 0)
5596         goto error_return;
5597
5598       amt = sizeof (lst_symbol);
5599       if (bfd_bread ((PTR) &lst_symbol, amt, abfd) != amt)
5600         goto error_return;
5601
5602       /* Get the name of the symbol, first get the length which is stored
5603          as a 32bit integer just before the symbol.
5604
5605          One might ask why we don't just read in the entire string table
5606          and index into it.  Well, according to the SOM ABI the string
5607          index can point *anywhere* in the archive to save space, so just
5608          using the string table would not be safe.  */
5609       if (bfd_seek (abfd, lst_filepos + lst_header->string_loc
5610                             + lst_symbol.name.n_strx - 4, SEEK_SET) != 0)
5611         goto error_return;
5612
5613       if (bfd_bread (&len, (bfd_size_type) 4, abfd) != 4)
5614         goto error_return;
5615
5616       /* Allocate space for the name and null terminate it too.  */
5617       set->name = bfd_zalloc (abfd, (bfd_size_type) len + 1);
5618       if (!set->name)
5619         goto error_return;
5620       if (bfd_bread (set->name, (bfd_size_type) len, abfd) != len)
5621         goto error_return;
5622
5623       set->name[len] = 0;
5624
5625       /* Fill in the file offset.  Note that the "location" field points
5626          to the SOM itself, not the ar_hdr in front of it.  */
5627       set->file_offset = som_dict[lst_symbol.som_index].location
5628                           - sizeof (struct ar_hdr);
5629
5630       /* Go to the next symbol.  */
5631       set++;
5632
5633       /* Iterate through the rest of the chain.  */
5634       while (lst_symbol.next_entry)
5635         {
5636           /* Seek to the next symbol and read it in.  */
5637           if (bfd_seek (abfd, lst_filepos + lst_symbol.next_entry, SEEK_SET)
5638               != 0)
5639             goto error_return;
5640
5641           amt = sizeof (lst_symbol);
5642           if (bfd_bread ((PTR) &lst_symbol, amt, abfd) != amt)
5643             goto error_return;
5644
5645           /* Seek to the name length & string and read them in.  */
5646           if (bfd_seek (abfd, lst_filepos + lst_header->string_loc
5647                                 + lst_symbol.name.n_strx - 4, SEEK_SET) != 0)
5648             goto error_return;
5649
5650           if (bfd_bread (&len, (bfd_size_type) 4, abfd) != 4)
5651             goto error_return;
5652
5653           /* Allocate space for the name and null terminate it too.  */
5654           set->name = bfd_zalloc (abfd, (bfd_size_type) len + 1);
5655           if (!set->name)
5656             goto error_return;
5657
5658           if (bfd_bread (set->name, (bfd_size_type) len, abfd) != len)
5659             goto error_return;
5660           set->name[len] = 0;
5661
5662           /* Fill in the file offset.  Note that the "location" field points
5663              to the SOM itself, not the ar_hdr in front of it.  */
5664           set->file_offset = som_dict[lst_symbol.som_index].location
5665                                - sizeof (struct ar_hdr);
5666
5667           /* Go on to the next symbol.  */
5668           set++;
5669         }
5670     }
5671   /* If we haven't died by now, then we successfully read the entire
5672      archive symbol table.  */
5673   if (hash_table != NULL)
5674     free (hash_table);
5675   if (som_dict != NULL)
5676     free (som_dict);
5677   return true;
5678
5679  error_return:
5680   if (hash_table != NULL)
5681     free (hash_table);
5682   if (som_dict != NULL)
5683     free (som_dict);
5684   return false;
5685 }
5686
5687 /* Read in the LST from the archive.  */
5688
5689 static boolean
5690 som_slurp_armap (abfd)
5691      bfd *abfd;
5692 {
5693   struct lst_header lst_header;
5694   struct ar_hdr ar_header;
5695   unsigned int parsed_size;
5696   struct artdata *ardata = bfd_ardata (abfd);
5697   char nextname[17];
5698   bfd_size_type amt = 16;
5699   int i = bfd_bread ((PTR) nextname, amt, abfd);
5700
5701   /* Special cases.  */
5702   if (i == 0)
5703     return true;
5704   if (i != 16)
5705     return false;
5706
5707   if (bfd_seek (abfd, (file_ptr) -16, SEEK_CUR) != 0)
5708     return false;
5709
5710   /* For archives without .o files there is no symbol table.  */
5711   if (strncmp (nextname, "/               ", 16))
5712     {
5713       bfd_has_map (abfd) = false;
5714       return true;
5715     }
5716
5717   /* Read in and sanity check the archive header.  */
5718   amt = sizeof (struct ar_hdr);
5719   if (bfd_bread ((PTR) &ar_header, amt, abfd) != amt)
5720     return false;
5721
5722   if (strncmp (ar_header.ar_fmag, ARFMAG, 2))
5723     {
5724       bfd_set_error (bfd_error_malformed_archive);
5725       return false;
5726     }
5727
5728   /* How big is the archive symbol table entry?  */
5729   errno = 0;
5730   parsed_size = strtol (ar_header.ar_size, NULL, 10);
5731   if (errno != 0)
5732     {
5733       bfd_set_error (bfd_error_malformed_archive);
5734       return false;
5735     }
5736
5737   /* Save off the file offset of the first real user data.  */
5738   ardata->first_file_filepos = bfd_tell (abfd) + parsed_size;
5739
5740   /* Read in the library symbol table.  We'll make heavy use of this
5741      in just a minute.  */
5742   amt = sizeof (struct lst_header);
5743   if (bfd_bread ((PTR) &lst_header, amt, abfd) != amt)
5744     return false;
5745
5746   /* Sanity check.  */
5747   if (lst_header.a_magic != LIBMAGIC)
5748     {
5749       bfd_set_error (bfd_error_malformed_archive);
5750       return false;
5751     }
5752
5753   /* Count the number of symbols in the library symbol table.  */
5754   if (som_bfd_count_ar_symbols (abfd, &lst_header, &ardata->symdef_count)
5755       == false)
5756     return false;
5757
5758   /* Get back to the start of the library symbol table.  */
5759   if (bfd_seek (abfd, (ardata->first_file_filepos - parsed_size
5760                        + sizeof (struct lst_header)), SEEK_SET) != 0)
5761     return false;
5762
5763   /* Initializae the cache and allocate space for the library symbols.  */
5764   ardata->cache = 0;
5765   amt = ardata->symdef_count;
5766   amt *= sizeof (carsym);
5767   ardata->symdefs = (carsym *) bfd_alloc (abfd, amt);
5768   if (!ardata->symdefs)
5769     return false;
5770
5771   /* Now fill in the canonical archive symbols.  */
5772   if (som_bfd_fill_in_ar_symbols (abfd, &lst_header, &ardata->symdefs)
5773       == false)
5774     return false;
5775
5776   /* Seek back to the "first" file in the archive.  Note the "first"
5777      file may be the extended name table.  */
5778   if (bfd_seek (abfd, ardata->first_file_filepos, SEEK_SET) != 0)
5779     return false;
5780
5781   /* Notify the generic archive code that we have a symbol map.  */
5782   bfd_has_map (abfd) = true;
5783   return true;
5784 }
5785
5786 /* Begin preparing to write a SOM library symbol table.
5787
5788    As part of the prep work we need to determine the number of symbols
5789    and the size of the associated string section.  */
5790
5791 static boolean
5792 som_bfd_prep_for_ar_write (abfd, num_syms, stringsize)
5793      bfd *abfd;
5794      unsigned int *num_syms, *stringsize;
5795 {
5796   bfd *curr_bfd = abfd->archive_head;
5797
5798   /* Some initialization.  */
5799   *num_syms = 0;
5800   *stringsize = 0;
5801
5802   /* Iterate over each BFD within this archive.  */
5803   while (curr_bfd != NULL)
5804     {
5805       unsigned int curr_count, i;
5806       som_symbol_type *sym;
5807
5808       /* Don't bother for non-SOM objects.  */
5809       if (curr_bfd->format != bfd_object
5810           || curr_bfd->xvec->flavour != bfd_target_som_flavour)
5811         {
5812           curr_bfd = curr_bfd->next;
5813           continue;
5814         }
5815
5816       /* Make sure the symbol table has been read, then snag a pointer
5817          to it.  It's a little slimey to grab the symbols via obj_som_symtab,
5818          but doing so avoids allocating lots of extra memory.  */
5819       if (som_slurp_symbol_table (curr_bfd) == false)
5820         return false;
5821
5822       sym = obj_som_symtab (curr_bfd);
5823       curr_count = bfd_get_symcount (curr_bfd);
5824
5825       /* Examine each symbol to determine if it belongs in the
5826          library symbol table.  */
5827       for (i = 0; i < curr_count; i++, sym++)
5828         {
5829           struct som_misc_symbol_info info;
5830
5831           /* Derive SOM information from the BFD symbol.  */
5832           som_bfd_derive_misc_symbol_info (curr_bfd, &sym->symbol, &info);
5833
5834           /* Should we include this symbol?  */
5835           if (info.symbol_type == ST_NULL
5836               || info.symbol_type == ST_SYM_EXT
5837               || info.symbol_type == ST_ARG_EXT)
5838             continue;
5839
5840           /* Only global symbols and unsatisfied commons.  */
5841           if (info.symbol_scope != SS_UNIVERSAL
5842               && info.symbol_type != ST_STORAGE)
5843             continue;
5844
5845           /* Do no include undefined symbols.  */
5846           if (bfd_is_und_section (sym->symbol.section))
5847             continue;
5848
5849           /* Bump the various counters, being careful to honor
5850              alignment considerations in the string table.  */
5851           (*num_syms)++;
5852           *stringsize = *stringsize + strlen (sym->symbol.name) + 5;
5853           while (*stringsize % 4)
5854             (*stringsize)++;
5855         }
5856
5857       curr_bfd = curr_bfd->next;
5858     }
5859   return true;
5860 }
5861
5862 /* Hash a symbol name based on the hashing algorithm presented in the
5863    SOM ABI.  */
5864
5865 static unsigned int
5866 som_bfd_ar_symbol_hash (symbol)
5867      asymbol *symbol;
5868 {
5869   unsigned int len = strlen (symbol->name);
5870
5871   /* Names with length 1 are special.  */
5872   if (len == 1)
5873     return 0x1000100 | (symbol->name[0] << 16) | symbol->name[0];
5874
5875   return ((len & 0x7f) << 24) | (symbol->name[1] << 16)
5876           | (symbol->name[len - 2] << 8) | symbol->name[len - 1];
5877 }
5878
5879 /* Do the bulk of the work required to write the SOM library
5880    symbol table.  */
5881
5882 static boolean
5883 som_bfd_ar_write_symbol_stuff (abfd, nsyms, string_size, lst, elength)
5884      bfd *abfd;
5885      unsigned int nsyms, string_size;
5886      struct lst_header lst;
5887      unsigned elength;
5888 {
5889   file_ptr lst_filepos;
5890   char *strings = NULL, *p;
5891   struct lst_symbol_record *lst_syms = NULL, *curr_lst_sym;
5892   bfd *curr_bfd;
5893   unsigned int *hash_table = NULL;
5894   struct som_entry *som_dict = NULL;
5895   struct lst_symbol_record **last_hash_entry = NULL;
5896   unsigned int curr_som_offset, som_index = 0;
5897   bfd_size_type amt;
5898
5899   amt = lst.hash_size;
5900   amt *= sizeof (unsigned int);
5901   hash_table = (unsigned int *) bfd_malloc (amt);
5902   if (hash_table == NULL && lst.hash_size != 0)
5903     goto error_return;
5904
5905   amt = lst.module_count;
5906   amt *= sizeof (struct som_entry);
5907   som_dict = (struct som_entry *) bfd_malloc (amt);
5908   if (som_dict == NULL && lst.module_count != 0)
5909     goto error_return;
5910
5911   amt = lst.hash_size;
5912   amt *= sizeof (struct lst_symbol_record *);
5913   last_hash_entry = ((struct lst_symbol_record **) bfd_malloc (amt));
5914   if (last_hash_entry == NULL && lst.hash_size != 0)
5915     goto error_return;
5916
5917   /* Lots of fields are file positions relative to the start
5918      of the lst record.  So save its location.  */
5919   lst_filepos = bfd_tell (abfd) - sizeof (struct lst_header);
5920
5921   /* Some initialization.  */
5922   memset (hash_table, 0, 4 * lst.hash_size);
5923   memset (som_dict, 0, lst.module_count * sizeof (struct som_entry));
5924   memset (last_hash_entry, 0,
5925           lst.hash_size * sizeof (struct lst_symbol_record *));
5926
5927   /* Symbols have som_index fields, so we have to keep track of the
5928      index of each SOM in the archive.
5929
5930      The SOM dictionary has (among other things) the absolute file
5931      position for the SOM which a particular dictionary entry
5932      describes.  We have to compute that information as we iterate
5933      through the SOMs/symbols.  */
5934   som_index = 0;
5935
5936   /* We add in the size of the archive header twice as the location
5937      in the SOM dictionary is the actual offset of the SOM, not the
5938      archive header before the SOM.  */
5939   curr_som_offset = 8 + 2 * sizeof (struct ar_hdr) + lst.file_end;
5940
5941   /* Make room for the archive header and the contents of the
5942      extended string table.  Note that elength includes the size
5943      of the archive header for the extended name table!  */
5944   if (elength)
5945     curr_som_offset += elength;
5946
5947   /* Make sure we're properly aligned.  */
5948   curr_som_offset = (curr_som_offset + 0x1) & ~0x1;
5949
5950   /* FIXME should be done with buffers just like everything else...  */
5951   amt = nsyms;
5952   amt *= sizeof (struct lst_symbol_record);
5953   lst_syms = bfd_malloc (amt);
5954   if (lst_syms == NULL && nsyms != 0)
5955     goto error_return;
5956   strings = bfd_malloc ((bfd_size_type) string_size);
5957   if (strings == NULL && string_size != 0)
5958     goto error_return;
5959
5960   p = strings;
5961   curr_lst_sym = lst_syms;
5962
5963   curr_bfd = abfd->archive_head;
5964   while (curr_bfd != NULL)
5965     {
5966       unsigned int curr_count, i;
5967       som_symbol_type *sym;
5968
5969       /* Don't bother for non-SOM objects.  */
5970       if (curr_bfd->format != bfd_object
5971           || curr_bfd->xvec->flavour != bfd_target_som_flavour)
5972         {
5973           curr_bfd = curr_bfd->next;
5974           continue;
5975         }
5976
5977       /* Make sure the symbol table has been read, then snag a pointer
5978          to it.  It's a little slimey to grab the symbols via obj_som_symtab,
5979          but doing so avoids allocating lots of extra memory.  */
5980       if (som_slurp_symbol_table (curr_bfd) == false)
5981         goto error_return;
5982
5983       sym = obj_som_symtab (curr_bfd);
5984       curr_count = bfd_get_symcount (curr_bfd);
5985
5986       for (i = 0; i < curr_count; i++, sym++)
5987         {
5988           struct som_misc_symbol_info info;
5989
5990           /* Derive SOM information from the BFD symbol.  */
5991           som_bfd_derive_misc_symbol_info (curr_bfd, &sym->symbol, &info);
5992
5993           /* Should we include this symbol?  */
5994           if (info.symbol_type == ST_NULL
5995               || info.symbol_type == ST_SYM_EXT
5996               || info.symbol_type == ST_ARG_EXT)
5997             continue;
5998
5999           /* Only global symbols and unsatisfied commons.  */
6000           if (info.symbol_scope != SS_UNIVERSAL
6001               && info.symbol_type != ST_STORAGE)
6002             continue;
6003
6004           /* Do no include undefined symbols.  */
6005           if (bfd_is_und_section (sym->symbol.section))
6006             continue;
6007
6008           /* If this is the first symbol from this SOM, then update
6009              the SOM dictionary too.  */
6010           if (som_dict[som_index].location == 0)
6011             {
6012               som_dict[som_index].location = curr_som_offset;
6013               som_dict[som_index].length = arelt_size (curr_bfd);
6014             }
6015
6016           /* Fill in the lst symbol record.  */
6017           curr_lst_sym->hidden = 0;
6018           curr_lst_sym->secondary_def = info.secondary_def;
6019           curr_lst_sym->symbol_type = info.symbol_type;
6020           curr_lst_sym->symbol_scope = info.symbol_scope;
6021           curr_lst_sym->check_level = 0;
6022           curr_lst_sym->must_qualify = 0;
6023           curr_lst_sym->initially_frozen = 0;
6024           curr_lst_sym->memory_resident = 0;
6025           curr_lst_sym->is_common = bfd_is_com_section (sym->symbol.section);
6026           curr_lst_sym->dup_common = 0;
6027           curr_lst_sym->xleast = 3;
6028           curr_lst_sym->arg_reloc = info.arg_reloc;
6029           curr_lst_sym->name.n_strx = p - strings + 4;
6030           curr_lst_sym->qualifier_name.n_strx = 0;
6031           curr_lst_sym->symbol_info = info.symbol_info;
6032           curr_lst_sym->symbol_value = info.symbol_value | info.priv_level;
6033           curr_lst_sym->symbol_descriptor = 0;
6034           curr_lst_sym->reserved = 0;
6035           curr_lst_sym->som_index = som_index;
6036           curr_lst_sym->symbol_key = som_bfd_ar_symbol_hash (&sym->symbol);
6037           curr_lst_sym->next_entry = 0;
6038
6039           /* Insert into the hash table.  */
6040           if (hash_table[curr_lst_sym->symbol_key % lst.hash_size])
6041             {
6042               struct lst_symbol_record *tmp;
6043
6044               /* There is already something at the head of this hash chain,
6045                  so tack this symbol onto the end of the chain.  */
6046               tmp = last_hash_entry[curr_lst_sym->symbol_key % lst.hash_size];
6047               tmp->next_entry
6048                 = (curr_lst_sym - lst_syms) * sizeof (struct lst_symbol_record)
6049                   + lst.hash_size * 4
6050                   + lst.module_count * sizeof (struct som_entry)
6051                   + sizeof (struct lst_header);
6052             }
6053           else
6054             {
6055               /* First entry in this hash chain.  */
6056               hash_table[curr_lst_sym->symbol_key % lst.hash_size]
6057                 = (curr_lst_sym - lst_syms) * sizeof (struct lst_symbol_record)
6058                   + lst.hash_size * 4
6059                   + lst.module_count * sizeof (struct som_entry)
6060                   + sizeof (struct lst_header);
6061             }
6062
6063           /* Keep track of the last symbol we added to this chain so we can
6064              easily update its next_entry pointer.  */
6065           last_hash_entry[curr_lst_sym->symbol_key % lst.hash_size]
6066             = curr_lst_sym;
6067
6068           /* Update the string table.  */
6069           bfd_put_32 (abfd, strlen (sym->symbol.name), p);
6070           p += 4;
6071           strcpy (p, sym->symbol.name);
6072           p += strlen (sym->symbol.name) + 1;
6073           while ((int) p % 4)
6074             {
6075               bfd_put_8 (abfd, 0, p);
6076               p++;
6077             }
6078
6079           /* Head to the next symbol.  */
6080           curr_lst_sym++;
6081         }
6082
6083       /* Keep track of where each SOM will finally reside; then look
6084          at the next BFD.  */
6085       curr_som_offset += arelt_size (curr_bfd) + sizeof (struct ar_hdr);
6086
6087       /* A particular object in the archive may have an odd length; the
6088          linker requires objects begin on an even boundary.  So round
6089          up the current offset as necessary.  */
6090       curr_som_offset = (curr_som_offset + 0x1) &~ (unsigned) 1;
6091       curr_bfd = curr_bfd->next;
6092       som_index++;
6093     }
6094
6095   /* Now scribble out the hash table.  */
6096   amt = lst.hash_size * 4;
6097   if (bfd_bwrite ((PTR) hash_table, amt, abfd) != amt)
6098     goto error_return;
6099
6100   /* Then the SOM dictionary.  */
6101   amt = lst.module_count * sizeof (struct som_entry);
6102   if (bfd_bwrite ((PTR) som_dict, amt, abfd) != amt)
6103     goto error_return;
6104
6105   /* The library symbols.  */
6106   amt = nsyms * sizeof (struct lst_symbol_record);
6107   if (bfd_bwrite ((PTR) lst_syms, amt, abfd) != amt)
6108     goto error_return;
6109
6110   /* And finally the strings.  */
6111   amt = string_size;
6112   if (bfd_bwrite ((PTR) strings, amt, abfd) != amt)
6113     goto error_return;
6114
6115   if (hash_table != NULL)
6116     free (hash_table);
6117   if (som_dict != NULL)
6118     free (som_dict);
6119   if (last_hash_entry != NULL)
6120     free (last_hash_entry);
6121   if (lst_syms != NULL)
6122     free (lst_syms);
6123   if (strings != NULL)
6124     free (strings);
6125   return true;
6126
6127  error_return:
6128   if (hash_table != NULL)
6129     free (hash_table);
6130   if (som_dict != NULL)
6131     free (som_dict);
6132   if (last_hash_entry != NULL)
6133     free (last_hash_entry);
6134   if (lst_syms != NULL)
6135     free (lst_syms);
6136   if (strings != NULL)
6137     free (strings);
6138
6139   return false;
6140 }
6141
6142 /* Write out the LST for the archive.
6143
6144    You'll never believe this is really how armaps are handled in SOM...  */
6145
6146 static boolean
6147 som_write_armap (abfd, elength, map, orl_count, stridx)
6148      bfd *abfd;
6149      unsigned int elength;
6150      struct orl *map ATTRIBUTE_UNUSED;
6151      unsigned int orl_count ATTRIBUTE_UNUSED;
6152      int stridx ATTRIBUTE_UNUSED;
6153 {
6154   bfd *curr_bfd;
6155   struct stat statbuf;
6156   unsigned int i, lst_size, nsyms, stringsize;
6157   struct ar_hdr hdr;
6158   struct lst_header lst;
6159   int *p;
6160   bfd_size_type amt;
6161
6162   /* We'll use this for the archive's date and mode later.  */
6163   if (stat (abfd->filename, &statbuf) != 0)
6164     {
6165       bfd_set_error (bfd_error_system_call);
6166       return false;
6167     }
6168   /* Fudge factor.  */
6169   bfd_ardata (abfd)->armap_timestamp = statbuf.st_mtime + 60;
6170
6171   /* Account for the lst header first.  */
6172   lst_size = sizeof (struct lst_header);
6173
6174   /* Start building the LST header.  */
6175   /* FIXME:  Do we need to examine each element to determine the
6176      largest id number?  */
6177   lst.system_id = CPU_PA_RISC1_0;
6178   lst.a_magic = LIBMAGIC;
6179   lst.version_id = VERSION_ID;
6180   lst.file_time.secs = 0;
6181   lst.file_time.nanosecs = 0;
6182
6183   lst.hash_loc = lst_size;
6184   lst.hash_size = SOM_LST_HASH_SIZE;
6185
6186   /* Hash table is a SOM_LST_HASH_SIZE 32bit offsets.  */
6187   lst_size += 4 * SOM_LST_HASH_SIZE;
6188
6189   /* We need to count the number of SOMs in this archive.  */
6190   curr_bfd = abfd->archive_head;
6191   lst.module_count = 0;
6192   while (curr_bfd != NULL)
6193     {
6194       /* Only true SOM objects count.  */
6195       if (curr_bfd->format == bfd_object
6196           && curr_bfd->xvec->flavour == bfd_target_som_flavour)
6197         lst.module_count++;
6198       curr_bfd = curr_bfd->next;
6199     }
6200   lst.module_limit = lst.module_count;
6201   lst.dir_loc = lst_size;
6202   lst_size += sizeof (struct som_entry) * lst.module_count;
6203
6204   /* We don't support import/export tables, auxiliary headers,
6205      or free lists yet.  Make the linker work a little harder
6206      to make our life easier.  */
6207
6208   lst.export_loc = 0;
6209   lst.export_count = 0;
6210   lst.import_loc = 0;
6211   lst.aux_loc = 0;
6212   lst.aux_size = 0;
6213
6214   /* Count how many symbols we will have on the hash chains and the
6215      size of the associated string table.  */
6216   if (som_bfd_prep_for_ar_write (abfd, &nsyms, &stringsize) == false)
6217     return false;
6218
6219   lst_size += sizeof (struct lst_symbol_record) * nsyms;
6220
6221   /* For the string table.  One day we might actually use this info
6222      to avoid small seeks/reads when reading archives.  */
6223   lst.string_loc = lst_size;
6224   lst.string_size = stringsize;
6225   lst_size += stringsize;
6226
6227   /* SOM ABI says this must be zero.  */
6228   lst.free_list = 0;
6229   lst.file_end = lst_size;
6230
6231   /* Compute the checksum.  Must happen after the entire lst header
6232      has filled in.  */
6233   p = (int *) &lst;
6234   lst.checksum = 0;
6235   for (i = 0; i < sizeof (struct lst_header) / sizeof (int) - 1; i++)
6236     lst.checksum ^= *p++;
6237
6238   sprintf (hdr.ar_name, "/               ");
6239   sprintf (hdr.ar_date, "%ld", bfd_ardata (abfd)->armap_timestamp);
6240   sprintf (hdr.ar_uid, "%ld", (long) getuid ());
6241   sprintf (hdr.ar_gid, "%ld", (long) getgid ());
6242   sprintf (hdr.ar_mode, "%-8o", (unsigned int) statbuf.st_mode);
6243   sprintf (hdr.ar_size, "%-10d", (int) lst_size);
6244   hdr.ar_fmag[0] = '`';
6245   hdr.ar_fmag[1] = '\012';
6246
6247   /* Turn any nulls into spaces.  */
6248   for (i = 0; i < sizeof (struct ar_hdr); i++)
6249     if (((char *) (&hdr))[i] == '\0')
6250       (((char *) (&hdr))[i]) = ' ';
6251
6252   /* Scribble out the ar header.  */
6253   amt = sizeof (struct ar_hdr);
6254   if (bfd_bwrite ((PTR) &hdr, amt, abfd) != amt)
6255     return false;
6256
6257   /* Now scribble out the lst header.  */
6258   amt = sizeof (struct lst_header);
6259   if (bfd_bwrite ((PTR) &lst, amt, abfd) != amt)
6260     return false;
6261
6262   /* Build and write the armap.  */
6263   if (!som_bfd_ar_write_symbol_stuff (abfd, nsyms, stringsize, lst, elength))
6264     return false;
6265
6266   /* Done.  */
6267   return true;
6268 }
6269
6270 /* Free all information we have cached for this BFD.  We can always
6271    read it again later if we need it.  */
6272
6273 static boolean
6274 som_bfd_free_cached_info (abfd)
6275      bfd *abfd;
6276 {
6277   asection *o;
6278
6279   if (bfd_get_format (abfd) != bfd_object)
6280     return true;
6281
6282 #define FREE(x) if (x != NULL) { free (x); x = NULL; }
6283   /* Free the native string and symbol tables.  */
6284   FREE (obj_som_symtab (abfd));
6285   FREE (obj_som_stringtab (abfd));
6286   for (o = abfd->sections; o != (asection *) NULL; o = o->next)
6287     {
6288       /* Free the native relocations.  */
6289       o->reloc_count = (unsigned) -1;
6290       FREE (som_section_data (o)->reloc_stream);
6291       /* Free the generic relocations.  */
6292       FREE (o->relocation);
6293     }
6294 #undef FREE
6295
6296   return true;
6297 }
6298
6299 /* End of miscellaneous support functions.  */
6300
6301 /* Linker support functions.  */
6302
6303 static boolean
6304 som_bfd_link_split_section (abfd, sec)
6305      bfd *abfd ATTRIBUTE_UNUSED;
6306      asection *sec;
6307 {
6308   return (som_is_subspace (sec) && sec->_raw_size > 240000);
6309 }
6310
6311 #define som_close_and_cleanup           som_bfd_free_cached_info
6312
6313 #define som_read_ar_hdr                 _bfd_generic_read_ar_hdr
6314 #define som_openr_next_archived_file    bfd_generic_openr_next_archived_file
6315 #define som_get_elt_at_index            _bfd_generic_get_elt_at_index
6316 #define som_generic_stat_arch_elt       bfd_generic_stat_arch_elt
6317 #define som_truncate_arname             bfd_bsd_truncate_arname
6318 #define som_slurp_extended_name_table   _bfd_slurp_extended_name_table
6319 #define som_construct_extended_name_table \
6320   _bfd_archive_coff_construct_extended_name_table
6321 #define som_update_armap_timestamp      bfd_true
6322 #define som_bfd_print_private_bfd_data  _bfd_generic_bfd_print_private_bfd_data
6323
6324 #define som_get_lineno                  _bfd_nosymbols_get_lineno
6325 #define som_bfd_make_debug_symbol       _bfd_nosymbols_bfd_make_debug_symbol
6326 #define som_read_minisymbols            _bfd_generic_read_minisymbols
6327 #define som_minisymbol_to_symbol        _bfd_generic_minisymbol_to_symbol
6328 #define som_get_section_contents_in_window \
6329   _bfd_generic_get_section_contents_in_window
6330
6331 #define som_bfd_get_relocated_section_contents \
6332  bfd_generic_get_relocated_section_contents
6333 #define som_bfd_relax_section bfd_generic_relax_section
6334 #define som_bfd_link_hash_table_create _bfd_generic_link_hash_table_create
6335 #define som_bfd_link_add_symbols _bfd_generic_link_add_symbols
6336 #define som_bfd_final_link _bfd_generic_final_link
6337
6338 #define som_bfd_gc_sections             bfd_generic_gc_sections
6339 #define som_bfd_merge_sections          bfd_generic_merge_sections
6340
6341 const bfd_target som_vec = {
6342   "som",                        /* name */
6343   bfd_target_som_flavour,
6344   BFD_ENDIAN_BIG,               /* target byte order */
6345   BFD_ENDIAN_BIG,               /* target headers byte order */
6346   (HAS_RELOC | EXEC_P |         /* object flags */
6347    HAS_LINENO | HAS_DEBUG |
6348    HAS_SYMS | HAS_LOCALS | WP_TEXT | D_PAGED | DYNAMIC),
6349   (SEC_CODE | SEC_DATA | SEC_ROM | SEC_HAS_CONTENTS
6350    | SEC_ALLOC | SEC_LOAD | SEC_RELOC),         /* section flags */
6351
6352 /* leading_symbol_char: is the first char of a user symbol
6353    predictable, and if so what is it */
6354   0,
6355   '/',                          /* ar_pad_char */
6356   14,                           /* ar_max_namelen */
6357   bfd_getb64, bfd_getb_signed_64, bfd_putb64,
6358   bfd_getb32, bfd_getb_signed_32, bfd_putb32,
6359   bfd_getb16, bfd_getb_signed_16, bfd_putb16,   /* data */
6360   bfd_getb64, bfd_getb_signed_64, bfd_putb64,
6361   bfd_getb32, bfd_getb_signed_32, bfd_putb32,
6362   bfd_getb16, bfd_getb_signed_16, bfd_putb16,   /* hdrs */
6363   {_bfd_dummy_target,
6364    som_object_p,                /* bfd_check_format */
6365    bfd_generic_archive_p,
6366    _bfd_dummy_target
6367   },
6368   {
6369     bfd_false,
6370     som_mkobject,
6371     _bfd_generic_mkarchive,
6372     bfd_false
6373   },
6374   {
6375     bfd_false,
6376     som_write_object_contents,
6377     _bfd_write_archive_contents,
6378     bfd_false,
6379   },
6380 #undef som
6381
6382   BFD_JUMP_TABLE_GENERIC (som),
6383   BFD_JUMP_TABLE_COPY (som),
6384   BFD_JUMP_TABLE_CORE (_bfd_nocore),
6385   BFD_JUMP_TABLE_ARCHIVE (som),
6386   BFD_JUMP_TABLE_SYMBOLS (som),
6387   BFD_JUMP_TABLE_RELOCS (som),
6388   BFD_JUMP_TABLE_WRITE (som),
6389   BFD_JUMP_TABLE_LINK (som),
6390   BFD_JUMP_TABLE_DYNAMIC (_bfd_nodynamic),
6391
6392   NULL,
6393
6394   (PTR) 0
6395 };
6396
6397 #endif /* HOST_HPPAHPUX || HOST_HPPABSD || HOST_HPPAOSF */