binutils ChangeLog:
[platform/upstream/binutils.git] / bfd / mmo.c
1 /* BFD back-end for mmo objects (MMIX-specific object-format).
2    Copyright 2001, 2002, 2003, 2004
3    Free Software Foundation, Inc.
4    Written by Hans-Peter Nilsson (hp@bitrange.com).
5    Infrastructure and other bits originally copied from srec.c and
6    binary.c.
7
8 This file is part of BFD, the Binary File Descriptor library.
9
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 2 of the License, or
13 (at your option) any later version.
14
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 GNU General Public License for more details.
19
20 You should have received a copy of the GNU General Public License
21 along with this program; if not, write to the Free Software
22 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
23
24 /*
25 SECTION
26         mmo backend
27
28         The mmo object format is used exclusively together with Professor
29         Donald E.@: Knuth's educational 64-bit processor MMIX.  The simulator
30         @command{mmix} which is available at
31         @url{http://www-cs-faculty.stanford.edu/~knuth/programs/mmix.tar.gz}
32         understands this format.  That package also includes a combined
33         assembler and linker called @command{mmixal}.  The mmo format has
34         no advantages feature-wise compared to e.g. ELF.  It is a simple
35         non-relocatable object format with no support for archives or
36         debugging information, except for symbol value information and
37         line numbers (which is not yet implemented in BFD).  See
38         @url{http://www-cs-faculty.stanford.edu/~knuth/mmix.html} for more
39         information about MMIX.  The ELF format is used for intermediate
40         object files in the BFD implementation.
41
42 @c We want to xref the symbol table node.  A feature in "chew"
43 @c requires that "commands" do not contain spaces in the
44 @c arguments.  Hence the hyphen in "Symbol-table".
45 @menu
46 @* File layout::
47 @* Symbol-table::
48 @* mmo section mapping::
49 @end menu
50
51 INODE
52 File layout, Symbol-table, mmo, mmo
53 SUBSECTION
54         File layout
55
56         The mmo file contents is not partitioned into named sections as
57         with e.g.@: ELF.  Memory areas is formed by specifying the
58         location of the data that follows.  Only the memory area
59         @samp{0x0000@dots{}00} to @samp{0x01ff@dots{}ff} is executable, so
60         it is used for code (and constants) and the area
61         @samp{0x2000@dots{}00} to @samp{0x20ff@dots{}ff} is used for
62         writable data.  @xref{mmo section mapping}.
63
64         Contents is entered as 32-bit words, xor:ed over previous
65         contents, always zero-initialized.  A word that starts with the
66         byte @samp{0x98} forms a command called a @samp{lopcode}, where
67         the next byte distinguished between the thirteen lopcodes.  The
68         two remaining bytes, called the @samp{Y} and @samp{Z} fields, or
69         the @samp{YZ} field (a 16-bit big-endian number), are used for
70         various purposes different for each lopcode.  As documented in
71         @url{http://www-cs-faculty.stanford.edu/~knuth/mmixal-intro.ps.gz},
72         the lopcodes are:
73
74         There is provision for specifying ``special data'' of 65536
75         different types.  We use type 80 (decimal), arbitrarily chosen the
76         same as the ELF <<e_machine>> number for MMIX, filling it with
77         section information normally found in ELF objects. @xref{mmo
78         section mapping}.
79
80         @table @code
81         @item lop_quote
82         0x98000001.  The next word is contents, regardless of whether it
83         starts with 0x98 or not.
84
85         @item lop_loc
86         0x9801YYZZ, where @samp{Z} is 1 or 2.  This is a location
87         directive, setting the location for the next data to the next
88         32-bit word (for @math{Z = 1}) or 64-bit word (for @math{Z = 2}),
89         plus @math{Y * 2^56}.  Normally @samp{Y} is 0 for the text segment
90         and 2 for the data segment.
91
92         @item lop_skip
93         0x9802YYZZ.  Increase the current location by @samp{YZ} bytes.
94
95         @item lop_fixo
96         0x9803YYZZ, where @samp{Z} is 1 or 2.  Store the current location
97         as 64 bits into the location pointed to by the next 32-bit
98         (@math{Z = 1}) or 64-bit (@math{Z = 2}) word, plus @math{Y *
99         2^56}.
100
101         @item lop_fixr
102         0x9804YYZZ.  @samp{YZ} is stored into the current location plus
103         @math{2 - 4 * YZ}.
104
105         @item lop_fixrx
106         0x980500ZZ.  @samp{Z} is 16 or 24.  A value @samp{L} derived from
107         the following 32-bit word are used in a manner similar to
108         @samp{YZ} in lop_fixr: it is xor:ed into the current location
109         minus @math{4 * L}.  The first byte of the word is 0 or 1.  If it
110         is 1, then @math{L = (@var{lowest 24 bits of word}) - 2^Z}, if 0,
111         then @math{L = (@var{lowest 24 bits of word})}.
112
113         @item lop_file
114         0x9806YYZZ.  @samp{Y} is the file number, @samp{Z} is count of
115         32-bit words.  Set the file number to @samp{Y} and the line
116         counter to 0.  The next @math{Z * 4} bytes contain the file name,
117         padded with zeros if the count is not a multiple of four.  The
118         same @samp{Y} may occur multiple times, but @samp{Z} must be 0 for
119         all but the first occurrence.
120
121         @item lop_line
122         0x9807YYZZ.  @samp{YZ} is the line number.  Together with
123         lop_file, it forms the source location for the next 32-bit word.
124         Note that for each non-lopcode 32-bit word, line numbers are
125         assumed incremented by one.
126
127         @item lop_spec
128         0x9808YYZZ.  @samp{YZ} is the type number.  Data until the next
129         lopcode other than lop_quote forms special data of type @samp{YZ}.
130         @xref{mmo section mapping}.
131
132         Other types than 80, (or type 80 with a content that does not
133         parse) is stored in sections named <<.MMIX.spec_data.@var{n}>>
134         where @var{n} is the @samp{YZ}-type.  The flags for such a
135         sections say not to allocate or load the data.  The vma is 0.
136         Contents of multiple occurrences of special data @var{n} is
137         concatenated to the data of the previous lop_spec @var{n}s.  The
138         location in data or code at which the lop_spec occurred is lost.
139
140         @item lop_pre
141         0x980901ZZ.  The first lopcode in a file.  The @samp{Z} field forms the
142         length of header information in 32-bit words, where the first word
143         tells the time in seconds since @samp{00:00:00 GMT Jan 1 1970}.
144
145         @item lop_post
146         0x980a00ZZ.  @math{Z > 32}.  This lopcode follows after all
147         content-generating lopcodes in a program.  The @samp{Z} field
148         denotes the value of @samp{rG} at the beginning of the program.
149         The following @math{256 - Z} big-endian 64-bit words are loaded
150         into global registers @samp{$G} @dots{} @samp{$255}.
151
152         @item lop_stab
153         0x980b0000.  The next-to-last lopcode in a program.  Must follow
154         immediately after the lop_post lopcode and its data.  After this
155         lopcode follows all symbols in a compressed format
156         (@pxref{Symbol-table}).
157
158         @item lop_end
159         0x980cYYZZ.  The last lopcode in a program.  It must follow the
160         lop_stab lopcode and its data.  The @samp{YZ} field contains the
161         number of 32-bit words of symbol table information after the
162         preceding lop_stab lopcode.
163         @end table
164
165         Note that the lopcode "fixups"; <<lop_fixr>>, <<lop_fixrx>> and
166         <<lop_fixo>> are not generated by BFD, but are handled.  They are
167         generated by <<mmixal>>.
168
169 EXAMPLE
170         This trivial one-label, one-instruction file:
171
172 | :Main TRAP 1,2,3
173
174         can be represented this way in mmo:
175
176 | 0x98090101 - lop_pre, one 32-bit word with timestamp.
177 | <timestamp>
178 | 0x98010002 - lop_loc, text segment, using a 64-bit address.
179 |              Note that mmixal does not emit this for the file above.
180 | 0x00000000 - Address, high 32 bits.
181 | 0x00000000 - Address, low 32 bits.
182 | 0x98060002 - lop_file, 2 32-bit words for file-name.
183 | 0x74657374 - "test"
184 | 0x2e730000 - ".s\0\0"
185 | 0x98070001 - lop_line, line 1.
186 | 0x00010203 - TRAP 1,2,3
187 | 0x980a00ff - lop_post, setting $255 to 0.
188 | 0x00000000
189 | 0x00000000
190 | 0x980b0000 - lop_stab for ":Main" = 0, serial 1.
191 | 0x203a4040   @xref{Symbol-table}.
192 | 0x10404020
193 | 0x4d206120
194 | 0x69016e00
195 | 0x81000000
196 | 0x980c0005 - lop_end; symbol table contained five 32-bit words.  */
197
198 #include "bfd.h"
199 #include "sysdep.h"
200 #include "libbfd.h"
201 #include "libiberty.h"
202 #include "elf/mmix.h"
203 #include "opcode/mmix.h"
204
205 #define LOP 0x98
206 #define LOP_QUOTE 0
207 #define LOP_LOC 1
208 #define LOP_SKIP 2
209 #define LOP_FIXO 3
210 #define LOP_FIXR 4
211 #define LOP_FIXRX 5
212 #define LOP_FILE 6
213 #define LOP_LINE 7
214 #define LOP_SPEC 8
215 #define LOP_PRE 9
216 #define LOP_POST 10
217 #define LOP_STAB 11
218 #define LOP_END 12
219
220 #define LOP_QUOTE_NEXT ((LOP << 24) | (LOP_QUOTE << 16) | 1)
221 #define SPEC_DATA_SECTION 80
222 #define LOP_SPEC_SECTION \
223  ((LOP << 24) | (LOP_SPEC << 16) | SPEC_DATA_SECTION)
224
225 /* Must be a power of two.  If you change this to be >= 64k, you need a
226    new test-case; the ld test b-loc64k.d touches chunk-size problem areas.  */
227 #define MMO_SEC_CONTENTS_CHUNK_SIZE (1 << 15)
228
229 /* An arbitrary number for the maximum length section name size.  */
230 #define MAX_SECTION_NAME_SIZE (1024 * 1024)
231
232 /* A quite arbitrary number for the maximum length section size.  */
233 #define MAX_ARTIFICIAL_SECTION_SIZE (1024 * 1024 * 1024)
234
235 #define MMO3_WCHAR 0x80
236 #define MMO3_LEFT 0x40
237 #define MMO3_MIDDLE 0x20
238 #define MMO3_RIGHT 0x10
239 #define MMO3_TYPEBITS 0xf
240 #define MMO3_REGQUAL_BITS 0xf
241 #define MMO3_UNDEF 2
242 #define MMO3_DATA 8
243 #define MMO3_SYMBITS 0x2f
244
245 /* Put these everywhere in new code.  */
246 #define FATAL_DEBUG                                             \
247  _bfd_abort (__FILE__, __LINE__,                                \
248              "Internal: Non-debugged code (test-case missing)")
249
250 #define BAD_CASE(x)                             \
251  _bfd_abort (__FILE__, __LINE__,                \
252              "bad case for " #x)
253
254 enum mmo_sym_type { mmo_reg_sym, mmo_undef_sym, mmo_data_sym, mmo_abs_sym};
255
256 /* When scanning the mmo file, a linked list of mmo_symbol
257    structures is built to represent the symbol table (if there is
258    one).  */
259
260 struct mmo_symbol
261   {
262     struct mmo_symbol *next;
263     const char *name;
264     bfd_vma value;
265     enum mmo_sym_type sym_type;
266     unsigned int serno;
267   };
268
269 struct mmo_data_list_struct
270   {
271     struct mmo_data_list_struct *next;
272     bfd_vma where;
273     bfd_size_type size;
274     bfd_size_type allocated_size;
275     bfd_byte data[1];
276   };
277
278 typedef struct mmo_data_list_struct mmo_data_list_type;
279
280 struct mmo_symbol_trie
281   {
282     struct mmo_symbol_trie *left;
283     struct mmo_symbol_trie *right;
284     struct mmo_symbol_trie *middle;
285
286     bfd_byte symchar;
287
288     /* A zero name means there's nothing here.  */
289     struct mmo_symbol sym;
290   };
291
292 /* The mmo tdata information.  */
293
294 struct mmo_data_struct
295   {
296     struct mmo_symbol *symbols;
297     struct mmo_symbol *symtail;
298     asymbol *csymbols;
299
300     /* File representation of time (NULL) when this file was created.  */
301     bfd_byte created[4];
302
303     /* When we're reading bytes recursively, check this occasionally.
304        Also holds write errors.  */
305     bfd_boolean have_error;
306
307     /* Max symbol length that may appear in the lop_stab table.  Note that
308        this table might just hold a subset of symbols for not-really large
309        programs, as it can only be 65536 * 4 bytes large.  */
310     int max_symbol_length;
311
312     /* Here's the symbol we build in lop_stab.  */
313     char *lop_stab_symbol;
314
315     /* Index into lop_stab_symbol for the next character when parsing the
316        symbol information.  */
317     int symbol_position;
318
319     /* When creating arbitrary sections, we need to count section numbers.  */
320     int sec_no;
321
322     /* When writing or reading byte-wise, we need to count the bytes
323        within a 32-bit word.  */
324     int byte_no;
325
326     /* We also need a buffer to hold the bytes we count reading or writing.  */
327     bfd_byte buf[4];
328   };
329
330 typedef struct mmo_data_struct tdata_type;
331
332 struct mmo_section_data_struct
333   {
334     mmo_data_list_type *head;
335     mmo_data_list_type *tail;
336   };
337
338 #define mmo_section_data(sec) \
339   ((struct mmo_section_data_struct *) (sec)->used_by_bfd)
340
341 /* These structures are used in bfd_map_over_sections constructs.  */
342
343 /* Used when writing out sections; all but the register contents section
344    which is stored in reg_section.  */
345 struct mmo_write_sec_info
346   {
347     asection *reg_section;
348     bfd_boolean retval;
349   };
350
351 /* Used when trying to find a section corresponding to addr.  */
352 struct mmo_find_sec_info
353   {
354     asection *sec;
355     bfd_vma addr;
356   };
357
358 static bfd_boolean mmo_bfd_copy_private_bfd_data
359   PARAMS ((bfd *, bfd *));
360 static void mmo_write_section_unless_reg_contents
361  PARAMS ((bfd *, asection *, PTR));
362 static void mmo_find_sec_w_addr
363   PARAMS ((bfd *, asection *, PTR));
364 static void mmo_find_sec_w_addr_grow
365   PARAMS ((bfd *, asection *, PTR));
366 static asection *mmo_make_section
367   PARAMS ((bfd *, const char *));
368 static void mmo_get_symbol_info
369   PARAMS ((bfd *, asymbol *, symbol_info *));
370 static void mmo_print_symbol
371   PARAMS ((bfd *, PTR, asymbol *, bfd_print_symbol_type));
372 static void mmo_init
373   PARAMS ((void));
374 static bfd_boolean mmo_mkobject
375   PARAMS ((bfd *));
376 static bfd_boolean mmo_scan
377   PARAMS ((bfd *));
378 static asection *mmo_decide_section
379   PARAMS ((bfd *, bfd_vma));
380 static asection *mmo_get_generic_spec_data_section
381   PARAMS ((bfd *, int));
382 static asection *mmo_get_spec_section
383   PARAMS ((bfd *, int));
384 static INLINE bfd_byte *mmo_get_loc
385   PARAMS ((asection *, bfd_vma, int));
386 static void mmo_xore_64
387   PARAMS ((asection *, bfd_vma vma, bfd_vma value));
388 static void mmo_xore_32
389   PARAMS ((asection *, bfd_vma vma, unsigned int));
390 static void mmo_xore_16
391   PARAMS ((asection *, bfd_vma vma, unsigned int));
392 static const bfd_target *mmo_object_p
393   PARAMS ((bfd *));
394 static void mmo_map_set_sizes
395   PARAMS ((bfd *, asection *, PTR));
396 static bfd_boolean mmo_get_symbols
397   PARAMS ((bfd *));
398 static bfd_boolean mmo_create_symbol
399   PARAMS ((bfd *, const char *, bfd_vma, enum mmo_sym_type, unsigned int));
400 static bfd_boolean mmo_get_section_contents
401   PARAMS ((bfd *, asection *, PTR, file_ptr, bfd_size_type));
402 static long mmo_get_symtab_upper_bound
403   PARAMS ((bfd *));
404 static long mmo_canonicalize_symtab
405   PARAMS ((bfd *, asymbol **));
406 static void mmo_get_symbol_info
407   PARAMS ((bfd *, asymbol *, symbol_info *));
408 static void mmo_print_symbol
409   PARAMS ((bfd *, PTR, asymbol *, bfd_print_symbol_type));
410 static bfd_boolean mmo_set_section_contents
411   PARAMS ((bfd *, sec_ptr, const PTR, file_ptr, bfd_size_type));
412 static int mmo_sizeof_headers
413   PARAMS ((bfd *, bfd_boolean));
414 static long mmo_get_reloc_upper_bound
415   PARAMS ((bfd *, asection *));
416
417 static bfd_boolean mmo_internal_write_header
418   PARAMS ((bfd *));
419 static bfd_boolean mmo_internal_write_post
420   PARAMS ((bfd *, int, asection *));
421 static bfd_boolean mmo_internal_add_3_sym
422   PARAMS ((bfd *, struct mmo_symbol_trie *, const struct mmo_symbol *));
423 static unsigned int mmo_internal_3_length
424   PARAMS ((bfd *, struct mmo_symbol_trie *));
425 static void mmo_internal_3_dump
426   PARAMS ((bfd *, struct mmo_symbol_trie *));
427 static void mmo_beb128_out
428   PARAMS ((bfd *, int, int));
429 static bfd_boolean mmo_internal_write_section
430   PARAMS ((bfd *, asection *));
431 static void mmo_write_tetra
432   PARAMS ((bfd *, unsigned int));
433 static void mmo_write_tetra_raw
434   PARAMS ((bfd *, unsigned int));
435 static void mmo_write_octa
436   PARAMS ((bfd *, bfd_vma));
437 static void mmo_write_octa_raw
438   PARAMS ((bfd *, bfd_vma));
439 static bfd_boolean mmo_write_chunk
440   PARAMS ((bfd *, const bfd_byte *, unsigned int));
441 static bfd_boolean mmo_flush_chunk
442   PARAMS ((bfd *));
443 static bfd_boolean mmo_write_loc_chunk
444   PARAMS ((bfd *, bfd_vma, const bfd_byte *, unsigned int, bfd_vma *));
445 static bfd_boolean mmo_write_chunk_list
446   PARAMS ((bfd *, mmo_data_list_type *));
447 static bfd_boolean mmo_write_loc_chunk_list
448   PARAMS ((bfd *, mmo_data_list_type *));
449 static bfd_boolean mmo_write_symbols_and_terminator
450   PARAMS ((bfd *));
451 static flagword mmo_sec_flags_from_bfd_flags
452   PARAMS ((flagword));
453 static flagword bfd_sec_flags_from_mmo_flags
454   PARAMS ((flagword));
455 static bfd_byte mmo_get_byte
456   PARAMS ((bfd *));
457 static void mmo_write_byte
458   PARAMS ((bfd *, bfd_byte));
459 static bfd_boolean mmo_new_section_hook
460   PARAMS ((bfd *, asection *));
461 static int mmo_sort_mmo_symbols
462   PARAMS ((const PTR, const PTR));
463 static bfd_boolean mmo_write_object_contents
464   PARAMS ((bfd *));
465 static long mmo_canonicalize_reloc
466   PARAMS ((bfd *, sec_ptr, arelent **, asymbol **));
467
468 /* Global "const" variables initialized once.  Must not depend on
469    particular input or caller; put such things into the bfd or elsewhere.
470    Look ma, no static per-invocation data!  */
471
472 static unsigned
473 char valid_mmo_symbol_character_set[/* A-Z a-z (we assume consecutive
474                                        codes; sorry EBCDIC:ers!).  */
475                                     + 'Z' - 'A' + 1 + 'z' - 'a' + 1
476                                     /* Digits.  */
477                                     + 10
478                                     /* ':' and '_'.  */
479                                     + 1 + 1
480                                     /* Codes higher than 126.  */
481                                     + 256 - 126
482                                     /* Ending zero.  */
483                                     + 1];
484
485
486 /* Get section SECNAME or create one if it doesn't exist.  When creating
487    one, new memory for the name is allocated.  */
488
489 static asection *
490 mmo_make_section (abfd, secname)
491      bfd *abfd;
492      const char *secname;
493 {
494   asection *sec = bfd_get_section_by_name (abfd, secname);
495
496   if (sec == NULL)
497     {
498       char *newsecname = strdup (secname);
499
500       if (newsecname == NULL)
501         {
502           (*_bfd_error_handler)
503             (_("%s: No core to allocate section name %s\n"),
504              bfd_get_filename (abfd), secname);
505           bfd_set_error (bfd_error_system_call);
506           return NULL;
507         }
508       sec = bfd_make_section (abfd, newsecname);
509     }
510
511   return sec;
512 }
513
514 /* Nothing to do, but keep as a placeholder if we need it.
515    Note that state that might differ between bfd:s must not be initialized
516    here, nor must it be static.  Add it to tdata information instead.  */
517
518 static void
519 mmo_init ()
520 {
521   static bfd_boolean inited = FALSE;
522   int i = 0;
523   int j = 0;
524   static const char letters[]
525     = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789:_";
526
527   if (inited)
528     return;
529   inited = TRUE;
530
531   /* Fill in the set of valid symbol characters.  */
532   strcpy (valid_mmo_symbol_character_set, letters);
533   i = strlen (letters);
534
535   for (j = 126; j < 256; j++)
536     valid_mmo_symbol_character_set[i++] = j;
537 }
538
539 /* Check whether an existing file is an mmo file.  */
540
541 static const bfd_target *
542 mmo_object_p (abfd)
543      bfd *abfd;
544 {
545   struct stat statbuf;
546   bfd_byte b[4];
547
548   mmo_init ();
549
550   if (bfd_stat (abfd, &statbuf) < 0
551       || bfd_seek (abfd, (file_ptr) 0, SEEK_SET) != 0
552       || bfd_bread (b, 4, abfd) != 4)
553     goto bad_final;
554
555   /* All mmo files are a multiple of four bytes long.
556      Only recognize version one.  */
557   if ((statbuf.st_size % 4) != 0
558       || b[0] != LOP || b[1] != LOP_PRE || b[2] != 1)
559     goto bad_format;
560
561   /* Get the last 32-bit word.  */
562   if (bfd_seek (abfd, (file_ptr) statbuf.st_size - 4, SEEK_SET) != 0
563       || bfd_bread (b, 4, abfd) != 4)
564     goto bad_final;
565
566   /* Check if the file ends in a lop_end lopcode. */
567   if (b[0] != LOP || b[1] != LOP_END || ! mmo_mkobject (abfd))
568     goto bad_format;
569
570   /* Compute an upper bound on the max symbol length.  Not really
571      important as all of the symbol information can only be 256k.  */
572   abfd->tdata.mmo_data->max_symbol_length = (b[2] * 256 + b[3]) * 4;
573   abfd->tdata.mmo_data->lop_stab_symbol
574     = bfd_malloc (abfd->tdata.mmo_data->max_symbol_length + 1);
575
576   if (abfd->tdata.mmo_data->lop_stab_symbol == NULL)
577     {
578       (*_bfd_error_handler)
579         (_("%s: No core to allocate a symbol %d bytes long\n"),
580          bfd_get_filename (abfd), abfd->tdata.mmo_data->max_symbol_length);
581       goto bad_final;
582     }
583
584   /* Read in everything.  */
585   if (! mmo_scan (abfd))
586     goto bad_format_free;
587
588   if (abfd->symcount > 0)
589     abfd->flags |= HAS_SYMS;
590
591   /* You'll have to tweak this if you want to use this format for other
592      arches (not recommended due to its small-size limitations).  Look at
593      the ELF format for how to make it target-generic.  */
594   if (! bfd_default_set_arch_mach (abfd, bfd_arch_mmix, 0))
595     goto bad_format_free;
596
597   return abfd->xvec;
598
599  bad_format_free:
600   free (abfd->tdata.mmo_data->lop_stab_symbol);
601  bad_format:
602   bfd_set_error (bfd_error_wrong_format);
603  bad_final:
604   return NULL;
605 }
606
607 /* Set up the mmo tdata information.  */
608
609 static bfd_boolean
610 mmo_mkobject (abfd)
611      bfd *abfd;
612 {
613   mmo_init ();
614
615   if (abfd->tdata.mmo_data == NULL)
616     {
617       time_t created;
618
619       /* All fields are zero-initialized, so we don't have to explicitly
620          initialize most.  */
621       tdata_type *tdata = (tdata_type *) bfd_zmalloc (sizeof (tdata_type));
622       if (tdata == NULL)
623         return FALSE;
624
625       created = time (NULL);
626       bfd_put_32 (abfd, created, tdata->created);
627
628       abfd->tdata.mmo_data = tdata;
629     }
630
631   return TRUE;
632 }
633
634 static bfd_boolean
635 mmo_bfd_copy_private_bfd_data (ibfd, obfd)
636      bfd *ibfd;
637      bfd *obfd;
638 {
639   if (bfd_get_flavour (ibfd) != bfd_target_mmo_flavour
640       || bfd_get_flavour (obfd) != bfd_target_mmo_flavour)
641     return TRUE;
642
643   /* Copy the time the copied-from file was created.  If people want the
644      time the file was last *modified*, they have that in the normal file
645      information.  */
646   memcpy (obfd->tdata.mmo_data->created, ibfd->tdata.mmo_data->created,
647           sizeof (obfd->tdata.mmo_data->created));
648   return TRUE;
649 }
650
651 /* Helper functions for mmo_decide_section, used through
652    bfd_map_over_sections.  */
653
654 static void
655 mmo_find_sec_w_addr (abfd, sec, p)
656      bfd *abfd ATTRIBUTE_UNUSED;
657      asection *sec;
658      PTR p;
659 {
660   struct mmo_find_sec_info *infop = (struct mmo_find_sec_info *) p;
661   bfd_vma vma = bfd_get_section_vma (abfd, sec);
662
663   /* Ignore sections that aren't loaded.  */
664   if ((bfd_get_section_flags (abfd, sec) & (SEC_LOAD | SEC_ALLOC))
665       !=  (SEC_LOAD | SEC_ALLOC))
666     return;
667
668   if (infop->addr >= vma && infop->addr < vma + sec->_raw_size)
669     infop->sec = sec;
670 }
671
672 static void
673 mmo_find_sec_w_addr_grow (abfd, sec, p)
674      bfd *abfd ATTRIBUTE_UNUSED;
675      asection *sec;
676      PTR p;
677 {
678   struct mmo_find_sec_info *infop = (struct mmo_find_sec_info *) p;
679   bfd_vma vma = bfd_get_section_vma (abfd, sec);
680
681   /* Ignore sections that aren't loaded.  */
682   if ((bfd_get_section_flags (abfd, sec) & (SEC_LOAD | SEC_ALLOC))
683       !=  (SEC_LOAD | SEC_ALLOC))
684     return;
685
686   if (infop->addr >= vma && infop->addr < vma + MAX_ARTIFICIAL_SECTION_SIZE)
687     infop->sec = sec;
688 }
689
690 /* Find a section that corresponds to a VMA.  Automatically create .text
691    or .data and set current section to it, depending on what vma.  If we
692    can't deduce a section, make one up as ".MMIX.sec.N", where N is an
693    increasing number.  */
694
695 static asection *
696 mmo_decide_section (abfd, vma)
697      bfd *abfd;
698      bfd_vma vma;
699 {
700   asection *sec = NULL;
701   char sec_name[sizeof (".MMIX.sec.") + 20];
702   struct mmo_find_sec_info info;
703
704   info.addr = vma;
705   info.sec = NULL;
706
707   /* First see if there's a section that would match exactly.  */
708   bfd_map_over_sections (abfd, mmo_find_sec_w_addr, &info);
709
710   if (info.sec != NULL)
711     return info.sec;
712
713   /* If there's no such section, try and expand one of the existing ones,
714      up to a limit.  Make sure we have .text and .data before we try that;
715      create them corresponding to expected addresses and set flags to make
716      them match the "loaded and with contents" expectation.  */
717   if ((vma >> 56) == 0)
718     {
719       sec = bfd_make_section_old_way (abfd, MMO_TEXT_SECTION_NAME);
720
721       if (sec == NULL)
722         return NULL;
723
724       if (! sec->user_set_vma)
725         bfd_set_section_vma (abfd, sec, vma);
726       if (! bfd_set_section_flags (abfd, sec,
727                                    bfd_get_section_flags (abfd, sec)
728                                    | SEC_CODE | SEC_LOAD | SEC_ALLOC))
729         return NULL;
730     }
731   else if ((vma >> 56) == 0x20)
732     {
733       sec = bfd_make_section_old_way (abfd, MMO_DATA_SECTION_NAME);
734
735       if (sec == NULL)
736         return NULL;
737
738       if (! sec->user_set_vma)
739         bfd_set_section_vma (abfd, sec, vma);
740       if (! bfd_set_section_flags (abfd, sec,
741                                    bfd_get_section_flags (abfd, sec)
742                                    | SEC_LOAD | SEC_ALLOC))
743         return NULL;
744     }
745
746   bfd_map_over_sections (abfd, mmo_find_sec_w_addr_grow, &info);
747
748   if (info.sec != NULL)
749     return info.sec;
750
751   /* If there's still no suitable section, make a new one.  */
752   sprintf (sec_name, ".MMIX.sec.%d", abfd->tdata.mmo_data->sec_no++);
753   sec = mmo_make_section (abfd, sec_name);
754   if (! sec->user_set_vma)
755     bfd_set_section_vma (abfd, sec, vma);
756
757   if (! bfd_set_section_flags (abfd, sec,
758                                bfd_get_section_flags (abfd, sec)
759                                | SEC_LOAD | SEC_ALLOC))
760     return NULL;
761   return sec;
762 }
763
764 /* Xor in a 64-bit value VALUE at VMA.  */
765
766 static INLINE void
767 mmo_xore_64 (sec, vma, value)
768      asection *sec;
769      bfd_vma vma;
770      bfd_vma value;
771 {
772   bfd_byte *loc = mmo_get_loc (sec, vma, 8);
773   bfd_vma prev = bfd_get_64 (sec->owner, loc);
774
775   value ^= prev;
776   bfd_put_64 (sec->owner, value, loc);
777 }
778
779 /* Xor in a 32-bit value VALUE at VMA.  */
780
781 static INLINE void
782 mmo_xore_32 (sec, vma, value)
783      asection *sec;
784      bfd_vma vma;
785      unsigned int value;
786 {
787   bfd_byte *loc = mmo_get_loc (sec, vma, 4);
788   unsigned int prev = bfd_get_32 (sec->owner, loc);
789
790   value ^= prev;
791   bfd_put_32 (sec->owner, value, loc);
792 }
793
794 /* Xor in a 16-bit value VALUE at VMA.  */
795
796 static INLINE void
797 mmo_xore_16 (sec, vma, value)
798      asection *sec;
799      bfd_vma vma;
800      unsigned int value;
801 {
802   bfd_byte *loc = mmo_get_loc (sec, vma, 2);
803   unsigned int prev = bfd_get_16 (sec->owner, loc);
804
805   value ^= prev;
806   bfd_put_16 (sec->owner, value, loc);
807 }
808
809 /* Write a 32-bit word to output file, no lop_quote generated.  */
810
811 static INLINE void
812 mmo_write_tetra_raw (abfd, value)
813      bfd *abfd;
814      unsigned int value;
815 {
816   bfd_byte buf[4];
817
818   bfd_put_32 (abfd, value, buf);
819
820   if (bfd_bwrite ((PTR) buf, 4, abfd) != 4)
821     abfd->tdata.mmo_data->have_error = TRUE;
822 }
823
824 /* Write a 32-bit word to output file; lop_quote if necessary.  */
825
826 static INLINE void
827 mmo_write_tetra (abfd, value)
828      bfd *abfd;
829      unsigned int value;
830 {
831   if (((value >> 24) & 0xff) == LOP)
832     mmo_write_tetra_raw (abfd, LOP_QUOTE_NEXT);
833
834   mmo_write_tetra_raw (abfd, value);
835 }
836
837 /* Write a 64-bit word to output file, perhaps with lop_quoting.  */
838
839 static INLINE void
840 mmo_write_octa (abfd, value)
841      bfd *abfd;
842      bfd_vma value;
843 {
844   mmo_write_tetra (abfd, (unsigned int) (value >> 32));
845   mmo_write_tetra (abfd, (unsigned int) value);
846 }
847
848 /* Write a 64-bit word to output file, without lop_quoting.  */
849
850 static INLINE void
851 mmo_write_octa_raw (abfd, value)
852      bfd *abfd;
853      bfd_vma value;
854 {
855   mmo_write_tetra_raw (abfd, (unsigned int) (value >> 32));
856   mmo_write_tetra_raw (abfd, (unsigned int) value);
857 }
858
859 /* Write quoted contents.  Intended to be called multiple times in
860    sequence, followed by a call to mmo_flush_chunk.  */
861
862 static INLINE bfd_boolean
863 mmo_write_chunk (abfd, loc, len)
864      bfd *abfd;
865      const bfd_byte *loc;
866      unsigned int len;
867 {
868   bfd_boolean retval = TRUE;
869
870   /* Fill up a tetra from bytes remaining from a previous chunk.  */
871   if (abfd->tdata.mmo_data->byte_no != 0)
872     {
873       while (abfd->tdata.mmo_data->byte_no < 4 && len != 0)
874         {
875           abfd->tdata.mmo_data->buf[abfd->tdata.mmo_data->byte_no++] = *loc++;
876           len--;
877         }
878
879       if (abfd->tdata.mmo_data->byte_no == 4)
880         {
881           mmo_write_tetra (abfd,
882                            bfd_get_32 (abfd, abfd->tdata.mmo_data->buf));
883           abfd->tdata.mmo_data->byte_no = 0;
884         }
885     }
886
887   while (len >= 4)
888     {
889       if (loc[0] == LOP)
890         mmo_write_tetra_raw (abfd, LOP_QUOTE_NEXT);
891
892       retval = (retval
893                 && ! abfd->tdata.mmo_data->have_error
894                 && 4 == bfd_bwrite ((PTR) loc, 4, abfd));
895
896       loc += 4;
897       len -= 4;
898     }
899
900   if (len)
901     {
902       memcpy (abfd->tdata.mmo_data->buf, loc, len);
903       abfd->tdata.mmo_data->byte_no = len;
904     }
905
906   if (! retval)
907     abfd->tdata.mmo_data->have_error = TRUE;
908   return retval;
909 }
910
911 /* Flush remaining bytes, from a previous mmo_write_chunk, zero-padded to
912    4 bytes.  */
913
914 static INLINE bfd_boolean
915 mmo_flush_chunk (abfd)
916      bfd *abfd;
917 {
918   if (abfd->tdata.mmo_data->byte_no != 0)
919     {
920       memset (abfd->tdata.mmo_data->buf + abfd->tdata.mmo_data->byte_no,
921               0, 4 - abfd->tdata.mmo_data->byte_no);
922       mmo_write_tetra (abfd,
923                        bfd_get_32 (abfd, abfd->tdata.mmo_data->buf));
924       abfd->tdata.mmo_data->byte_no = 0;
925     }
926
927   return ! abfd->tdata.mmo_data->have_error;
928 }
929
930 /* Same, but from a list.  */
931
932 static INLINE bfd_boolean
933 mmo_write_chunk_list (abfd, datap)
934      bfd *abfd;
935      mmo_data_list_type *datap;
936 {
937   for (; datap != NULL; datap = datap->next)
938     if (! mmo_write_chunk (abfd, datap->data, datap->size))
939       return FALSE;
940
941   return mmo_flush_chunk (abfd);
942 }
943
944 /* Write a lop_loc and some contents.  A caller needs to call
945    mmo_flush_chunk after calling this function.  The location is only
946    output if different than *LAST_VMAP, which is updated after this call.  */
947
948 static bfd_boolean
949 mmo_write_loc_chunk (abfd, vma, loc, len, last_vmap)
950      bfd *abfd;
951      bfd_vma vma;
952      const bfd_byte *loc;
953      unsigned int len;
954      bfd_vma *last_vmap;
955 {
956   /* Find an initial and trailing section of zero tetras; we don't need to
957      write out zeros.  FIXME: When we do this, we should emit section size
958      and address specifiers, else objcopy can't always perform an identity
959      translation.  Only do this if we *don't* have left-over data from a
960      previous write or the vma of this chunk is *not* the next address,
961      because then data isn't tetrabyte-aligned and we're concatenating to
962      that left-over data.  */
963
964   if (abfd->tdata.mmo_data->byte_no == 0 || vma != *last_vmap)
965     {
966       while (len >= 4 && bfd_get_32 (abfd, loc) == 0)
967         {
968           vma += 4;
969           len -= 4;
970           loc += 4;
971         }
972
973       while (len >= 4 && bfd_get_32 (abfd, loc + len - 4) == 0)
974         len -= 4;
975     }
976
977   /* Only write out the location if it's different than the one the caller
978      (supposedly) previously handled, accounting for omitted leading zeros.  */
979   if (vma != *last_vmap)
980     {
981       /* We might be in the middle of a sequence.  */
982       mmo_flush_chunk (abfd);
983
984       /* We always write the location as 64 bits; no use saving bytes
985          here.  */
986       mmo_write_tetra_raw (abfd, (LOP << 24) | (LOP_LOC << 16) | 2);
987       mmo_write_octa_raw (abfd, vma);
988     }
989
990   /* Update to reflect end of this chunk, with trailing zeros omitted.  */
991   *last_vmap = vma + len;
992
993   return (! abfd->tdata.mmo_data->have_error
994           && mmo_write_chunk (abfd, loc, len));
995 }
996
997 /* Same, but from a list.  */
998
999 static INLINE bfd_boolean
1000 mmo_write_loc_chunk_list (abfd, datap)
1001      bfd *abfd;
1002      mmo_data_list_type *datap;
1003 {
1004   /* Get an address different than the address of the first chunk.  */
1005   bfd_vma last_vma = datap ? datap->where - 1 : 0;
1006
1007   for (; datap != NULL; datap = datap->next)
1008     if (! mmo_write_loc_chunk (abfd, datap->where, datap->data, datap->size,
1009                                &last_vma))
1010       return FALSE;
1011
1012   return mmo_flush_chunk (abfd);
1013 }
1014
1015 /* Make a .MMIX.spec_data.N section.  */
1016
1017 static asection *
1018 mmo_get_generic_spec_data_section (abfd, spec_data_number)
1019      bfd *abfd;
1020      int spec_data_number;
1021 {
1022   asection *sec;
1023   char secname[sizeof (MMIX_OTHER_SPEC_SECTION_PREFIX) + 20]
1024     = MMIX_OTHER_SPEC_SECTION_PREFIX;
1025
1026   sprintf (secname + strlen (MMIX_OTHER_SPEC_SECTION_PREFIX),
1027            "%d", spec_data_number);
1028
1029   sec = mmo_make_section (abfd, secname);
1030
1031   return sec;
1032 }
1033
1034 /* Make a special section for SPEC_DATA_NUMBER.  If it is the one we use
1035    ourselves, parse some of its data to get at the section name.  */
1036
1037 static asection *
1038 mmo_get_spec_section (abfd, spec_data_number)
1039      bfd *abfd;
1040      int spec_data_number;
1041 {
1042   bfd_byte *secname;
1043   asection *sec;
1044   bfd_byte buf[4];
1045   unsigned int secname_length;
1046   unsigned int i;
1047   bfd_vma section_length;
1048   bfd_vma section_vma;
1049   mmo_data_list_type *loc;
1050   flagword flags;
1051   long orig_pos;
1052
1053   /* If this isn't the "special" special data, then make a placeholder
1054      section.  */
1055   if (spec_data_number != SPEC_DATA_SECTION)
1056     return mmo_get_generic_spec_data_section (abfd, spec_data_number);
1057
1058   /* Seek back to this position if there was a format error.  */
1059   orig_pos = bfd_tell (abfd);
1060
1061   /* Read the length (in 32-bit words).  */
1062   if (bfd_bread (buf, 4, abfd) != 4)
1063     goto format_error;
1064
1065   if (buf[0] == LOP)
1066     {
1067       if (buf[1] != LOP_QUOTE)
1068         goto format_error;
1069
1070       if (bfd_bread (buf, 4, abfd) != 4)
1071         goto format_error;
1072     }
1073
1074   /* We don't care to keep the name length accurate.  It's
1075      zero-terminated.  */
1076   secname_length = bfd_get_32 (abfd, buf) * 4;
1077
1078   /* Check section name length for sanity.  */
1079   if (secname_length > MAX_SECTION_NAME_SIZE)
1080     goto format_error;
1081
1082   /* This should be free'd regardless if a section is created.  */
1083   secname = bfd_malloc (secname_length + 1);
1084   secname[secname_length] = 0;
1085
1086   for (i = 0; i < secname_length / 4; i++)
1087     {
1088       if (bfd_bread (secname + i * 4, 4, abfd) != 4)
1089         goto format_error_free;
1090
1091       if (secname[i * 4] == LOP)
1092         {
1093           /* A bit of overkill, but we handle char 0x98 in a section name,
1094              and recognize misparsing.  */
1095           if (secname[i * 4 + 1] != LOP_QUOTE
1096               || bfd_bread (secname + i * 4, 4, abfd) != 4)
1097             /* Whoops.  We thought this was a name, and now we found a
1098                non-lop_quote lopcode before we parsed the whole length of
1099                the name.  Signal end-of-file in the same manner.  */
1100               goto format_error_free;
1101         }
1102     }
1103
1104   /* Get the section flags.  */
1105   if (bfd_bread (buf, 4, abfd) != 4
1106       || (buf[0] == LOP
1107           && (buf[1] != LOP_QUOTE || bfd_bread (buf, 4, abfd) != 4)))
1108     goto format_error_free;
1109
1110   flags = bfd_get_32 (abfd, buf);
1111
1112   /* Get the section length.  */
1113   if (bfd_bread (buf, 4, abfd) != 4
1114       || (buf[0] == LOP
1115           && (buf[1] != LOP_QUOTE || bfd_bread (buf, 4, abfd) != 4)))
1116     goto format_error_free;
1117
1118   section_length = (bfd_vma) bfd_get_32 (abfd, buf) << 32;
1119
1120   /* That's the first, high-part.  Now get the low part.  */
1121
1122   if (bfd_bread (buf, 4, abfd) != 4
1123       || (buf[0] == LOP
1124           && (buf[1] != LOP_QUOTE || bfd_bread (buf, 4, abfd) != 4)))
1125     goto format_error_free;
1126
1127   section_length |= (bfd_vma) bfd_get_32 (abfd, buf);
1128
1129   /* Check the section length for sanity.  */
1130   if (section_length > MAX_ARTIFICIAL_SECTION_SIZE)
1131     goto format_error_free;
1132
1133   /* Get the section VMA.  */
1134   if (bfd_bread (buf, 4, abfd) != 4
1135       || (buf[0] == LOP
1136           && (buf[1] != LOP_QUOTE || bfd_bread (buf, 4, abfd) != 4)))
1137     goto format_error_free;
1138
1139   section_vma = (bfd_vma) bfd_get_32 (abfd, buf) << 32;
1140
1141   /* That's the first, high-part.  Now get the low part.  */
1142   if (bfd_bread (buf, 4, abfd) != 4
1143       || (buf[0] == LOP
1144           && (buf[1] != LOP_QUOTE || bfd_bread (buf, 4, abfd) != 4)))
1145     goto format_error_free;
1146
1147   section_vma |= (bfd_vma) bfd_get_32 (abfd, buf);
1148
1149   sec = mmo_make_section (abfd, secname);
1150   free (secname);
1151   if (sec == NULL)
1152     goto format_error;
1153
1154   /* We allocate a buffer here for the advertised size, with head room for
1155      tetrabyte alignment.  */
1156   loc = bfd_zmalloc (section_length + 3
1157                      + sizeof (struct mmo_data_list_struct));
1158   if (loc == NULL)
1159     goto format_error;
1160
1161   /* Use a TETRA-rounded size for the allocated buffer; we set the
1162      "visible" section size below.  */
1163   loc->size = (section_length + 3) & ~3;
1164
1165   /* Add in the section flags we found to those bfd entered during this
1166      process and set the contents.  */
1167   if (! bfd_set_section_flags (abfd, sec,
1168                                bfd_sec_flags_from_mmo_flags (flags)
1169                                | bfd_get_section_flags (abfd, sec)
1170                                | (section_length != 0 ? SEC_HAS_CONTENTS : 0))
1171       || ! bfd_set_section_size (abfd, sec,
1172                                  sec->_cooked_size + section_length)
1173       /* Set VMA only for the first occurrence.  */
1174       || (! sec->user_set_vma
1175           && ! bfd_set_section_vma  (abfd, sec, section_vma)))
1176     {
1177       /* If we get an error for any of the calls above, signal more than
1178          just a format error for the spec section.  */
1179       return NULL;
1180     }
1181
1182   loc->next = NULL;
1183   if (mmo_section_data (sec)->tail != NULL)
1184     mmo_section_data (sec)->tail->next = loc;
1185   else
1186     mmo_section_data (sec)->head = loc;
1187   mmo_section_data (sec)->tail = loc;
1188   loc->where = section_vma;
1189
1190   return sec;
1191
1192  format_error_free:
1193   free (secname);
1194  format_error:
1195   if (bfd_seek (abfd, orig_pos, SEEK_SET) != 0)
1196     return NULL;
1197
1198   return mmo_get_generic_spec_data_section (abfd, spec_data_number);
1199 }
1200
1201 /* Read a byte, but read from file in multiples of 32-bit words.  */
1202
1203 static bfd_byte
1204 mmo_get_byte (abfd)
1205      bfd *abfd;
1206 {
1207   bfd_byte retval;
1208
1209   if (abfd->tdata.mmo_data->byte_no == 0)
1210     {
1211       if (! abfd->tdata.mmo_data->have_error
1212           && bfd_bread (abfd->tdata.mmo_data->buf, 4, abfd) != 4)
1213         {
1214           abfd->tdata.mmo_data->have_error = TRUE;
1215
1216           /* A value somewhat safe against tripping on some inconsistency
1217              when mopping up after this error.  */
1218           return 128;
1219         }
1220     }
1221
1222   retval = abfd->tdata.mmo_data->buf[abfd->tdata.mmo_data->byte_no];
1223   abfd->tdata.mmo_data->byte_no = (abfd->tdata.mmo_data->byte_no + 1) % 4;
1224
1225   return retval;
1226 }
1227
1228 /* Write a byte, in multiples of 32-bit words.  */
1229
1230 static void
1231 mmo_write_byte (abfd, value)
1232      bfd *abfd;
1233      bfd_byte value;
1234 {
1235   abfd->tdata.mmo_data->buf[(abfd->tdata.mmo_data->byte_no++ % 4)] = value;
1236   if ((abfd->tdata.mmo_data->byte_no % 4) == 0)
1237     {
1238       if (! abfd->tdata.mmo_data->have_error
1239           && bfd_bwrite (abfd->tdata.mmo_data->buf, 4, abfd) != 4)
1240         abfd->tdata.mmo_data->have_error = TRUE;
1241     }
1242 }
1243
1244 /* Create a symbol.  */
1245
1246 static bfd_boolean
1247 mmo_create_symbol (abfd, symname, addr, sym_type, serno)
1248      bfd *abfd;
1249      const char *symname;
1250      bfd_vma addr;
1251      enum mmo_sym_type sym_type;
1252      unsigned int serno;
1253 {
1254   struct mmo_symbol *n;
1255
1256   n = (struct mmo_symbol *) bfd_alloc (abfd, sizeof (struct mmo_symbol));
1257   if (n == NULL)
1258     return FALSE;
1259
1260   n->name = bfd_alloc (abfd, strlen (symname) + 1);
1261   if (n->name == NULL)
1262     return FALSE;
1263
1264   strcpy ((PTR) n->name, symname);
1265
1266   n->value = addr;
1267   n->sym_type = sym_type;
1268   n->serno = serno;
1269
1270   if (abfd->tdata.mmo_data->symbols == NULL)
1271     abfd->tdata.mmo_data->symbols = n;
1272   else
1273     abfd->tdata.mmo_data->symtail->next = n;
1274   abfd->tdata.mmo_data->symtail = n;
1275   n->next = NULL;
1276
1277   ++abfd->symcount;
1278
1279   /* Check that :Main equals the last octa of the .MMIX.reg_contents
1280      section, as it's the one place we're sure to pass when reading a mmo
1281      object.  For written objects, we do it while setting the symbol
1282      table.  */
1283   if (strcmp (symname, MMIX_START_SYMBOL_NAME) == 0
1284       && bfd_get_start_address (abfd) != addr)
1285     {
1286       (*_bfd_error_handler)
1287         (_("%s: invalid mmo file: initialization value for $255 is not `Main'\n"),
1288          bfd_get_filename (abfd));
1289       bfd_set_error (bfd_error_bad_value);
1290       return FALSE;
1291     }
1292
1293   return TRUE;
1294 }
1295
1296 /* Read in symbols.  */
1297
1298 static bfd_boolean
1299 mmo_get_symbols (abfd)
1300      bfd *abfd;
1301 {
1302 /*
1303 INODE
1304 Symbol-table, mmo section mapping, File layout, mmo
1305 SUBSECTION
1306         Symbol table format
1307
1308         From mmixal.w (or really, the generated mmixal.tex) in
1309         @url{http://www-cs-faculty.stanford.edu/~knuth/programs/mmix.tar.gz}):
1310         ``Symbols are stored and retrieved by means of a @samp{ternary
1311         search trie}, following ideas of Bentley and Sedgewick. (See
1312         ACM--SIAM Symp.@: on Discrete Algorithms @samp{8} (1997), 360--369;
1313         R.@:Sedgewick, @samp{Algorithms in C} (Reading, Mass.@:
1314         Addison--Wesley, 1998), @samp{15.4}.)  Each trie node stores a
1315         character, and there are branches to subtries for the cases where
1316         a given character is less than, equal to, or greater than the
1317         character in the trie.  There also is a pointer to a symbol table
1318         entry if a symbol ends at the current node.''
1319
1320         So it's a tree encoded as a stream of bytes.  The stream of bytes
1321         acts on a single virtual global symbol, adding and removing
1322         characters and signalling complete symbol points.  Here, we read
1323         the stream and create symbols at the completion points.
1324
1325         First, there's a control byte <<m>>.  If any of the listed bits
1326         in <<m>> is nonzero, we execute what stands at the right, in
1327         the listed order:
1328
1329 | (MMO3_LEFT)
1330 | 0x40 - Traverse left trie.
1331 |        (Read a new command byte and recurse.)
1332 |
1333 | (MMO3_SYMBITS)
1334 | 0x2f - Read the next byte as a character and store it in the
1335 |        current character position; increment character position.
1336 |        Test the bits of <<m>>:
1337 |
1338 |        (MMO3_WCHAR)
1339 |        0x80 - The character is 16-bit (so read another byte,
1340 |               merge into current character.
1341 |
1342 |        (MMO3_TYPEBITS)
1343 |        0xf  - We have a complete symbol; parse the type, value
1344 |               and serial number and do what should be done
1345 |               with a symbol.  The type and length information
1346 |               is in j = (m & 0xf).
1347 |
1348 |               (MMO3_REGQUAL_BITS)
1349 |               j == 0xf: A register variable.  The following
1350 |                         byte tells which register.
1351 |               j <= 8:   An absolute symbol.  Read j bytes as the
1352 |                         big-endian number the symbol equals.
1353 |                         A j = 2 with two zero bytes denotes an
1354 |                         unknown symbol.
1355 |               j > 8:    As with j <= 8, but add (0x20 << 56)
1356 |                         to the value in the following j - 8
1357 |                         bytes.
1358 |
1359 |               Then comes the serial number, as a variant of
1360 |               uleb128, but better named ubeb128:
1361 |               Read bytes and shift the previous value left 7
1362 |               (multiply by 128).  Add in the new byte, repeat
1363 |               until a byte has bit 7 set.  The serial number
1364 |               is the computed value minus 128.
1365 |
1366 |        (MMO3_MIDDLE)
1367 |        0x20 - Traverse middle trie.  (Read a new command byte
1368 |               and recurse.)  Decrement character position.
1369 |
1370 | (MMO3_RIGHT)
1371 | 0x10 - Traverse right trie.  (Read a new command byte and
1372 |        recurse.)
1373
1374         Let's look again at the <<lop_stab>> for the trivial file
1375         (@pxref{File layout}).
1376
1377 | 0x980b0000 - lop_stab for ":Main" = 0, serial 1.
1378 | 0x203a4040
1379 | 0x10404020
1380 | 0x4d206120
1381 | 0x69016e00
1382 | 0x81000000
1383
1384         This forms the trivial trie (note that the path between ``:'' and
1385         ``M'' is redundant):
1386
1387 | 203a     ":"
1388 | 40       /
1389 | 40      /
1390 | 10      \
1391 | 40      /
1392 | 40     /
1393 | 204d  "M"
1394 | 2061  "a"
1395 | 2069  "i"
1396 | 016e  "n" is the last character in a full symbol, and
1397 |       with a value represented in one byte.
1398 | 00    The value is 0.
1399 | 81    The serial number is 1.  */
1400
1401   bfd_byte m = mmo_get_byte (abfd);
1402
1403   /* Check first if we have a bad hair day.  */
1404   if (abfd->tdata.mmo_data->have_error)
1405     return FALSE;
1406
1407   if (m & MMO3_LEFT)
1408     /* Traverse left trie. */
1409     mmo_get_symbols (abfd);
1410
1411   if (m & MMO3_SYMBITS)
1412     {
1413       bfd_byte c = mmo_get_byte (abfd);
1414       bfd_byte j = m & MMO3_TYPEBITS;
1415       bfd_vma addr = 0;
1416       enum mmo_sym_type sym_type;
1417       unsigned int serno = 0;
1418       bfd_byte k;
1419
1420       if (m & MMO3_WCHAR)
1421         {
1422           bfd_byte c2 = mmo_get_byte (abfd);
1423
1424           /* A two-byte character.  We can't grok this, but neither can
1425              mmotype, for other cases than the second byte being zero.  */
1426
1427           if (c != 0)
1428             {
1429               abfd->tdata.mmo_data->lop_stab_symbol
1430                 [abfd->tdata.mmo_data->symbol_position] = 0;
1431
1432               (*_bfd_error_handler)
1433                 (_("%s: unsupported wide character sequence\
1434  0x%02X 0x%02X after symbol name starting with `%s'\n"),
1435                  bfd_get_filename (abfd), c, c2,
1436                  abfd->tdata.mmo_data->lop_stab_symbol);
1437               bfd_set_error (bfd_error_bad_value);
1438               abfd->tdata.mmo_data->have_error = TRUE;
1439               return FALSE;
1440             }
1441           else
1442             c = c2;
1443         }
1444
1445       abfd->tdata.mmo_data->lop_stab_symbol[abfd->tdata.mmo_data->symbol_position++] = c;
1446       abfd->tdata.mmo_data->lop_stab_symbol[abfd->tdata.mmo_data->symbol_position] = 0;
1447
1448       if (j & MMO3_REGQUAL_BITS)
1449         {
1450           if (j == MMO3_REGQUAL_BITS)
1451             {
1452               sym_type = mmo_reg_sym;
1453               addr = mmo_get_byte (abfd);
1454             }
1455           else if (j <= 8)
1456             {
1457               unsigned int i;
1458
1459               for (i = 0; i < j; i++)
1460                 addr = (addr << 8) + mmo_get_byte (abfd);
1461
1462               if (addr == 0 && j == MMO3_UNDEF)
1463                 sym_type = mmo_undef_sym;
1464               else
1465                 sym_type = mmo_abs_sym;
1466             }
1467           else
1468             {
1469               unsigned int i;
1470
1471               for (i = MMO3_DATA; i < j; i++)
1472                 addr = (addr << 8) + mmo_get_byte (abfd);
1473
1474               addr += (bfd_vma) 0x20 << 56;
1475               sym_type = mmo_data_sym;
1476             }
1477
1478           /* Get the serial number.  */
1479           do
1480             {
1481               k = mmo_get_byte (abfd);
1482               serno = (serno << 7) + k;
1483             }
1484           while (k < 128);
1485           serno -= 128;
1486
1487           /* Got it.  Now enter it.  Skip a leading ":".  */
1488           if (! abfd->tdata.mmo_data->have_error
1489               && ! mmo_create_symbol (abfd,
1490                                       abfd->tdata.mmo_data->lop_stab_symbol
1491                                       + 1,
1492                                       addr, sym_type, serno))
1493             abfd->tdata.mmo_data->have_error = TRUE;
1494         }
1495
1496       if (m & MMO3_MIDDLE)
1497         /* Traverse middle trie. */
1498         mmo_get_symbols (abfd);
1499
1500       abfd->tdata.mmo_data->symbol_position--;
1501     }
1502
1503   if (m & MMO3_RIGHT)
1504     /* Traverse right trie.  */
1505     mmo_get_symbols (abfd);
1506
1507   return ! abfd->tdata.mmo_data->have_error;
1508 }
1509
1510 /* Get the location of memory area [VMA..VMA + SIZE - 1], which we think
1511    is in section SEC.  Adjust and reallocate zero-initialized contents.
1512    If there's new contents, allocate to the next multiple of
1513    MMO_SEC_CONTENTS_CHUNK_SIZE.  */
1514
1515 static INLINE bfd_byte *
1516 mmo_get_loc (sec, vma, size)
1517      asection *sec;
1518      bfd_vma vma;
1519      int size;
1520 {
1521   bfd_size_type allocated_size;
1522   struct mmo_section_data_struct *sdatap = mmo_section_data (sec);
1523   struct mmo_data_list_struct *datap = sdatap->head;
1524   struct mmo_data_list_struct *entry;
1525
1526   /* First search the list to see if we have the requested chunk in one
1527      piece, or perhaps if we have a suitable chunk with room to fit.  */
1528   for (; datap != NULL; datap = datap->next)
1529     {
1530       if (datap->where <= vma
1531           && datap->where + datap->size >= vma + size)
1532         return datap->data + vma - datap->where;
1533       else if (datap->where <= vma
1534                && datap->where + datap->allocated_size >= vma + size
1535                /* Only munch on the "allocated size" if it does not
1536                   overlap the next chunk.  */
1537                && (datap->next == NULL || datap->next->where >= vma + size))
1538         {
1539           /* There was room allocated, but the size wasn't set to include
1540              it.  Do that now.  */
1541           datap->size += (vma + size) - (datap->where + datap->size);
1542
1543           /* Update the section size.  This happens only if we update the
1544              32-bit-aligned chunk size.  Callers that have
1545              non-32-bit-aligned sections should do all allocation and
1546              size-setting by themselves or at least set the section size
1547              after the last allocating call to this function.  */
1548           if (vma + size > sec->vma + sec->_raw_size)
1549             sec->_raw_size += (vma + size) - (sec->vma + sec->_raw_size);
1550
1551           return datap->data + vma - datap->where;
1552         }
1553     }
1554
1555   /* Not found; allocate a new block.  First check in case we get a
1556      request for a size split up over several blocks; we'll have to return
1557      NULL for those cases, requesting the caller to split up the request.
1558      Requests with an address aligned on MMO_SEC_CONTENTS_CHUNK_SIZE bytes and
1559      for no more than MMO_SEC_CONTENTS_CHUNK_SIZE will always get resolved.  */
1560
1561   for (datap = sdatap->head; datap != NULL; datap = datap->next)
1562     if ((datap->where <= vma && datap->where + datap->size > vma)
1563         || (datap->where < vma + size
1564             && datap->where + datap->size >= vma + size))
1565       return NULL;
1566
1567   allocated_size
1568     = (size + MMO_SEC_CONTENTS_CHUNK_SIZE - 1) & ~(MMO_SEC_CONTENTS_CHUNK_SIZE - 1);
1569   entry = (mmo_data_list_type *)
1570     bfd_zalloc (sec->owner, sizeof (mmo_data_list_type) + allocated_size);
1571   if (entry == NULL)
1572     return NULL;
1573   entry->where = vma;
1574   entry->size = size;
1575   entry->allocated_size = allocated_size;
1576
1577   datap = sdatap->head;
1578
1579   /* Sort the records by address.  Optimize for the common case of adding
1580      a record to the end of the list.  */
1581   if (sdatap->tail != NULL && entry->where >= sdatap->tail->where)
1582     {
1583       sdatap->tail->next = entry;
1584       entry->next = NULL;
1585       sdatap->tail = entry;
1586     }
1587   else
1588     {
1589       mmo_data_list_type **look;
1590       for (look = &sdatap->head;
1591            *look != NULL && (*look)->where < entry->where;
1592            look = &(*look)->next)
1593         ;
1594       entry->next = *look;
1595       *look = entry;
1596       if (entry->next == NULL)
1597         {
1598           sdatap->tail = entry;
1599
1600           /* We get here for the first time (at other times too) for this
1601              section.  Say we have contents.  */
1602           if (! bfd_set_section_flags (sec->owner, sec,
1603                                        bfd_get_section_flags (sec->owner, sec)
1604                                        | SEC_HAS_CONTENTS))
1605             return NULL;
1606         }
1607     }
1608
1609   /* Update the section size.  This happens only when we add contents and
1610      re-size as we go.  The section size will then be aligned to 32 bits.  */
1611   if (vma + size > sec->vma + sec->_raw_size)
1612     sec->_raw_size += (vma + size) - (sec->vma + sec->_raw_size);
1613   return entry->data;
1614 }
1615
1616 /* Set sizes once we've read in all sections.  */
1617
1618 static void
1619 mmo_map_set_sizes (abfd, sec, ignored)
1620      bfd *abfd ATTRIBUTE_UNUSED;
1621      asection *sec;
1622      PTR ignored ATTRIBUTE_UNUSED;
1623 {
1624   sec->_cooked_size = sec->_raw_size;
1625   sec->lma = sec->vma;
1626 }
1627
1628 /* Read the mmo file and turn it into sections.  */
1629
1630 static bfd_boolean
1631 mmo_scan (abfd)
1632      bfd *abfd;
1633 {
1634   unsigned int i;
1635   unsigned int lineno = 1;
1636   bfd_boolean error = FALSE;
1637   bfd_vma vma = 0;
1638   asection *sec = bfd_make_section_old_way (abfd, MMO_TEXT_SECTION_NAME);
1639   asection *non_spec_sec = NULL;
1640   bfd_vma non_spec_vma = 0;
1641   char *current_filename = NULL;
1642   bfd_size_type nbytes_read = 0;
1643   /* Buffer with room to read a 64-bit value.  */
1644   bfd_byte buf[8];
1645   long stab_loc = -1;
1646   char *file_names[256];
1647
1648   memset (file_names, 0, sizeof (file_names));
1649
1650   if (bfd_seek (abfd, (file_ptr) 0, SEEK_SET) != 0)
1651     goto error_return;
1652
1653   while ((nbytes_read = bfd_bread (buf, 4, abfd)) == 4)
1654     {
1655       if (buf[0] == LOP)
1656         {
1657           unsigned int y = bfd_get_8 (abfd, buf + 2);
1658           unsigned int z = bfd_get_8 (abfd, buf + 3);
1659
1660           /* Change back to the original section for lopcodes other
1661              than LOP_QUOTE that comes after a LOP_SPEC.  */
1662           if ((buf[1] != LOP_QUOTE || y != 0 || z != 1)
1663               && non_spec_sec != NULL)
1664             {
1665               sec = non_spec_sec;
1666               vma = non_spec_vma;
1667               non_spec_sec = NULL;
1668             }
1669
1670           switch (buf[1])
1671             {
1672             default:
1673               (*_bfd_error_handler)
1674                 (_("%s: invalid mmo file: unsupported lopcode `%d'\n"),
1675                  bfd_get_filename (abfd), buf[1]);
1676               bfd_set_error (bfd_error_bad_value);
1677               goto error_return;
1678
1679             case LOP_QUOTE:
1680               /* Quote the next 32-bit word.  */
1681               if (y != 0 || z != 1)
1682                 {
1683                   (*_bfd_error_handler)
1684                     (_("%s: invalid mmo file: expected YZ = 1 got YZ = %d for lop_quote\n"),
1685                      bfd_get_filename (abfd), y*256+z);
1686                   bfd_set_error (bfd_error_bad_value);
1687                   goto error_return;
1688                 }
1689               if (bfd_bread (buf, 4, abfd) != 4)
1690                 goto error_return;
1691
1692               mmo_xore_32 (sec, vma, bfd_get_32 (abfd, buf));
1693               vma += 4;
1694               vma &= ~3;
1695               lineno++;
1696               break;
1697
1698             case LOP_LOC:
1699               /* Set vma (and section).  */
1700               vma = (bfd_vma) y << 56;
1701               if (z == 1)
1702                 {
1703                   /* Get a 32-bit value.  */
1704                   if (bfd_bread (buf, 4, abfd) != 4)
1705                     goto error_return;
1706
1707                   vma += bfd_get_32 (abfd, buf);
1708                 }
1709               else if (z == 2)
1710                 {
1711                   /* Get a 64-bit value.  */
1712                   if (bfd_bread (buf, 8, abfd) != 8)
1713                     goto error_return;
1714
1715                   vma += bfd_get_64 (abfd, buf);
1716                 }
1717               else
1718                 {
1719                   (*_bfd_error_handler)
1720                     (_("%s: invalid mmo file: expected z = 1 or z = 2, got z = %d for lop_loc\n"),
1721                      bfd_get_filename (abfd), z);
1722                   bfd_set_error (bfd_error_bad_value);
1723                   goto error_return;
1724                 }
1725
1726               sec = mmo_decide_section (abfd, vma);
1727               if (sec == NULL)
1728                 goto error_return;
1729               break;
1730
1731             case LOP_SKIP:
1732               /* Move forward within the same section.  */
1733               vma += y * 256 + z;
1734
1735               sec = mmo_decide_section (abfd, vma);
1736               if (sec == NULL)
1737                 goto error_return;
1738               break;
1739
1740             case LOP_FIXO:
1741               /* A fixup: Store the current vma somewhere.  Position using
1742                  same format as LOP_LOC.  */
1743               {
1744                 bfd_vma p = (bfd_vma) y << 56;
1745                 asection *fixosec;
1746
1747                 if (z == 1)
1748                   {
1749                     /* Get a 32-bit value.  */
1750                     if (bfd_bread (buf, 4, abfd) != 4)
1751                       goto error_return;
1752
1753                     p += bfd_get_32 (abfd, buf);
1754                   }
1755                 else if (z == 2)
1756                   {
1757                     /* Get a 64-bit value.  */
1758                     if (bfd_bread (buf, 8, abfd) != 8)
1759                       goto error_return;
1760
1761                     p += bfd_get_64 (abfd, buf);
1762                   }
1763                 else
1764                   {
1765                     (*_bfd_error_handler)
1766                       (_("%s: invalid mmo file: expected z = 1 or z = 2, got z = %d for lop_fixo\n"),
1767                        bfd_get_filename (abfd), z);
1768                     bfd_set_error (bfd_error_bad_value);
1769                     goto error_return;
1770                   }
1771
1772                 /* The section where we store this address might be a
1773                    different one than the current section.  */
1774                 fixosec = mmo_decide_section (abfd, p);
1775                 if (fixosec == NULL)
1776                   goto error_return;
1777                 mmo_xore_64 (fixosec, p, vma);
1778               }
1779             break;
1780
1781             case LOP_FIXR:
1782               /* A fixup: Store YZ of this lopcode into YZ at vma - 4 * yz.  */
1783               {
1784                 unsigned int yz = (y * 256 + z);
1785                 bfd_vma p = vma + 2 - 4 * yz;
1786                 asection *fixrsec = mmo_decide_section (abfd, p);
1787                 if (fixrsec == NULL)
1788                   goto error_return;
1789                 mmo_xore_16 (fixrsec, p, yz);
1790               }
1791             break;
1792
1793             case LOP_FIXRX:
1794               /* A fixup, similar to lop_fixr, but taking larger numbers
1795                  and can change branches into the opposite direction
1796                  (gasp!).  */
1797               {
1798                 bfd_vma delta;
1799                 bfd_vma p;
1800                 asection *fixrsec;
1801
1802                 if (y != 0)
1803                   {
1804                     (*_bfd_error_handler)
1805                       (_("%s: invalid mmo file: expected y = 0, got y = %d for lop_fixrx\n"),
1806                        bfd_get_filename (abfd), y);
1807                     bfd_set_error (bfd_error_bad_value);
1808                     goto error_return;
1809                   }
1810
1811                 if (z != 16 && z != 24)
1812                   {
1813                     (*_bfd_error_handler)
1814                       (_("%s: invalid mmo file: expected z = 16 or z = 24, got z = %d for lop_fixrx\n"),
1815                        bfd_get_filename (abfd), z);
1816                     bfd_set_error (bfd_error_bad_value);
1817                     goto error_return;
1818                   }
1819
1820                 /* Get the next 32-bit value.  */
1821                 if (bfd_bread (buf, 4, abfd) != 4)
1822                   goto error_return;
1823
1824                 delta = bfd_get_32 (abfd, buf);
1825
1826                 /* Do an, ehm, involved calculation for the location of
1827                    the fixup.  See mmixal documentation for a verbose
1828                    explanation.  We follow it verbosely here for the
1829                    readers delight.  */
1830                 if (buf[0] == 0)
1831                   p = vma - 4 * delta;
1832                 else if (buf[0] == 1)
1833                   p = vma - 4 * ((delta & 0xffffff) - (1 << z));
1834                 else
1835                   {
1836                     (*_bfd_error_handler)
1837                       (_("%s: invalid mmo file: leading byte of operand word must be 0 or 1, got %d for lop_fixrx\n"),
1838                        bfd_get_filename (abfd), buf[0]);
1839                     bfd_set_error (bfd_error_bad_value);
1840                     goto error_return;
1841                   }
1842
1843                 fixrsec = mmo_decide_section (abfd, vma);
1844                 if (fixrsec == NULL)
1845                   goto error_return;
1846                 mmo_xore_32 (fixrsec, p, delta);
1847               }
1848             break;
1849
1850             case LOP_FILE:
1851               /* Set current file and perhaps the file name.  Reset line
1852                  number.  */
1853               if (z != 0)
1854                 {
1855                   char *fname = bfd_malloc (z * 4 + 1);
1856
1857                   if (fname == NULL)
1858                     {
1859                       (*_bfd_error_handler)
1860                         (_("%s: cannot allocate file name for file number %d, %d bytes\n"),
1861                          bfd_get_filename (abfd), y, z * 4 + 1);
1862                       bfd_set_error (bfd_error_system_call);
1863                       goto error_return;
1864                     }
1865
1866                   fname[z * 4] = 0;
1867
1868                   for (i = 0; i < z; i++)
1869                     {
1870                       if (bfd_bread (fname + i * 4, 4, abfd) != 4)
1871                         {
1872                           free (fname);
1873                           goto error_return;
1874                         }
1875                     }
1876
1877                   if (file_names[y] != NULL)
1878                     {
1879                       (*_bfd_error_handler)
1880                         (_("%s: invalid mmo file: file number %d `%s',\
1881  was already entered as `%s'\n"),
1882                          bfd_get_filename (abfd), y, fname, file_names[y]);
1883                       bfd_set_error (bfd_error_bad_value);
1884                       goto error_return;
1885                     }
1886
1887                   file_names[y] = fname;
1888                 }
1889
1890               if (file_names[y] == NULL)
1891                 {
1892                   (*_bfd_error_handler)
1893                     (_("%s: invalid mmo file: file name for number %d\
1894  was not specified before use\n"),
1895                      bfd_get_filename (abfd), y);
1896                   bfd_set_error (bfd_error_bad_value);
1897                   goto error_return;
1898                 }
1899
1900               current_filename = file_names[y];
1901               lineno = 0;
1902               break;
1903
1904             case LOP_LINE:
1905               /* Set line number.  */
1906               lineno = y * 256 + z;
1907               /* FIXME: Create a sequence of mmo-specific line number
1908                  entries for each section, then translate into canonical
1909                  format.  */
1910               break;
1911
1912             case LOP_SPEC:
1913               /* Special data follows until the next non-lop_quote
1914                  lopcode.  */
1915               non_spec_sec = sec;
1916               non_spec_vma = vma;
1917               sec = mmo_get_spec_section (abfd, y * 256 + z);
1918               if (sec == NULL)
1919                 goto error_return;
1920
1921               vma = sec->vma;
1922               break;
1923
1924             case LOP_PRE:
1925               {
1926                 /* We ignore header information, except we read in the
1927                    creation time from the first 32-bit word with the time
1928                    in seconds since era.  */
1929                 if (z >= 1
1930                     && bfd_bread (abfd->tdata.mmo_data->created, 4,
1931                                  abfd) != 4)
1932                   goto error_return;
1933
1934                 for (i = 1; i < z; i++)
1935                   if (bfd_bread (buf, 4, abfd) != 4)
1936                     goto error_return;
1937               }
1938               break;
1939
1940             case LOP_POST:
1941               /* This tells of the contents of registers $Z..$255 at
1942                  startup.  We make a section out of it, with VMA = Z * 8,
1943                  but only if Z != 255 or the contents is non-zero.  */
1944               {
1945                 asection *rsec;
1946                 bfd_byte *loc;
1947                 bfd_vma first_octa;
1948                 bfd_vma startaddr_octa;
1949
1950                 /* Read first octaword outside loop to simplify logic when
1951                    excluding the Z == 255, octa == 0 case.  */
1952                 if (bfd_bread (buf, 8, abfd) != 8)
1953                   goto error_return;
1954
1955                 first_octa = bfd_get_64 (abfd, buf);
1956
1957                 /* Don't emit contents for the trivial case which is
1958                    always present; $255 pointing to Main.  */
1959                 if (z != 255)
1960                   {
1961                     rsec
1962                       = bfd_make_section_old_way (abfd,
1963                                                   MMIX_REG_CONTENTS_SECTION_NAME);
1964                     rsec->vma = z * 8;
1965                     loc = mmo_get_loc (rsec, z * 8, (255 - z) * 8);
1966                     bfd_put_64 (abfd, first_octa, loc);
1967
1968                     for (i = z + 1; i < 255; i++)
1969                       {
1970                         if (bfd_bread (loc + (i - z) * 8, 8, abfd) != 8)
1971                           goto error_return;
1972                       }
1973
1974                     /* Read out the last octabyte, and use it to set the
1975                        start address.  */
1976                     if (bfd_bread (buf, 8, abfd) != 8)
1977                       goto error_return;
1978
1979                     startaddr_octa = bfd_get_64 (abfd, buf);
1980                   }
1981                 else
1982                   startaddr_octa = first_octa;
1983
1984                 if (! bfd_set_start_address (abfd, startaddr_octa))
1985                   {
1986                     /* Currently this can't fail, but this should handle
1987                        future failures.  */
1988                     bfd_set_error (bfd_error_bad_value);
1989                     goto error_return;
1990                   }
1991               }
1992               break;
1993
1994             case LOP_STAB:
1995               /* We read in the symbols now, not later.  */
1996               if (y != 0 || z != 0)
1997                 {
1998                   (*_bfd_error_handler)
1999                     (_("%s: invalid mmo file: fields y and z of lop_stab\
2000  non-zero, y: %d, z: %d\n"),
2001                      bfd_get_filename (abfd), y, z);
2002                   bfd_set_error (bfd_error_bad_value);
2003                   goto error_return;
2004                 }
2005
2006               /* Save the location, so we can check that YZ in the LOP_END
2007                  is correct.  */
2008               stab_loc = bfd_tell (abfd);
2009
2010               /* It's not said that an MMO can be without symbols (though
2011                  mmixal will refuse to assemble files without Main), but
2012                  it seems it would still be a valid mmo-file, so allow it.
2013                  We detect the absence of a symbol area in that the upper
2014                  limit is computed (from the lop_end YZ field) as 0.
2015                  Don't call mmo_get_symbols; it can only detect the end of
2016                  a valid symbol trie, not the absence of one.  */
2017               if (abfd->tdata.mmo_data->max_symbol_length != 0
2018                   && ! mmo_get_symbols (abfd))
2019                 goto error_return;
2020               break;
2021
2022             case LOP_END:
2023               {
2024                 /* This must be the last 32-bit word in an mmo file.
2025                    Let's find out.  */
2026                 struct stat statbuf;
2027                 long curpos = bfd_tell (abfd);
2028
2029                 if (bfd_stat (abfd, &statbuf) < 0)
2030                   goto error_return;
2031
2032                 if (statbuf.st_size != curpos)
2033                   {
2034                     (*_bfd_error_handler)
2035                       (_("%s: invalid mmo file: lop_end not last item in\
2036  file\n"),
2037                        bfd_get_filename (abfd));
2038                     bfd_set_error (bfd_error_bad_value);
2039                     goto error_return;
2040                   }
2041
2042                 /* Check that the YZ field is right.  Subtract the size of
2043                    this LOP_END in the calculation; YZ does not include
2044                    it.  */
2045                 if ((long) (y * 256 + z) * 4 != (curpos - stab_loc) - 4)
2046                   {
2047                     (*_bfd_error_handler)
2048                       (_("%s: invalid mmo file: YZ of lop_end (%ld)\
2049  not equal to the number of tetras to the preceding lop_stab (%ld)\n"),
2050                        bfd_get_filename (abfd), (long) (y * 256 + z),
2051                        (curpos - stab_loc - 4)/4);
2052                     bfd_set_error (bfd_error_bad_value);
2053                     goto error_return;
2054                   }
2055
2056                 bfd_map_over_sections (abfd, mmo_map_set_sizes, NULL);
2057                 goto done;
2058               }
2059             }
2060         }
2061       else
2062         {
2063           /* This wasn't a lopcode, so store it in the current section.  */
2064           mmo_xore_32 (sec, vma & ~3, bfd_get_32 (abfd, buf));
2065           vma += 4;
2066           vma &= ~3;
2067           lineno++;
2068         }
2069     }
2070
2071   /* We know this file is a multiple of four bytes (checked in
2072      mmo_object_p), so if we got something other than 0, this was a bad
2073      file (although it's more likely we'll get 0 in that case too).
2074      If we got end-of-file, then there was no lop_stab, so the file has
2075      invalid format.  */
2076
2077   if (nbytes_read != 0)
2078     bfd_set_error (bfd_error_system_call);
2079   else
2080     bfd_set_error (bfd_error_bad_value);
2081
2082  error_return:
2083   error = TRUE;
2084  done:
2085   /* Mark the .text and .data section with their normal attribute if they
2086      contain anything.  This is not redundant wrt. mmo_decide_section,
2087      since that code might never execute, and conversely the alloc+code
2088      section flags must be set then.  */
2089   sec = bfd_get_section_by_name (abfd, MMO_TEXT_SECTION_NAME);
2090   if (sec != NULL
2091       && (bfd_get_section_flags (abfd, sec) & SEC_HAS_CONTENTS)
2092       && ! bfd_set_section_flags (abfd, sec,
2093                                   bfd_get_section_flags (abfd, sec)
2094                                   | SEC_ALLOC | SEC_LOAD | SEC_CODE))
2095     error = TRUE;
2096
2097   sec = bfd_get_section_by_name (abfd, MMO_DATA_SECTION_NAME);
2098   if (sec != NULL
2099       && (bfd_get_section_flags (abfd, sec) & SEC_HAS_CONTENTS)
2100       && ! bfd_set_section_flags (abfd, sec,
2101                                   bfd_get_section_flags (abfd, sec)
2102                                   | SEC_ALLOC | SEC_LOAD))
2103     error = TRUE;
2104
2105   /* Free whatever resources we took.  */
2106   for (i = 0; i < sizeof (file_names) / sizeof (file_names[0]); i++)
2107     if (file_names[i])
2108       free (file_names[i]);
2109   return ! error;
2110 }
2111
2112 /* A hook to set up object file dependent section information.  For mmo,
2113    we point out the shape of allocated section contents.  */
2114
2115 static bfd_boolean
2116 mmo_new_section_hook (abfd, newsect)
2117      bfd *abfd ATTRIBUTE_UNUSED;
2118      asection *newsect;
2119 {
2120   /* We zero-fill all fields and assume NULL is represented by an all
2121      zero-bit pattern.  */
2122   newsect->used_by_bfd =
2123     (PTR) bfd_zalloc (abfd, sizeof (struct mmo_section_data_struct));
2124
2125   if (!newsect->used_by_bfd)
2126     return FALSE;
2127
2128   /* Always align to at least 32-bit words.  */
2129   newsect->alignment_power = 2;
2130   return TRUE;
2131 }
2132
2133 /* We already have section contents loaded for sections that have
2134    contents.  */
2135
2136 static bfd_boolean
2137 mmo_get_section_contents (abfd, sec, location, offset, bytes_to_do)
2138      bfd *abfd ATTRIBUTE_UNUSED;
2139      asection *sec ATTRIBUTE_UNUSED;
2140      PTR location ATTRIBUTE_UNUSED;
2141      file_ptr offset ATTRIBUTE_UNUSED;
2142      bfd_size_type bytes_to_do ATTRIBUTE_UNUSED;
2143 {
2144   /* Iterate over diminishing chunk sizes, copying contents, like
2145      mmo_set_section_contents.  */
2146   while (bytes_to_do)
2147     {
2148       /* A minor song-and-dance to make sure we're not bitten by the
2149          distant possibility of the cast from bfd_vma to int making the
2150          chunk zero-sized.  */
2151       int chunk_size
2152         = (int) bytes_to_do != 0 ? bytes_to_do : MMO_SEC_CONTENTS_CHUNK_SIZE;
2153       bfd_byte *loc;
2154
2155       do
2156         loc = mmo_get_loc (sec, sec->vma + offset, chunk_size);
2157       while (loc == NULL && (chunk_size /= 2) != 0);
2158
2159       if (chunk_size == 0)
2160         return FALSE;
2161
2162       memcpy (location, loc, chunk_size);
2163
2164       location += chunk_size;
2165       bytes_to_do -= chunk_size;
2166       offset += chunk_size;
2167     }
2168   return TRUE;
2169 }
2170
2171 /* Return the amount of memory needed to read the symbol table.  */
2172
2173 static long
2174 mmo_get_symtab_upper_bound (abfd)
2175      bfd *abfd ATTRIBUTE_UNUSED;
2176 {
2177   return (abfd->symcount + 1) * sizeof (asymbol *);
2178 }
2179
2180 /* Sort mmo symbols by serial number.  */
2181
2182 static int
2183 mmo_sort_mmo_symbols (arg1, arg2)
2184      const PTR arg1;
2185      const PTR arg2;
2186 {
2187   const struct mmo_symbol *sym1 = *(const struct mmo_symbol **) arg1;
2188   const struct mmo_symbol *sym2 = *(const struct mmo_symbol **) arg2;
2189
2190   /* Sort by serial number first.  */
2191   if (sym1->serno < sym2->serno)
2192     return -1;
2193   else if (sym1->serno > sym2->serno)
2194     return 1;
2195
2196   /* Then sort by address of the table entries.  */
2197   return ((const char *) arg1 - (const char *) arg2);
2198 }
2199
2200 /* Translate the symbol table.  */
2201
2202 static long
2203 mmo_canonicalize_symtab (abfd, alocation)
2204      bfd *abfd;
2205      asymbol **alocation;
2206 {
2207   unsigned int symcount = bfd_get_symcount (abfd);
2208   asymbol *csymbols;
2209   unsigned int i;
2210
2211   csymbols = abfd->tdata.mmo_data->csymbols;
2212   if (csymbols == NULL)
2213     {
2214       asymbol *c;
2215       struct mmo_symbol *s;
2216       struct mmo_symbol **msp;
2217
2218       /* First we store the symbols into the table we'll return, then we
2219          qsort it on the serial number, with secondary on the address of
2220          the symbol, to preserve order if there would be non-unique serial
2221          numbers.  */
2222       for (s = abfd->tdata.mmo_data->symbols,
2223              msp = (struct mmo_symbol **) alocation;
2224            s != NULL;
2225            s = s->next, ++msp)
2226         *msp = s;
2227
2228       *msp = NULL;
2229
2230       qsort (alocation, symcount, sizeof (struct mmo_symbol *),
2231              mmo_sort_mmo_symbols);
2232
2233       csymbols = (asymbol *) bfd_alloc (abfd, symcount * sizeof (asymbol));
2234       if (csymbols == NULL && symcount != 0)
2235         return FALSE;
2236       abfd->tdata.mmo_data->csymbols = csymbols;
2237
2238       for (msp = (struct mmo_symbol **) alocation, c = csymbols;
2239            *msp != NULL;
2240            msp++, ++c)
2241         {
2242           s = *msp;
2243           c->the_bfd = abfd;
2244           c->name = s->name;
2245           c->value = s->value;
2246           c->flags = BSF_GLOBAL;
2247
2248           if (s->sym_type == mmo_data_sym)
2249             {
2250               c->section
2251                 = bfd_get_section_by_name (abfd, MMO_DATA_SECTION_NAME);
2252
2253               if (c->section == NULL)
2254                 c->section = bfd_abs_section_ptr;
2255               else
2256                 c->value -= c->section->vma;
2257             }
2258           else if (s->sym_type == mmo_undef_sym)
2259             c->section = bfd_und_section_ptr;
2260           else if (s->sym_type == mmo_reg_sym)
2261             {
2262               c->section
2263                 = bfd_make_section_old_way (abfd, MMIX_REG_SECTION_NAME);
2264             }
2265           else
2266             {
2267               asection *textsec
2268                 = bfd_get_section_by_name (abfd, MMO_TEXT_SECTION_NAME);
2269
2270               if (textsec != NULL
2271                   && c->value >= textsec->vma
2272                   && c->value <= textsec->vma + textsec->_cooked_size)
2273                 {
2274                   c->section = textsec;
2275                   c->value -= c->section->vma;
2276                 }
2277               else
2278                 c->section = bfd_abs_section_ptr;
2279             }
2280
2281           c->udata.p = NULL;
2282         }
2283     }
2284
2285   /* Last, overwrite the incoming table with the right-type entries.  */
2286   for (i = 0; i < symcount; i++)
2287     *alocation++ = csymbols++;
2288   *alocation = NULL;
2289
2290   return symcount;
2291 }
2292
2293 /* Get information about a symbol.  */
2294
2295 static void
2296 mmo_get_symbol_info (ignore_abfd, symbol, ret)
2297      bfd *ignore_abfd ATTRIBUTE_UNUSED;
2298      asymbol *symbol;
2299      symbol_info *ret;
2300 {
2301   bfd_symbol_info (symbol, ret);
2302 }
2303
2304 static void
2305 mmo_print_symbol (abfd, afile, symbol, how)
2306      bfd *abfd;
2307      PTR afile;
2308      asymbol *symbol;
2309      bfd_print_symbol_type how;
2310 {
2311   FILE *file = (FILE *) afile;
2312
2313   switch (how)
2314     {
2315     case bfd_print_symbol_name:
2316       fprintf (file, "%s", symbol->name);
2317       break;
2318     default:
2319       bfd_print_symbol_vandf (abfd, (PTR) file, symbol);
2320
2321       fprintf (file, " %-5s %s",
2322                symbol->section->name,
2323                symbol->name);
2324     }
2325 }
2326
2327 /* We can't map a file directly into executable code, so the
2328    size of header information is irrelevant.  */
2329
2330 static int
2331 mmo_sizeof_headers (abfd, exec)
2332      bfd *abfd ATTRIBUTE_UNUSED;
2333      bfd_boolean exec ATTRIBUTE_UNUSED;
2334 {
2335   return 0;
2336 }
2337
2338 /* Write the (section-neutral) file preamble.  */
2339
2340 static bfd_boolean
2341 mmo_internal_write_header (abfd)
2342      bfd *abfd;
2343 {
2344   const char lop_pre_bfd[] = { LOP, LOP_PRE, 1, 1};
2345
2346   if (bfd_bwrite (lop_pre_bfd, 4, abfd) != 4)
2347     return FALSE;
2348
2349   /* Copy creation time of original file.  */
2350   if (bfd_bwrite (abfd->tdata.mmo_data->created, 4, abfd) != 4)
2351     return FALSE;
2352
2353   return TRUE;
2354 }
2355
2356 /* Write the LOP_POST record, with global register initializations.
2357    Z is the Z field of the LOP_POST, corresponding to 255 - number of
2358    registers at DATA.  The Z = 255 field is filled in with the
2359    start-address.  */
2360
2361 static bfd_boolean
2362 mmo_internal_write_post (abfd, z, sec)
2363      bfd *abfd;
2364      int z;
2365      asection *sec;
2366 {
2367   int i;
2368   bfd_byte buf[8];
2369   mmo_write_tetra_raw (abfd, (LOP << 24) | (LOP_POST << 16) | z);
2370
2371   for (i = z; i < 255; i++)
2372     {
2373       bfd_byte *data = mmo_get_loc (sec, i * 8, 8);
2374
2375       if (bfd_bwrite (data, 8, abfd) != 8)
2376         return FALSE;
2377     }
2378
2379   /* For Z == $255, we always emit the start location; supposedly Main,
2380      but we have it handy at bfd_get_start_address.  If we're called with
2381      Z == 255, don't assume DATA is valid.  */
2382   bfd_put_64 (abfd, bfd_get_start_address (abfd), buf);
2383
2384   return ! abfd->tdata.mmo_data->have_error && bfd_bwrite (buf, 8, abfd) == 8;
2385 }
2386
2387 /* Translate to and from BFD flags.  This is to make sure that we don't
2388    get bitten by BFD flag number changes.  */
2389
2390 static flagword
2391 mmo_sec_flags_from_bfd_flags (flags)
2392      flagword flags;
2393 {
2394   flagword oflags = 0;
2395
2396   if (flags & SEC_ALLOC)
2397     oflags |= MMO_SEC_ALLOC;
2398   if (flags & SEC_LOAD)
2399     oflags |= MMO_SEC_LOAD;
2400   if (flags & SEC_RELOC)
2401     oflags |= MMO_SEC_RELOC;
2402   if (flags & SEC_READONLY)
2403     oflags |= MMO_SEC_READONLY;
2404   if (flags & SEC_CODE)
2405     oflags |= MMO_SEC_CODE;
2406   if (flags & SEC_DATA)
2407     oflags |= MMO_SEC_DATA;
2408   if (flags & SEC_NEVER_LOAD)
2409     oflags |= MMO_SEC_NEVER_LOAD;
2410   if (flags & SEC_IS_COMMON)
2411     oflags |= MMO_SEC_IS_COMMON;
2412   if (flags & SEC_DEBUGGING)
2413     oflags |= MMO_SEC_DEBUGGING;
2414
2415   return oflags;
2416 }
2417
2418 static flagword
2419 bfd_sec_flags_from_mmo_flags (flags)
2420      flagword flags;
2421 {
2422   flagword oflags = 0;
2423
2424   if (flags & MMO_SEC_ALLOC)
2425     oflags |= SEC_ALLOC;
2426   if (flags & MMO_SEC_LOAD)
2427     oflags |= SEC_LOAD;
2428   if (flags & MMO_SEC_RELOC)
2429     oflags |= SEC_RELOC;
2430   if (flags & MMO_SEC_READONLY)
2431     oflags |= SEC_READONLY;
2432   if (flags & MMO_SEC_CODE)
2433     oflags |= SEC_CODE;
2434   if (flags & MMO_SEC_DATA)
2435     oflags |= SEC_DATA;
2436   if (flags & MMO_SEC_NEVER_LOAD)
2437     oflags |= SEC_NEVER_LOAD;
2438   if (flags & MMO_SEC_IS_COMMON)
2439     oflags |= SEC_IS_COMMON;
2440   if (flags & MMO_SEC_DEBUGGING)
2441     oflags |= SEC_DEBUGGING;
2442
2443   return oflags;
2444 }
2445
2446 /* Write a section.  */
2447
2448 static bfd_boolean
2449 mmo_internal_write_section (abfd, sec)
2450      bfd *abfd;
2451      asection *sec;
2452 {
2453   /* We do it differently depending on what section this is:
2454
2455    ".text": Output, prepended by information about the first source file
2456    (not yet implemented.)
2457
2458    ".data": Output.
2459
2460    (".MMIX.reg_contents": Not handled here.)
2461
2462    Anything else: Output inside a lop_spec 80, in the format described
2463    above.  */
2464
2465   if (strcmp (sec->name, MMO_TEXT_SECTION_NAME) == 0)
2466     /* FIXME: Output source file name and line number.  */
2467     return mmo_write_loc_chunk_list (abfd, mmo_section_data (sec)->head);
2468   else if (strcmp (sec->name, MMO_DATA_SECTION_NAME) == 0)
2469     return mmo_write_loc_chunk_list (abfd, mmo_section_data (sec)->head);
2470   else if (strcmp (sec->name, MMIX_REG_CONTENTS_SECTION_NAME) == 0)
2471     /* Not handled here.  */
2472     {
2473       /* This would normally be an abort call since this can't happen, but
2474          we don't do that.  */
2475       bfd_set_error (bfd_error_bad_value);
2476       return FALSE;
2477     }
2478   else if (strncmp (sec->name, MMIX_OTHER_SPEC_SECTION_PREFIX,
2479                     strlen (MMIX_OTHER_SPEC_SECTION_PREFIX)) == 0)
2480     {
2481       int n = atoi (sec->name + strlen (MMIX_OTHER_SPEC_SECTION_PREFIX));
2482       mmo_write_tetra_raw (abfd, (LOP << 24) | (LOP_SPEC << 16) | n);
2483       return (! abfd->tdata.mmo_data->have_error
2484               && mmo_write_chunk_list (abfd, mmo_section_data (sec)->head));
2485     }
2486   /* Ignore sections that are just allocated or empty; we write out
2487      _contents_ here.  */
2488   else if ((bfd_get_section_flags (abfd, sec) & SEC_HAS_CONTENTS) != 0
2489            && sec->_raw_size != 0)
2490     {
2491       /* Keep the document-comment formatted the way it is.  */
2492 /*
2493 INODE
2494 mmo section mapping, , Symbol-table, mmo
2495 SUBSECTION
2496         mmo section mapping
2497
2498         The implementation in BFD uses special data type 80 (decimal) to
2499         encapsulate and describe named sections, containing e.g.@: debug
2500         information.  If needed, any datum in the encapsulation will be
2501         quoted using lop_quote.  First comes a 32-bit word holding the
2502         number of 32-bit words containing the zero-terminated zero-padded
2503         segment name.  After the name there's a 32-bit word holding flags
2504         describing the section type.  Then comes a 64-bit big-endian word
2505         with the section length (in bytes), then another with the section
2506         start address.  Depending on the type of section, the contents
2507         might follow, zero-padded to 32-bit boundary.  For a loadable
2508         section (such as data or code), the contents might follow at some
2509         later point, not necessarily immediately, as a lop_loc with the
2510         same start address as in the section description, followed by the
2511         contents.  This in effect forms a descriptor that must be emitted
2512         before the actual contents.  Sections described this way must not
2513         overlap.
2514
2515         For areas that don't have such descriptors, synthetic sections are
2516         formed by BFD.  Consecutive contents in the two memory areas
2517         @samp{0x0000@dots{}00} to @samp{0x01ff@dots{}ff} and
2518         @samp{0x2000@dots{}00} to @samp{0x20ff@dots{}ff} are entered in
2519         sections named <<.text>> and <<.data>> respectively.  If an area
2520         is not otherwise described, but would together with a neighboring
2521         lower area be less than @samp{0x40000000} bytes long, it is joined
2522         with the lower area and the gap is zero-filled.  For other cases,
2523         a new section is formed, named <<.MMIX.sec.@var{n}>>.  Here,
2524         @var{n} is a number, a running count through the mmo file,
2525         starting at 0.
2526
2527 EXAMPLE
2528         A loadable section specified as:
2529
2530 | .section secname,"ax"
2531 | TETRA 1,2,3,4,-1,-2009
2532 | BYTE 80
2533
2534         and linked to address @samp{0x4}, is represented by the sequence:
2535
2536 | 0x98080050 - lop_spec 80
2537 | 0x00000002 - two 32-bit words for the section name
2538 | 0x7365636e - "secn"
2539 | 0x616d6500 - "ame\0"
2540 | 0x00000033 - flags CODE, READONLY, LOAD, ALLOC
2541 | 0x00000000 - high 32 bits of section length
2542 | 0x0000001c - section length is 28 bytes; 6 * 4 + 1 + alignment to 32 bits
2543 | 0x00000000 - high 32 bits of section address
2544 | 0x00000004 - section address is 4
2545 | 0x98010002 - 64 bits with address of following data
2546 | 0x00000000 - high 32 bits of address
2547 | 0x00000004 - low 32 bits: data starts at address 4
2548 | 0x00000001 - 1
2549 | 0x00000002 - 2
2550 | 0x00000003 - 3
2551 | 0x00000004 - 4
2552 | 0xffffffff - -1
2553 | 0xfffff827 - -2009
2554 | 0x50000000 - 80 as a byte, padded with zeros.
2555
2556         Note that the lop_spec wrapping does not include the section
2557         contents.  Compare this to a non-loaded section specified as:
2558
2559 | .section thirdsec
2560 | TETRA 200001,100002
2561 | BYTE 38,40
2562
2563         This, when linked to address @samp{0x200000000000001c}, is
2564         represented by:
2565
2566 | 0x98080050 - lop_spec 80
2567 | 0x00000002 - two 32-bit words for the section name
2568 | 0x7365636e - "thir"
2569 | 0x616d6500 - "dsec"
2570 | 0x00000010 - flag READONLY
2571 | 0x00000000 - high 32 bits of section length
2572 | 0x0000000c - section length is 12 bytes; 2 * 4 + 2 + alignment to 32 bits
2573 | 0x20000000 - high 32 bits of address
2574 | 0x0000001c - low 32 bits of address 0x200000000000001c
2575 | 0x00030d41 - 200001
2576 | 0x000186a2 - 100002
2577 | 0x26280000 - 38, 40 as bytes, padded with zeros
2578
2579         For the latter example, the section contents must not be
2580         loaded in memory, and is therefore specified as part of the
2581         special data.  The address is usually unimportant but might
2582         provide information for e.g.@: the DWARF 2 debugging format.  */
2583
2584       mmo_write_tetra_raw (abfd, LOP_SPEC_SECTION);
2585       mmo_write_tetra (abfd, (strlen (sec->name) + 3) / 4);
2586       mmo_write_chunk (abfd, sec->name, strlen (sec->name));
2587       mmo_flush_chunk (abfd);
2588       /* FIXME: We can get debug sections (.debug_line & Co.) with a
2589          section flag still having SEC_RELOC set.  Investigate.  This
2590          might be true for all alien sections; perhaps mmo.em should clear
2591          that flag.  Might be related to weak references.  */
2592       mmo_write_tetra (abfd,
2593                        mmo_sec_flags_from_bfd_flags
2594                        (bfd_get_section_flags (abfd, sec)));
2595       mmo_write_octa (abfd, sec->_raw_size);
2596       mmo_write_octa (abfd, bfd_get_section_vma (abfd, sec));
2597
2598       /* Writing a LOP_LOC ends the LOP_SPEC data, and makes data actually
2599          loaded.  */
2600       if (bfd_get_section_flags (abfd, sec) & SEC_LOAD)
2601         return (! abfd->tdata.mmo_data->have_error
2602                 && mmo_write_loc_chunk_list (abfd,
2603                                              mmo_section_data (sec)->head));
2604       return (! abfd->tdata.mmo_data->have_error
2605               && mmo_write_chunk_list (abfd, mmo_section_data (sec)->head));
2606     }
2607   return TRUE;
2608 }
2609
2610 /* We save up all data before output.  */
2611
2612 static bfd_boolean
2613 mmo_set_section_contents (abfd, sec, location, offset, bytes_to_do)
2614      bfd *abfd ATTRIBUTE_UNUSED;
2615      sec_ptr sec;
2616      const PTR location;
2617      file_ptr offset;
2618      bfd_size_type bytes_to_do;
2619 {
2620   /* Iterate over diminishing chunk sizes, copying contents.  */
2621   while (bytes_to_do)
2622     {
2623       /* A minor song-and-dance to make sure we're not bitten by the
2624          distant possibility of the cast from bfd_vma to int making the
2625          chunk zero-sized.  */
2626       int chunk_size
2627         = (int) bytes_to_do != 0 ? bytes_to_do : MMO_SEC_CONTENTS_CHUNK_SIZE;
2628       bfd_byte *loc;
2629
2630       do
2631         loc = mmo_get_loc (sec, sec->vma + offset, chunk_size);
2632       while (loc == NULL && (chunk_size /= 2) != 0);
2633
2634       if (chunk_size == 0)
2635         return FALSE;
2636
2637       memcpy (loc, location, chunk_size);
2638
2639       location += chunk_size;
2640       bytes_to_do -= chunk_size;
2641       offset += chunk_size;
2642     }
2643   return TRUE;
2644 }
2645
2646 /* Add a symbol to a trie-tree.  */
2647
2648 static bfd_boolean
2649 mmo_internal_add_3_sym (abfd, rootp, symp)
2650      bfd *abfd;
2651      struct mmo_symbol_trie *rootp;
2652      const struct mmo_symbol *symp;
2653 {
2654   const char *name = symp->name;
2655   struct mmo_symbol_trie *trie = rootp;
2656   struct mmo_symbol_trie **triep = NULL;
2657
2658   while (*name && trie != NULL)
2659     {
2660       if (*name < trie->symchar)
2661         {
2662           triep = &trie->left;
2663           trie = trie->left;
2664         }
2665       else if (*name > trie->symchar)
2666         {
2667           triep = &trie->right;
2668           trie = trie->right;
2669         }
2670       else if (*name == trie->symchar)
2671         {
2672           triep = &trie->middle;
2673           name++;
2674
2675           /* Make sure "trie" points to where we should fill in the
2676              current symbol whenever we've iterated through "name".  We
2677              would lose the right position if we encounter "foobar" then
2678              "foo".  */
2679           if (*name)
2680             trie = trie->middle;
2681         }
2682     }
2683
2684   while (*name != 0)
2685     {
2686       /* Create middle branches for the rest of the characters.  */
2687       trie = bfd_zalloc (abfd, sizeof (struct mmo_symbol_trie));
2688       *triep = trie;
2689       trie->symchar = *name++;
2690       triep = &trie->middle;
2691     }
2692
2693   /* We discover a duplicate symbol rather late in the process, but still;
2694      we discover it and bail out.  */
2695   if (trie->sym.name != NULL)
2696     {
2697       (*_bfd_error_handler)
2698         (_("%s: invalid symbol table: duplicate symbol `%s'\n"),
2699          bfd_get_filename (abfd), trie->sym.name);
2700       bfd_set_error (bfd_error_bad_value);
2701       return FALSE;
2702     }
2703
2704   memcpy (&trie->sym, symp, sizeof *symp);
2705   return TRUE;
2706 }
2707
2708 /* Find out the length of the serialized version of a trie in bytes.  */
2709
2710 static unsigned int
2711 mmo_internal_3_length (abfd, trie)
2712      bfd *abfd;
2713      struct mmo_symbol_trie *trie;
2714 {
2715   /* First, one for the control byte.  */
2716   unsigned int length = 1;
2717
2718   if (trie == NULL)
2719     return 0;
2720
2721   /* Add in the recursion to the left.  */
2722   length += mmo_internal_3_length (abfd, trie->left);
2723
2724   /* Add in the middle trie and the character.  */
2725   length += 1 + mmo_internal_3_length (abfd, trie->middle);
2726
2727   /* Add in the recursion to the right.  */
2728   length += mmo_internal_3_length (abfd, trie->right);
2729
2730   /* Add in bytes for the symbol (if this is an endnode). */
2731   if (trie->sym.name != NULL)
2732     {
2733       unsigned int serno = trie->sym.serno;
2734
2735       /* First what it takes to encode the value. */
2736       if (trie->sym.sym_type == mmo_reg_sym)
2737         length++;
2738       else if (trie->sym.sym_type == mmo_undef_sym)
2739         length += 2;
2740       else
2741         {
2742           bfd_vma value = trie->sym.value;
2743
2744           /* Coded in one to eight following bytes.  */
2745           if (trie->sym.sym_type == mmo_data_sym)
2746             value -= (bfd_vma) 0x20 << 56;
2747
2748           do
2749             {
2750               value >>= 8;
2751               length++;
2752             }
2753           while (value != 0);
2754         }
2755
2756       /* Find out what it takes to encode the serial number.  */
2757       do
2758         {
2759           serno >>= 7;
2760           length++;
2761         }
2762       while (serno != 0);
2763     }
2764
2765   return length;
2766 }
2767
2768 /* Helper function for outputting the serial number of a symbol, output as
2769    a variant of leb128 (see dwarf2 documentation) which could be called
2770    beb128.  Using a helper function and recursion simplifies debugging.  */
2771
2772 static void
2773 mmo_beb128_out (abfd, serno, marker)
2774      bfd *abfd;
2775      int serno;
2776      int marker;
2777 {
2778   if (serno & ~0x7f)
2779     mmo_beb128_out (abfd, serno >> 7, 0);
2780   mmo_write_byte (abfd, marker | (serno & 0x7f));
2781 }
2782
2783 /* Serialize a trie.  */
2784
2785 static void
2786 mmo_internal_3_dump (abfd, trie)
2787      bfd *abfd;
2788      struct mmo_symbol_trie *trie;
2789 {
2790   bfd_byte control = 0;
2791
2792   if (trie == NULL)
2793     return;
2794
2795   if (trie->left)
2796     control |= MMO3_LEFT;
2797
2798   if (trie->middle)
2799     control |= MMO3_MIDDLE;
2800
2801   if (trie->right)
2802     control |= MMO3_RIGHT;
2803
2804   if (trie->sym.name != NULL)
2805     {
2806       /* Encode the symbol type and length of value bytes.  */
2807       if (trie->sym.sym_type == mmo_reg_sym)
2808         control |= MMO3_REGQUAL_BITS;
2809       else if (trie->sym.sym_type == mmo_undef_sym)
2810         control |= MMO3_UNDEF;
2811       else
2812         {
2813           bfd_vma value = trie->sym.value;
2814
2815           /* Coded in 1..8 following bytes.  */
2816           if (trie->sym.sym_type == mmo_data_sym)
2817             {
2818               control |= MMO3_DATA;
2819               value -= (bfd_vma) 0x20 << 56;
2820             }
2821
2822           do
2823             {
2824               value >>= 8;
2825               control++;
2826             }
2827           while (value != 0);
2828         }
2829     }
2830
2831   /* The control byte is output before recursing.  */
2832   mmo_write_byte (abfd, control);
2833
2834   mmo_internal_3_dump (abfd, trie->left);
2835
2836   if (control & MMO3_SYMBITS)
2837     {
2838       mmo_write_byte (abfd, trie->symchar);
2839
2840       if (trie->sym.name != NULL)
2841         {
2842           if (trie->sym.sym_type == mmo_reg_sym)
2843             mmo_write_byte (abfd, trie->sym.value);
2844           else if (trie->sym.sym_type == mmo_undef_sym)
2845             {
2846               mmo_write_byte (abfd, 0);
2847               mmo_write_byte (abfd, 0);
2848             }
2849           else
2850             {
2851               bfd_vma value = trie->sym.value;
2852
2853               bfd_byte byte_n = control & 15;
2854
2855               /* Coded in 1..8 following bytes.  Note that the value is
2856                  shifted out big-endian.  */
2857               if (trie->sym.sym_type == mmo_data_sym)
2858                 {
2859                   value -= (bfd_vma) 0x20 << 56;
2860                   byte_n -= 8;
2861                 }
2862
2863               do
2864                 {
2865                   mmo_write_byte (abfd, (value >> ((byte_n - 1) * 8)) & 0xff);
2866                   byte_n--;
2867                 }
2868               while (byte_n != 0);
2869             }
2870
2871           mmo_beb128_out (abfd, trie->sym.serno, 128);
2872         }
2873       mmo_internal_3_dump (abfd, trie->middle);
2874     }
2875   mmo_internal_3_dump (abfd, trie->right);
2876 }
2877
2878 /* Write symbols in mmo format.  Also write the lop_end terminator.  */
2879
2880 static bfd_boolean
2881 mmo_write_symbols_and_terminator (abfd)
2882      bfd *abfd;
2883 {
2884   int count = bfd_get_symcount (abfd);
2885   asymbol *maintable[2];
2886   asymbol **table;
2887   asymbol **orig_table = bfd_get_outsymbols (abfd);
2888   int serno;
2889   struct mmo_symbol_trie root;
2890   int trie_len;
2891   int i;
2892   bfd_byte buf[4];
2893
2894   /* Create a symbol for "Main".  */
2895   asymbol *fakemain = bfd_make_empty_symbol (abfd);
2896
2897   fakemain->flags = BSF_GLOBAL;
2898   fakemain->value = bfd_get_start_address (abfd);
2899   fakemain->name = MMIX_START_SYMBOL_NAME;
2900   fakemain->section = bfd_abs_section_ptr;
2901   maintable[0] = fakemain;
2902   maintable[1] = NULL;
2903
2904   memset (&root, 0, sizeof (root));
2905
2906   /* Make all symbols take a left turn.  */
2907   root.symchar = 0xff;
2908
2909   /* There must always be a ":Main", so we'll add one if there are no
2910      symbols.  Make sure we have room for it.  */
2911   table = bfd_alloc (abfd, (count + 1) * sizeof (asymbol *));
2912   if (table == NULL)
2913     return FALSE;
2914
2915   memcpy (table, orig_table, count * sizeof (asymbol *));
2916
2917   /* Move :Main (if there is one) to the first position.  This is
2918      necessary to get the same layout of the trie-tree when linking as
2919      when objcopying the result as in the objcopy.exp test "simple objcopy
2920      of executable".  It also automatically takes care of assigning serial
2921      number 1 to :Main (as is mandatory).  */
2922   for (i = 0; i < count; i++)
2923     if (table[i] != NULL
2924         && strcmp (table[i]->name, MMIX_START_SYMBOL_NAME) == 0
2925         && (table[i]->flags & (BSF_DEBUGGING|BSF_GLOBAL)) == BSF_GLOBAL)
2926       {
2927         asymbol *mainsym = table[i];
2928         memcpy (table + 1, orig_table, i * sizeof (asymbol *));
2929         table[0] = mainsym;
2930
2931         /* Check that the value assigned to :Main is the same as the entry
2932            address.  The default linker script asserts this.  This is as
2933            good a place as any to check this consistency. */
2934         if ((mainsym->value
2935              + mainsym->section->output_section->vma
2936              + mainsym->section->output_offset)
2937             != bfd_get_start_address (abfd))
2938           {
2939             /* Arbitrary buffer to hold the printable representation of a
2940                vma.  */
2941             char vmas_main[40];
2942             char vmas_start[40];
2943             bfd_vma vma_start = bfd_get_start_address (abfd);
2944
2945             sprintf_vma (vmas_main, mainsym->value);
2946             sprintf_vma (vmas_start, vma_start);
2947
2948             (*_bfd_error_handler)
2949               (_("%s: Bad symbol definition: `Main' set to %s rather\
2950  than the start address %s\n"),
2951                bfd_get_filename (abfd), vmas_main, vmas_start);
2952             bfd_set_error (bfd_error_bad_value);
2953             return FALSE;
2954           }
2955         break;
2956       }
2957   if (i == count && count != 0)
2958     {
2959       /* When there are symbols, there must be a :Main.  There was no
2960          :Main, so we need to add it manually.  */
2961       memcpy (table + 1, orig_table, count * sizeof (asymbol *));
2962       table[0] = fakemain;
2963       count++;
2964     }
2965
2966   for (i = 0, serno = 1; i < count && table[i] != NULL; i++)
2967     {
2968       asymbol *s = table[i];
2969
2970       /* It's not enough to consult bfd_is_local_label, since it does not
2971          mean "local" in the sense of linkable-and-observable-after-link.
2972          Let's just check the BSF_GLOBAL flag.
2973
2974          Also, don't export symbols with characters not in the allowed set.  */
2975       if ((s->flags & (BSF_DEBUGGING|BSF_GLOBAL)) == BSF_GLOBAL
2976           && strspn (s->name,
2977                      valid_mmo_symbol_character_set) == strlen (s->name))
2978         {
2979           struct mmo_symbol sym;
2980           memset (&sym, 0, sizeof (sym));
2981
2982           sym.name = s->name;
2983           sym.value =
2984             s->value
2985             + s->section->output_section->vma
2986             + s->section->output_offset;
2987
2988           if (bfd_is_und_section (s->section))
2989             sym.sym_type = mmo_undef_sym;
2990           else if (strcmp (s->section->name, MMO_DATA_SECTION_NAME) == 0
2991                    /* The encoding of data symbols require that the "rest"
2992                       of the value fits in 6 bytes, so the upper two bytes
2993                       must be 0x2000.  All other symbols get to be the
2994                       absolute type.  */
2995                    && (sym.value >> 48) == 0x2000)
2996             sym.sym_type = mmo_data_sym;
2997           else if (strcmp (s->section->name, MMIX_REG_SECTION_NAME) == 0)
2998             sym.sym_type = mmo_reg_sym;
2999           else if (strcmp (s->section->name,
3000                            MMIX_REG_CONTENTS_SECTION_NAME) == 0)
3001             {
3002               sym.sym_type = mmo_reg_sym;
3003               sym.value /= 8;
3004             }
3005           else
3006             sym.sym_type = mmo_abs_sym;
3007
3008           /* FIXME: We assume the order of the received symbols is an
3009              ordered mapping of the serial numbers.  This is not
3010              necessarily true if we e.g. objcopy a mmo file to another and
3011              there are gaps in the numbering.  Not sure if this can
3012              happen.  Not sure what to do.  */
3013           sym.serno = serno++;
3014
3015           if (! mmo_internal_add_3_sym (abfd, &root, &sym))
3016             return FALSE;
3017         }
3018     }
3019
3020   /* Change the root node to be a ":"-prefix.  */
3021   root.symchar = ':';
3022   root.middle = root.left;
3023   root.right = NULL;
3024   root.left = NULL;
3025
3026   /* We have to find out if we can fit the whole symbol table in the mmo
3027      symtab.  It would be bad to assume we can always fit it in 262144
3028      bytes.  If we can't, just leave the Main symbol.  */
3029   trie_len = (mmo_internal_3_length (abfd, &root) + 3)/4;
3030
3031   if (trie_len > 0xffff)
3032     {
3033       /* Test this code by using a lower limit in the test above and check
3034          that the single "Main" symbol is emitted and handled properly.
3035          There's no specific test-case.  */
3036       struct mmo_symbol sym;
3037
3038       (*_bfd_error_handler)
3039         (_("%s: warning: symbol table too large for mmo, larger than 65535\
3040  32-bit words: %d.  Only `Main' will be emitted.\n"),
3041          bfd_get_filename (abfd), trie_len);
3042
3043       memset (&sym, 0, sizeof (sym));
3044       sym.sym_type = mmo_abs_sym;
3045       sym.name = MMIX_START_SYMBOL_NAME;
3046       sym.serno = 1;
3047       sym.value = bfd_get_start_address (abfd);
3048
3049       /* Then patch up a symbol table to be just the ":Main" symbol.  */
3050       memset (&root, 0, sizeof (root));
3051       root.left = root.middle;
3052       root.symchar = 0xff;
3053       root.middle = NULL;
3054       root.right = NULL;
3055
3056       if (! mmo_internal_add_3_sym (abfd, &root, &sym))
3057         return FALSE;
3058
3059       root.symchar = ':';
3060       root.middle = root.left;
3061       root.right = NULL;
3062       root.left = NULL;
3063
3064       trie_len = (mmo_internal_3_length (abfd, &root) + 3)/4;
3065     }
3066
3067   /* Reset the written-bytes counter.  */
3068   abfd->tdata.mmo_data->byte_no = 0;
3069
3070   /* Put out the lop_stab mark.  */
3071   bfd_put_32 (abfd, (LOP << 24) | (LOP_STAB << 16), buf);
3072   if (bfd_bwrite (buf, 4, abfd) != 4)
3073     return FALSE;
3074
3075   /* Dump out symbols.  */
3076   mmo_internal_3_dump (abfd, &root);
3077
3078   if (trie_len != (abfd->tdata.mmo_data->byte_no + 3)/4)
3079     {
3080       /* I haven't seen this trig.  It seems no use claiming this case
3081          isn't debugged and abort if we get here.  Instead emit a
3082          diagnostic and fail "normally".  */
3083       (*_bfd_error_handler)
3084         (_("%s: internal error, symbol table changed size from %d to %d\
3085  words\n"),
3086          bfd_get_filename (abfd), trie_len,
3087          (abfd->tdata.mmo_data->byte_no + 3)/4);
3088       bfd_set_error (bfd_error_bad_value);
3089       return FALSE;
3090     }
3091
3092   /* Dump out remaining bytes in the buffer and handle I/O errors by
3093      propagating errors.  */
3094   if ((abfd->tdata.mmo_data->byte_no % 4) != 0
3095       || abfd->tdata.mmo_data->have_error)
3096     {
3097       memset (abfd->tdata.mmo_data->buf + (abfd->tdata.mmo_data->byte_no % 4),
3098               0, 4 - (abfd->tdata.mmo_data->byte_no % 4));
3099
3100       if (abfd->tdata.mmo_data->have_error
3101           || bfd_bwrite (abfd->tdata.mmo_data->buf, 4, abfd) != 4)
3102         return FALSE;
3103     }
3104
3105   bfd_put_32 (abfd, (LOP << 24) | (LOP_END << 16) | trie_len, buf);
3106   return bfd_bwrite (buf, 4, abfd) == 4;
3107 }
3108
3109 /* Write section unless it is the register contents section.  For that, we
3110    instead store the section in the supplied pointer.  This function is
3111    used through bfd_map_over_sections.  */
3112
3113 static void
3114 mmo_write_section_unless_reg_contents (abfd, sec, p)
3115      bfd *abfd;
3116      asection *sec;
3117      PTR p;
3118 {
3119   struct mmo_write_sec_info *infop = (struct mmo_write_sec_info *) p;
3120
3121   if (! infop->retval)
3122     return;
3123
3124   if (strcmp (sec->name, MMIX_REG_CONTENTS_SECTION_NAME) == 0)
3125     {
3126       infop->reg_section = sec;
3127       return;
3128     }
3129
3130   /* Exclude the convenience register section.  */
3131   if (strcmp (sec->name, MMIX_REG_SECTION_NAME) == 0)
3132     {
3133       if (bfd_get_section_flags (abfd, sec) & SEC_HAS_CONTENTS)
3134         {
3135           /* Make sure it hasn't got contents.  It seems impossible to
3136              make it carry contents, so we don't have a test-case for
3137              this.  */
3138           (*_bfd_error_handler)
3139             (_("%s: internal error, internal register section %s had\
3140  contents\n"),
3141              bfd_get_filename (abfd), sec->name);
3142           bfd_set_error (bfd_error_bad_value);
3143           infop->retval = FALSE;
3144           return;
3145         }
3146
3147       return;
3148     }
3149
3150   infop->retval = mmo_internal_write_section (abfd, sec);
3151 }
3152
3153 /* Do the actual output of a file.  Assumes mmo_set_section_contents is
3154    already called. */
3155
3156 static bfd_boolean
3157 mmo_write_object_contents (abfd)
3158      bfd *abfd;
3159 {
3160   struct mmo_write_sec_info wsecinfo;
3161
3162   /* First, there are a few words of preamble.  */
3163   if (! mmo_internal_write_header (abfd))
3164     return FALSE;
3165
3166   wsecinfo.reg_section = NULL;
3167   wsecinfo.retval = TRUE;
3168
3169   bfd_map_over_sections (abfd, mmo_write_section_unless_reg_contents,
3170                          (PTR) &wsecinfo);
3171
3172   if (! wsecinfo.retval)
3173     return FALSE;
3174
3175   if (wsecinfo.reg_section != NULL)
3176     {
3177       asection *sec = wsecinfo.reg_section;
3178       unsigned int z = (unsigned int) (sec->vma / 8);
3179
3180       /* Registers 0..31 must not be global.  Do sanity check on the "vma"
3181          of the register contents section and check that it corresponds to
3182          the length of the section.  */
3183       if (z < 32 || z >= 255 || (sec->vma & 7) != 0
3184           || sec->vma != 256 * 8 - sec->_raw_size - 8)
3185         {
3186           bfd_set_error (bfd_error_bad_value);
3187
3188           if (sec->_raw_size == 0)
3189             /* There must always be at least one such register.  */
3190             (*_bfd_error_handler)
3191               (_("%s: no initialized registers; section length 0\n"),
3192                bfd_get_filename (abfd));
3193           else if (sec->vma > (256 - 32) * 8)
3194             /* Provide better error message for the case of too many
3195                global registers.  */
3196             (*_bfd_error_handler)
3197               (_("%s: too many initialized registers; section length %ld\n"),
3198                bfd_get_filename (abfd),
3199                (long) sec->_raw_size);
3200           else
3201             (*_bfd_error_handler)
3202               (_("%s: invalid start address for initialized registers of\
3203  length %ld: 0x%lx%08lx\n"),
3204                bfd_get_filename (abfd),
3205                (long) sec->_raw_size,
3206                (unsigned long) (sec->vma >> 32), (unsigned long) (sec->vma));
3207
3208           return FALSE;
3209         }
3210
3211       if (! mmo_internal_write_post (abfd, z, sec))
3212         return FALSE;
3213     }
3214   else
3215     if (! mmo_internal_write_post (abfd, 255, NULL))
3216       return FALSE;
3217
3218   return mmo_write_symbols_and_terminator (abfd);
3219 }
3220
3221 /* Return the size of a NULL pointer, so we support linking in an mmo
3222    object.  */
3223
3224 static long
3225 mmo_get_reloc_upper_bound (abfd, sec)
3226      bfd *abfd ATTRIBUTE_UNUSED;
3227      asection *sec ATTRIBUTE_UNUSED;
3228 {
3229   return sizeof (PTR);
3230 }
3231
3232 /* Similarly canonicalize relocs to empty, filling in the terminating NULL
3233    pointer.  */
3234
3235 long
3236 mmo_canonicalize_reloc (abfd, section, relptr, symbols)
3237      bfd *abfd ATTRIBUTE_UNUSED;
3238      sec_ptr section ATTRIBUTE_UNUSED;
3239      arelent **relptr;
3240      asymbol **symbols ATTRIBUTE_UNUSED;
3241 {
3242   *relptr = NULL;
3243   return 0;
3244 }
3245
3246 /* If there's anything in particular in a mmo bfd that we want to free,
3247    make this a real function.  Only do this if you see major memory
3248    thrashing; zealous free:ing will cause unwanted behavior, especially if
3249    you "free" memory allocated with "bfd_alloc", or even "bfd_release" a
3250    block allocated with "bfd_alloc"; they're really allocated from an
3251    obstack, and we don't know what was allocated there since this
3252    particular allocation.  */
3253
3254 #define mmo_close_and_cleanup _bfd_generic_close_and_cleanup
3255 #define mmo_bfd_free_cached_info _bfd_generic_bfd_free_cached_info
3256
3257 /* Perhaps we need to adjust this one; mmo labels (originally) without a
3258    leading ':' might more appropriately be called local.  */
3259 #define mmo_bfd_is_local_label_name bfd_generic_is_local_label_name
3260
3261 /* Is this one really used or defined by anyone?  */
3262 #define mmo_get_lineno _bfd_nosymbols_get_lineno
3263
3264 /* FIXME: We can do better on this one, if we have a dwarf2 .debug_line
3265    section or if MMO line numbers are implemented.  */
3266 #define mmo_find_nearest_line _bfd_nosymbols_find_nearest_line
3267 #define mmo_make_empty_symbol _bfd_generic_make_empty_symbol
3268 #define mmo_bfd_make_debug_symbol _bfd_nosymbols_bfd_make_debug_symbol
3269 #define mmo_read_minisymbols _bfd_generic_read_minisymbols
3270 #define mmo_minisymbol_to_symbol _bfd_generic_minisymbol_to_symbol
3271
3272 #define mmo_get_section_contents_in_window \
3273   _bfd_generic_get_section_contents_in_window
3274 #define mmo_bfd_get_relocated_section_contents \
3275   bfd_generic_get_relocated_section_contents
3276 #define mmo_bfd_gc_sections bfd_generic_gc_sections
3277 #define mmo_bfd_link_hash_table_create _bfd_generic_link_hash_table_create
3278 #define mmo_bfd_link_hash_table_free _bfd_generic_link_hash_table_free
3279 #define mmo_bfd_link_add_symbols _bfd_generic_link_add_symbols
3280 #define mmo_bfd_link_just_syms _bfd_generic_link_just_syms
3281 #define mmo_bfd_final_link _bfd_generic_final_link
3282 #define mmo_bfd_link_split_section _bfd_generic_link_split_section
3283
3284 /* Strictly speaking, only MMIX uses this restricted format, but let's not
3285    stop anybody from shooting themselves in the foot.  */
3286 #define mmo_set_arch_mach bfd_default_set_arch_mach
3287 #define mmo_bfd_relax_section bfd_generic_relax_section
3288 #define mmo_bfd_merge_sections bfd_generic_merge_sections
3289 #define mmo_bfd_is_group_section bfd_generic_is_group_section
3290 #define mmo_bfd_discard_group bfd_generic_discard_group
3291
3292 /* objcopy will be upset if we return -1 from bfd_get_reloc_upper_bound by
3293    using BFD_JUMP_TABLE_RELOCS (_bfd_norelocs) rather than 0.  FIXME: Most
3294    likely a bug in the _bfd_norelocs definition.
3295
3296    On the other hand, we smuggle in an mmo object (because setting up ELF
3297    is too cumbersome) when linking (from other formats, presumably ELF) to
3298    represent the g255 entry.  We need to link that object, so need to say
3299    it has no relocs.  Upper bound for the size of the relocation table is
3300    the size of a NULL pointer, and we support "canonicalization" for that
3301    pointer.  */
3302 #define mmo_bfd_reloc_type_lookup _bfd_norelocs_bfd_reloc_type_lookup
3303
3304 /* We want to copy time of creation, otherwise we'd use
3305    BFD_JUMP_TABLE_COPY (_bfd_generic).  */
3306 #define mmo_bfd_merge_private_bfd_data _bfd_generic_bfd_merge_private_bfd_data
3307 #define mmo_bfd_copy_private_section_data _bfd_generic_bfd_copy_private_section_data
3308 #define mmo_bfd_copy_private_symbol_data _bfd_generic_bfd_copy_private_symbol_data
3309 #define mmo_bfd_copy_private_header_data _bfd_generic_bfd_copy_private_header_data
3310 #define mmo_bfd_set_private_flags _bfd_generic_bfd_set_private_flags
3311 #define mmo_bfd_print_private_bfd_data _bfd_generic_bfd_print_private_bfd_data
3312
3313 const bfd_target bfd_mmo_vec =
3314 {
3315   "mmo",                        /* name */
3316   bfd_target_mmo_flavour,
3317   BFD_ENDIAN_BIG,               /* target byte order */
3318   BFD_ENDIAN_BIG,               /* target headers byte order */
3319
3320   /* FIXME: Might need adjustments.  */
3321   (HAS_RELOC | EXEC_P |         /* object flags */
3322    HAS_LINENO | HAS_DEBUG |
3323    HAS_SYMS | HAS_LOCALS | WP_TEXT),
3324
3325   /* FIXME: Might need adjustments.  */
3326   (SEC_CODE | SEC_DATA | SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD
3327    | SEC_READONLY | SEC_EXCLUDE | SEC_DEBUGGING | SEC_IN_MEMORY),
3328                                 /* section flags */
3329   0,                            /* leading underscore */
3330   ' ',                          /* ar_pad_char */
3331   16,                           /* ar_max_namelen */
3332   bfd_getb64, bfd_getb_signed_64, bfd_putb64,
3333   bfd_getb32, bfd_getb_signed_32, bfd_putb32,
3334   bfd_getb16, bfd_getb_signed_16, bfd_putb16,   /* data */
3335   bfd_getb64, bfd_getb_signed_64, bfd_putb64,
3336   bfd_getb32, bfd_getb_signed_32, bfd_putb32,
3337   bfd_getb16, bfd_getb_signed_16, bfd_putb16,   /* hdrs */
3338
3339   {
3340     _bfd_dummy_target,
3341     mmo_object_p,               /* bfd_check_format */
3342     _bfd_dummy_target,
3343     _bfd_dummy_target,
3344   },
3345   {
3346     bfd_false,
3347     mmo_mkobject,
3348     bfd_false,
3349     bfd_false,
3350   },
3351   {                             /* bfd_write_contents */
3352     bfd_false,
3353     mmo_write_object_contents,
3354     bfd_false,
3355     bfd_false,
3356   },
3357
3358   BFD_JUMP_TABLE_GENERIC (mmo),
3359   BFD_JUMP_TABLE_COPY (mmo),
3360   BFD_JUMP_TABLE_CORE (_bfd_nocore),
3361   BFD_JUMP_TABLE_ARCHIVE (_bfd_noarchive),
3362   BFD_JUMP_TABLE_SYMBOLS (mmo),
3363   /* We have to provide a valid method for getting relocs, returning zero,
3364      so we can't say BFD_JUMP_TABLE_RELOCS (_bfd_norelocs).  */
3365   BFD_JUMP_TABLE_RELOCS (mmo),
3366   BFD_JUMP_TABLE_WRITE (mmo),
3367   BFD_JUMP_TABLE_LINK (mmo),
3368   BFD_JUMP_TABLE_DYNAMIC (_bfd_nodynamic),
3369
3370   NULL,
3371
3372   NULL
3373 };