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
8This file is part of BFD, the Binary File Descriptor library.
9
10This program is free software; you can redistribute it and/or modify
11it under the terms of the GNU General Public License as published by
12the Free Software Foundation; either version 2 of the License, or
13(at your option) any later version.
14
15This program is distributed in the hope that it will be useful,
16but WITHOUT ANY WARRANTY; without even the implied warranty of
17MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18GNU General Public License for more details.
19
20You should have received a copy of the GNU General Public License
21along with this program; if not, write to the Free Software
22Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
23
24/*
25SECTION
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
51INODE
52File layout, Symbol-table, mmo, mmo
53SUBSECTION
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
169EXAMPLE
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
254enum 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
260struct 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
269struct 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
278typedef struct mmo_data_list_struct mmo_data_list_type;
279
280struct 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
294struct 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
330typedef struct mmo_data_struct tdata_type;
331
332struct 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.  */
345struct 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.  */
352struct mmo_find_sec_info
353  {
354    asection *sec;
355    bfd_vma addr;
356  };
357
358static bfd_boolean mmo_bfd_copy_private_bfd_data
359  PARAMS ((bfd *, bfd *));
360static void mmo_write_section_unless_reg_contents
361 PARAMS ((bfd *, asection *, PTR));
362static void mmo_find_sec_w_addr
363  PARAMS ((bfd *, asection *, PTR));
364static void mmo_find_sec_w_addr_grow
365  PARAMS ((bfd *, asection *, PTR));
366static asection *mmo_make_section
367  PARAMS ((bfd *, const char *));
368static void mmo_get_symbol_info
369  PARAMS ((bfd *, asymbol *, symbol_info *));
370static void mmo_print_symbol
371  PARAMS ((bfd *, PTR, asymbol *, bfd_print_symbol_type));
372static void mmo_init
373  PARAMS ((void));
374static bfd_boolean mmo_mkobject
375  PARAMS ((bfd *));
376static bfd_boolean mmo_scan
377  PARAMS ((bfd *));
378static asection *mmo_decide_section
379  PARAMS ((bfd *, bfd_vma));
380static asection *mmo_get_generic_spec_data_section
381  PARAMS ((bfd *, int));
382static asection *mmo_get_spec_section
383  PARAMS ((bfd *, int));
384static INLINE bfd_byte *mmo_get_loc
385  PARAMS ((asection *, bfd_vma, int));
386static void mmo_xore_64
387  PARAMS ((asection *, bfd_vma vma, bfd_vma value));
388static void mmo_xore_32
389  PARAMS ((asection *, bfd_vma vma, unsigned int));
390static void mmo_xore_16
391  PARAMS ((asection *, bfd_vma vma, unsigned int));
392static const bfd_target *mmo_object_p
393  PARAMS ((bfd *));
394static void mmo_map_set_sizes
395  PARAMS ((bfd *, asection *, PTR));
396static bfd_boolean mmo_get_symbols
397  PARAMS ((bfd *));
398static bfd_boolean mmo_create_symbol
399  PARAMS ((bfd *, const char *, bfd_vma, enum mmo_sym_type, unsigned int));
400static bfd_boolean mmo_get_section_contents
401  PARAMS ((bfd *, asection *, PTR, file_ptr, bfd_size_type));
402static long mmo_get_symtab_upper_bound
403  PARAMS ((bfd *));
404static long mmo_canonicalize_symtab
405  PARAMS ((bfd *, asymbol **));
406static void mmo_get_symbol_info
407  PARAMS ((bfd *, asymbol *, symbol_info *));
408static void mmo_print_symbol
409  PARAMS ((bfd *, PTR, asymbol *, bfd_print_symbol_type));
410static bfd_boolean mmo_set_section_contents
411  PARAMS ((bfd *, sec_ptr, const PTR, file_ptr, bfd_size_type));
412static int mmo_sizeof_headers
413  PARAMS ((bfd *, bfd_boolean));
414static long mmo_get_reloc_upper_bound
415  PARAMS ((bfd *, asection *));
416
417static bfd_boolean mmo_internal_write_header
418  PARAMS ((bfd *));
419static bfd_boolean mmo_internal_write_post
420  PARAMS ((bfd *, int, asection *));
421static bfd_boolean mmo_internal_add_3_sym
422  PARAMS ((bfd *, struct mmo_symbol_trie *, const struct mmo_symbol *));
423static unsigned int mmo_internal_3_length
424  PARAMS ((bfd *, struct mmo_symbol_trie *));
425static void mmo_internal_3_dump
426  PARAMS ((bfd *, struct mmo_symbol_trie *));
427static void mmo_beb128_out
428  PARAMS ((bfd *, int, int));
429static bfd_boolean mmo_internal_write_section
430  PARAMS ((bfd *, asection *));
431static void mmo_write_tetra
432  PARAMS ((bfd *, unsigned int));
433static void mmo_write_tetra_raw
434  PARAMS ((bfd *, unsigned int));
435static void mmo_write_octa
436  PARAMS ((bfd *, bfd_vma));
437static void mmo_write_octa_raw
438  PARAMS ((bfd *, bfd_vma));
439static bfd_boolean mmo_write_chunk
440  PARAMS ((bfd *, const bfd_byte *, unsigned int));
441static bfd_boolean mmo_flush_chunk
442  PARAMS ((bfd *));
443static bfd_boolean mmo_write_loc_chunk
444  PARAMS ((bfd *, bfd_vma, const bfd_byte *, unsigned int, bfd_vma *));
445static bfd_boolean mmo_write_chunk_list
446  PARAMS ((bfd *, mmo_data_list_type *));
447static bfd_boolean mmo_write_loc_chunk_list
448  PARAMS ((bfd *, mmo_data_list_type *));
449static bfd_boolean mmo_write_symbols_and_terminator
450  PARAMS ((bfd *));
451static flagword mmo_sec_flags_from_bfd_flags
452  PARAMS ((flagword));
453static flagword bfd_sec_flags_from_mmo_flags
454  PARAMS ((flagword));
455static bfd_byte mmo_get_byte
456  PARAMS ((bfd *));
457static void mmo_write_byte
458  PARAMS ((bfd *, bfd_byte));
459static bfd_boolean mmo_new_section_hook
460  PARAMS ((bfd *, asection *));
461static int mmo_sort_mmo_symbols
462  PARAMS ((const PTR, const PTR));
463static bfd_boolean mmo_write_object_contents
464  PARAMS ((bfd *));
465static 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
472static unsigned
473char 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
489static asection *
490mmo_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
518static void
519mmo_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
541static const bfd_target *
542mmo_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
609static bfd_boolean
610mmo_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
634static bfd_boolean
635mmo_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
654static void
655mmo_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->size)
669    infop->sec = sec;
670}
671
672static void
673mmo_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
695static asection *
696mmo_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
766static INLINE void
767mmo_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
781static INLINE void
782mmo_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
796static INLINE void
797mmo_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
811static INLINE void
812mmo_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
826static INLINE void
827mmo_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
839static INLINE void
840mmo_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
850static INLINE void
851mmo_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
862static INLINE bfd_boolean
863mmo_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
914static INLINE bfd_boolean
915mmo_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
932static INLINE bfd_boolean
933mmo_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
948static bfd_boolean
949mmo_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
999static INLINE bfd_boolean
1000mmo_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
1017static asection *
1018mmo_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
1037static asection *
1038mmo_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, sec->size + section_length)
1172      /* Set VMA only for the first occurrence.  */
1173      || (! sec->user_set_vma
1174	  && ! bfd_set_section_vma  (abfd, sec, section_vma)))
1175    {
1176      /* If we get an error for any of the calls above, signal more than
1177	 just a format error for the spec section.  */
1178      return NULL;
1179    }
1180
1181  loc->next = NULL;
1182  if (mmo_section_data (sec)->tail != NULL)
1183    mmo_section_data (sec)->tail->next = loc;
1184  else
1185    mmo_section_data (sec)->head = loc;
1186  mmo_section_data (sec)->tail = loc;
1187  loc->where = section_vma;
1188
1189  return sec;
1190
1191 format_error_free:
1192  free (secname);
1193 format_error:
1194  if (bfd_seek (abfd, orig_pos, SEEK_SET) != 0)
1195    return NULL;
1196
1197  return mmo_get_generic_spec_data_section (abfd, spec_data_number);
1198}
1199
1200/* Read a byte, but read from file in multiples of 32-bit words.  */
1201
1202static bfd_byte
1203mmo_get_byte (abfd)
1204     bfd *abfd;
1205{
1206  bfd_byte retval;
1207
1208  if (abfd->tdata.mmo_data->byte_no == 0)
1209    {
1210      if (! abfd->tdata.mmo_data->have_error
1211	  && bfd_bread (abfd->tdata.mmo_data->buf, 4, abfd) != 4)
1212	{
1213	  abfd->tdata.mmo_data->have_error = TRUE;
1214
1215	  /* A value somewhat safe against tripping on some inconsistency
1216	     when mopping up after this error.  */
1217	  return 128;
1218	}
1219    }
1220
1221  retval = abfd->tdata.mmo_data->buf[abfd->tdata.mmo_data->byte_no];
1222  abfd->tdata.mmo_data->byte_no = (abfd->tdata.mmo_data->byte_no + 1) % 4;
1223
1224  return retval;
1225}
1226
1227/* Write a byte, in multiples of 32-bit words.  */
1228
1229static void
1230mmo_write_byte (abfd, value)
1231     bfd *abfd;
1232     bfd_byte value;
1233{
1234  abfd->tdata.mmo_data->buf[(abfd->tdata.mmo_data->byte_no++ % 4)] = value;
1235  if ((abfd->tdata.mmo_data->byte_no % 4) == 0)
1236    {
1237      if (! abfd->tdata.mmo_data->have_error
1238	  && bfd_bwrite (abfd->tdata.mmo_data->buf, 4, abfd) != 4)
1239	abfd->tdata.mmo_data->have_error = TRUE;
1240    }
1241}
1242
1243/* Create a symbol.  */
1244
1245static bfd_boolean
1246mmo_create_symbol (abfd, symname, addr, sym_type, serno)
1247     bfd *abfd;
1248     const char *symname;
1249     bfd_vma addr;
1250     enum mmo_sym_type sym_type;
1251     unsigned int serno;
1252{
1253  struct mmo_symbol *n;
1254
1255  n = (struct mmo_symbol *) bfd_alloc (abfd, sizeof (struct mmo_symbol));
1256  if (n == NULL)
1257    return FALSE;
1258
1259  n->name = bfd_alloc (abfd, strlen (symname) + 1);
1260  if (n->name == NULL)
1261    return FALSE;
1262
1263  strcpy ((PTR) n->name, symname);
1264
1265  n->value = addr;
1266  n->sym_type = sym_type;
1267  n->serno = serno;
1268
1269  if (abfd->tdata.mmo_data->symbols == NULL)
1270    abfd->tdata.mmo_data->symbols = n;
1271  else
1272    abfd->tdata.mmo_data->symtail->next = n;
1273  abfd->tdata.mmo_data->symtail = n;
1274  n->next = NULL;
1275
1276  ++abfd->symcount;
1277
1278  /* Check that :Main equals the last octa of the .MMIX.reg_contents
1279     section, as it's the one place we're sure to pass when reading a mmo
1280     object.  For written objects, we do it while setting the symbol
1281     table.  */
1282  if (strcmp (symname, MMIX_START_SYMBOL_NAME) == 0
1283      && bfd_get_start_address (abfd) != addr)
1284    {
1285      (*_bfd_error_handler)
1286	(_("%s: invalid mmo file: initialization value for $255 is not `Main'\n"),
1287	 bfd_get_filename (abfd));
1288      bfd_set_error (bfd_error_bad_value);
1289      return FALSE;
1290    }
1291
1292  return TRUE;
1293}
1294
1295/* Read in symbols.  */
1296
1297static bfd_boolean
1298mmo_get_symbols (abfd)
1299     bfd *abfd;
1300{
1301/*
1302INODE
1303Symbol-table, mmo section mapping, File layout, mmo
1304SUBSECTION
1305	Symbol table format
1306
1307	From mmixal.w (or really, the generated mmixal.tex) in
1308	@url{http://www-cs-faculty.stanford.edu/~knuth/programs/mmix.tar.gz}):
1309	``Symbols are stored and retrieved by means of a @samp{ternary
1310	search trie}, following ideas of Bentley and Sedgewick. (See
1311	ACM--SIAM Symp.@: on Discrete Algorithms @samp{8} (1997), 360--369;
1312	R.@:Sedgewick, @samp{Algorithms in C} (Reading, Mass.@:
1313	Addison--Wesley, 1998), @samp{15.4}.)  Each trie node stores a
1314	character, and there are branches to subtries for the cases where
1315	a given character is less than, equal to, or greater than the
1316	character in the trie.  There also is a pointer to a symbol table
1317	entry if a symbol ends at the current node.''
1318
1319	So it's a tree encoded as a stream of bytes.  The stream of bytes
1320	acts on a single virtual global symbol, adding and removing
1321	characters and signalling complete symbol points.  Here, we read
1322	the stream and create symbols at the completion points.
1323
1324	First, there's a control byte <<m>>.  If any of the listed bits
1325	in <<m>> is nonzero, we execute what stands at the right, in
1326	the listed order:
1327
1328| (MMO3_LEFT)
1329| 0x40 - Traverse left trie.
1330|        (Read a new command byte and recurse.)
1331|
1332| (MMO3_SYMBITS)
1333| 0x2f - Read the next byte as a character and store it in the
1334|        current character position; increment character position.
1335|        Test the bits of <<m>>:
1336|
1337|        (MMO3_WCHAR)
1338|        0x80 - The character is 16-bit (so read another byte,
1339|               merge into current character.
1340|
1341|        (MMO3_TYPEBITS)
1342|        0xf  - We have a complete symbol; parse the type, value
1343|               and serial number and do what should be done
1344|               with a symbol.  The type and length information
1345|               is in j = (m & 0xf).
1346|
1347|               (MMO3_REGQUAL_BITS)
1348|	        j == 0xf: A register variable.  The following
1349|                         byte tells which register.
1350|               j <= 8:   An absolute symbol.  Read j bytes as the
1351|                         big-endian number the symbol equals.
1352|                         A j = 2 with two zero bytes denotes an
1353|                         unknown symbol.
1354|               j > 8:    As with j <= 8, but add (0x20 << 56)
1355|                         to the value in the following j - 8
1356|                         bytes.
1357|
1358|               Then comes the serial number, as a variant of
1359|               uleb128, but better named ubeb128:
1360|               Read bytes and shift the previous value left 7
1361|               (multiply by 128).  Add in the new byte, repeat
1362|               until a byte has bit 7 set.  The serial number
1363|               is the computed value minus 128.
1364|
1365|        (MMO3_MIDDLE)
1366|        0x20 - Traverse middle trie.  (Read a new command byte
1367|               and recurse.)  Decrement character position.
1368|
1369| (MMO3_RIGHT)
1370| 0x10 - Traverse right trie.  (Read a new command byte and
1371|        recurse.)
1372
1373	Let's look again at the <<lop_stab>> for the trivial file
1374	(@pxref{File layout}).
1375
1376| 0x980b0000 - lop_stab for ":Main" = 0, serial 1.
1377| 0x203a4040
1378| 0x10404020
1379| 0x4d206120
1380| 0x69016e00
1381| 0x81000000
1382
1383	This forms the trivial trie (note that the path between ``:'' and
1384	``M'' is redundant):
1385
1386| 203a	   ":"
1387| 40       /
1388| 40      /
1389| 10      \
1390| 40      /
1391| 40     /
1392| 204d  "M"
1393| 2061  "a"
1394| 2069  "i"
1395| 016e  "n" is the last character in a full symbol, and
1396|       with a value represented in one byte.
1397| 00    The value is 0.
1398| 81    The serial number is 1.  */
1399
1400  bfd_byte m = mmo_get_byte (abfd);
1401
1402  /* Check first if we have a bad hair day.  */
1403  if (abfd->tdata.mmo_data->have_error)
1404    return FALSE;
1405
1406  if (m & MMO3_LEFT)
1407    /* Traverse left trie. */
1408    mmo_get_symbols (abfd);
1409
1410  if (m & MMO3_SYMBITS)
1411    {
1412      bfd_byte c = mmo_get_byte (abfd);
1413      bfd_byte j = m & MMO3_TYPEBITS;
1414      bfd_vma addr = 0;
1415      enum mmo_sym_type sym_type;
1416      unsigned int serno = 0;
1417      bfd_byte k;
1418
1419      if (m & MMO3_WCHAR)
1420	{
1421	  bfd_byte c2 = mmo_get_byte (abfd);
1422
1423	  /* A two-byte character.  We can't grok this, but neither can
1424	     mmotype, for other cases than the second byte being zero.  */
1425
1426	  if (c != 0)
1427	    {
1428	      abfd->tdata.mmo_data->lop_stab_symbol
1429		[abfd->tdata.mmo_data->symbol_position] = 0;
1430
1431	      (*_bfd_error_handler)
1432		(_("%s: unsupported wide character sequence\
1433 0x%02X 0x%02X after symbol name starting with `%s'\n"),
1434		 bfd_get_filename (abfd), c, c2,
1435		 abfd->tdata.mmo_data->lop_stab_symbol);
1436	      bfd_set_error (bfd_error_bad_value);
1437	      abfd->tdata.mmo_data->have_error = TRUE;
1438	      return FALSE;
1439	    }
1440	  else
1441	    c = c2;
1442	}
1443
1444      abfd->tdata.mmo_data->lop_stab_symbol[abfd->tdata.mmo_data->symbol_position++] = c;
1445      abfd->tdata.mmo_data->lop_stab_symbol[abfd->tdata.mmo_data->symbol_position] = 0;
1446
1447      if (j & MMO3_REGQUAL_BITS)
1448	{
1449	  if (j == MMO3_REGQUAL_BITS)
1450	    {
1451	      sym_type = mmo_reg_sym;
1452	      addr = mmo_get_byte (abfd);
1453	    }
1454	  else if (j <= 8)
1455	    {
1456	      unsigned int i;
1457
1458	      for (i = 0; i < j; i++)
1459		addr = (addr << 8) + mmo_get_byte (abfd);
1460
1461	      if (addr == 0 && j == MMO3_UNDEF)
1462		sym_type = mmo_undef_sym;
1463	      else
1464		sym_type = mmo_abs_sym;
1465	    }
1466	  else
1467	    {
1468	      unsigned int i;
1469
1470	      for (i = MMO3_DATA; i < j; i++)
1471		addr = (addr << 8) + mmo_get_byte (abfd);
1472
1473	      addr += (bfd_vma) 0x20 << 56;
1474	      sym_type = mmo_data_sym;
1475	    }
1476
1477	  /* Get the serial number.  */
1478	  do
1479	    {
1480	      k = mmo_get_byte (abfd);
1481	      serno = (serno << 7) + k;
1482	    }
1483	  while (k < 128);
1484	  serno -= 128;
1485
1486	  /* Got it.  Now enter it.  Skip a leading ":".  */
1487	  if (! abfd->tdata.mmo_data->have_error
1488	      && ! mmo_create_symbol (abfd,
1489				      abfd->tdata.mmo_data->lop_stab_symbol
1490				      + 1,
1491				      addr, sym_type, serno))
1492	    abfd->tdata.mmo_data->have_error = TRUE;
1493	}
1494
1495      if (m & MMO3_MIDDLE)
1496	/* Traverse middle trie. */
1497	mmo_get_symbols (abfd);
1498
1499      abfd->tdata.mmo_data->symbol_position--;
1500    }
1501
1502  if (m & MMO3_RIGHT)
1503    /* Traverse right trie.  */
1504    mmo_get_symbols (abfd);
1505
1506  return ! abfd->tdata.mmo_data->have_error;
1507}
1508
1509/* Get the location of memory area [VMA..VMA + SIZE - 1], which we think
1510   is in section SEC.  Adjust and reallocate zero-initialized contents.
1511   If there's new contents, allocate to the next multiple of
1512   MMO_SEC_CONTENTS_CHUNK_SIZE.  */
1513
1514static INLINE bfd_byte *
1515mmo_get_loc (sec, vma, size)
1516     asection *sec;
1517     bfd_vma vma;
1518     int size;
1519{
1520  bfd_size_type allocated_size;
1521  struct mmo_section_data_struct *sdatap = mmo_section_data (sec);
1522  struct mmo_data_list_struct *datap = sdatap->head;
1523  struct mmo_data_list_struct *entry;
1524
1525  /* First search the list to see if we have the requested chunk in one
1526     piece, or perhaps if we have a suitable chunk with room to fit.  */
1527  for (; datap != NULL; datap = datap->next)
1528    {
1529      if (datap->where <= vma
1530	  && datap->where + datap->size >= vma + size)
1531	return datap->data + vma - datap->where;
1532      else if (datap->where <= vma
1533	       && datap->where + datap->allocated_size >= vma + size
1534	       /* Only munch on the "allocated size" if it does not
1535		  overlap the next chunk.  */
1536	       && (datap->next == NULL || datap->next->where >= vma + size))
1537	{
1538	  /* There was room allocated, but the size wasn't set to include
1539	     it.  Do that now.  */
1540	  datap->size += (vma + size) - (datap->where + datap->size);
1541
1542	  /* Update the section size.  This happens only if we update the
1543	     32-bit-aligned chunk size.  Callers that have
1544	     non-32-bit-aligned sections should do all allocation and
1545	     size-setting by themselves or at least set the section size
1546	     after the last allocating call to this function.  */
1547	  if (vma + size > sec->vma + sec->size)
1548	    sec->size += (vma + size) - (sec->vma + sec->size);
1549
1550	  return datap->data + vma - datap->where;
1551	}
1552    }
1553
1554  /* Not found; allocate a new block.  First check in case we get a
1555     request for a size split up over several blocks; we'll have to return
1556     NULL for those cases, requesting the caller to split up the request.
1557     Requests with an address aligned on MMO_SEC_CONTENTS_CHUNK_SIZE bytes and
1558     for no more than MMO_SEC_CONTENTS_CHUNK_SIZE will always get resolved.  */
1559
1560  for (datap = sdatap->head; datap != NULL; datap = datap->next)
1561    if ((datap->where <= vma && datap->where + datap->size > vma)
1562	|| (datap->where < vma + size
1563	    && datap->where + datap->size >= vma + size))
1564      return NULL;
1565
1566  allocated_size
1567    = (size + MMO_SEC_CONTENTS_CHUNK_SIZE - 1) & ~(MMO_SEC_CONTENTS_CHUNK_SIZE - 1);
1568  entry = (mmo_data_list_type *)
1569    bfd_zalloc (sec->owner, sizeof (mmo_data_list_type) + allocated_size);
1570  if (entry == NULL)
1571    return NULL;
1572  entry->where = vma;
1573  entry->size = size;
1574  entry->allocated_size = allocated_size;
1575
1576  datap = sdatap->head;
1577
1578  /* Sort the records by address.  Optimize for the common case of adding
1579     a record to the end of the list.  */
1580  if (sdatap->tail != NULL && entry->where >= sdatap->tail->where)
1581    {
1582      sdatap->tail->next = entry;
1583      entry->next = NULL;
1584      sdatap->tail = entry;
1585    }
1586  else
1587    {
1588      mmo_data_list_type **look;
1589      for (look = &sdatap->head;
1590	   *look != NULL && (*look)->where < entry->where;
1591	   look = &(*look)->next)
1592	;
1593      entry->next = *look;
1594      *look = entry;
1595      if (entry->next == NULL)
1596	{
1597	  sdatap->tail = entry;
1598
1599	  /* We get here for the first time (at other times too) for this
1600	     section.  Say we have contents.  */
1601	  if (! bfd_set_section_flags (sec->owner, sec,
1602				       bfd_get_section_flags (sec->owner, sec)
1603				       | SEC_HAS_CONTENTS))
1604	    return NULL;
1605	}
1606    }
1607
1608  /* Update the section size.  This happens only when we add contents and
1609     re-size as we go.  The section size will then be aligned to 32 bits.  */
1610  if (vma + size > sec->vma + sec->size)
1611    sec->size += (vma + size) - (sec->vma + sec->size);
1612  return entry->data;
1613}
1614
1615/* Set sizes once we've read in all sections.  */
1616
1617static void
1618mmo_map_set_sizes (abfd, sec, ignored)
1619     bfd *abfd ATTRIBUTE_UNUSED;
1620     asection *sec;
1621     PTR ignored ATTRIBUTE_UNUSED;
1622{
1623  sec->lma = sec->vma;
1624}
1625
1626/* Read the mmo file and turn it into sections.  */
1627
1628static bfd_boolean
1629mmo_scan (abfd)
1630     bfd *abfd;
1631{
1632  unsigned int i;
1633  unsigned int lineno = 1;
1634  bfd_boolean error = FALSE;
1635  bfd_vma vma = 0;
1636  asection *sec = bfd_make_section_old_way (abfd, MMO_TEXT_SECTION_NAME);
1637  asection *non_spec_sec = NULL;
1638  bfd_vma non_spec_vma = 0;
1639  char *current_filename = NULL;
1640  bfd_size_type nbytes_read = 0;
1641  /* Buffer with room to read a 64-bit value.  */
1642  bfd_byte buf[8];
1643  long stab_loc = -1;
1644  char *file_names[256];
1645
1646  memset (file_names, 0, sizeof (file_names));
1647
1648  if (bfd_seek (abfd, (file_ptr) 0, SEEK_SET) != 0)
1649    goto error_return;
1650
1651  while ((nbytes_read = bfd_bread (buf, 4, abfd)) == 4)
1652    {
1653      if (buf[0] == LOP)
1654	{
1655	  unsigned int y = bfd_get_8 (abfd, buf + 2);
1656	  unsigned int z = bfd_get_8 (abfd, buf + 3);
1657
1658	  /* Change back to the original section for lopcodes other
1659	     than LOP_QUOTE that comes after a LOP_SPEC.  */
1660	  if ((buf[1] != LOP_QUOTE || y != 0 || z != 1)
1661	      && non_spec_sec != NULL)
1662	    {
1663	      sec = non_spec_sec;
1664	      vma = non_spec_vma;
1665	      non_spec_sec = NULL;
1666	    }
1667
1668	  switch (buf[1])
1669	    {
1670	    default:
1671	      (*_bfd_error_handler)
1672		(_("%s: invalid mmo file: unsupported lopcode `%d'\n"),
1673		 bfd_get_filename (abfd), buf[1]);
1674	      bfd_set_error (bfd_error_bad_value);
1675	      goto error_return;
1676
1677	    case LOP_QUOTE:
1678	      /* Quote the next 32-bit word.  */
1679	      if (y != 0 || z != 1)
1680		{
1681		  (*_bfd_error_handler)
1682		    (_("%s: invalid mmo file: expected YZ = 1 got YZ = %d for lop_quote\n"),
1683		     bfd_get_filename (abfd), y*256+z);
1684		  bfd_set_error (bfd_error_bad_value);
1685		  goto error_return;
1686		}
1687	      if (bfd_bread (buf, 4, abfd) != 4)
1688		goto error_return;
1689
1690	      mmo_xore_32 (sec, vma, bfd_get_32 (abfd, buf));
1691	      vma += 4;
1692	      vma &= ~3;
1693	      lineno++;
1694	      break;
1695
1696	    case LOP_LOC:
1697	      /* Set vma (and section).  */
1698	      vma = (bfd_vma) y << 56;
1699	      if (z == 1)
1700		{
1701		  /* Get a 32-bit value.  */
1702		  if (bfd_bread (buf, 4, abfd) != 4)
1703		    goto error_return;
1704
1705		  vma += bfd_get_32 (abfd, buf);
1706		}
1707	      else if (z == 2)
1708		{
1709		  /* Get a 64-bit value.  */
1710		  if (bfd_bread (buf, 8, abfd) != 8)
1711		    goto error_return;
1712
1713		  vma += bfd_get_64 (abfd, buf);
1714		}
1715	      else
1716		{
1717		  (*_bfd_error_handler)
1718		    (_("%s: invalid mmo file: expected z = 1 or z = 2, got z = %d for lop_loc\n"),
1719		     bfd_get_filename (abfd), z);
1720		  bfd_set_error (bfd_error_bad_value);
1721		  goto error_return;
1722		}
1723
1724	      sec = mmo_decide_section (abfd, vma);
1725	      if (sec == NULL)
1726		goto error_return;
1727	      break;
1728
1729	    case LOP_SKIP:
1730	      /* Move forward within the same section.  */
1731	      vma += y * 256 + z;
1732
1733	      sec = mmo_decide_section (abfd, vma);
1734	      if (sec == NULL)
1735		goto error_return;
1736	      break;
1737
1738	    case LOP_FIXO:
1739	      /* A fixup: Store the current vma somewhere.  Position using
1740		 same format as LOP_LOC.  */
1741	      {
1742		bfd_vma p = (bfd_vma) y << 56;
1743		asection *fixosec;
1744
1745		if (z == 1)
1746		  {
1747		    /* Get a 32-bit value.  */
1748		    if (bfd_bread (buf, 4, abfd) != 4)
1749		      goto error_return;
1750
1751		    p += bfd_get_32 (abfd, buf);
1752		  }
1753		else if (z == 2)
1754		  {
1755		    /* Get a 64-bit value.  */
1756		    if (bfd_bread (buf, 8, abfd) != 8)
1757		      goto error_return;
1758
1759		    p += bfd_get_64 (abfd, buf);
1760		  }
1761		else
1762		  {
1763		    (*_bfd_error_handler)
1764		      (_("%s: invalid mmo file: expected z = 1 or z = 2, got z = %d for lop_fixo\n"),
1765		       bfd_get_filename (abfd), z);
1766		    bfd_set_error (bfd_error_bad_value);
1767		    goto error_return;
1768		  }
1769
1770		/* The section where we store this address might be a
1771		   different one than the current section.  */
1772		fixosec = mmo_decide_section (abfd, p);
1773		if (fixosec == NULL)
1774		  goto error_return;
1775		mmo_xore_64 (fixosec, p, vma);
1776	      }
1777	    break;
1778
1779	    case LOP_FIXR:
1780	      /* A fixup: Store YZ of this lopcode into YZ at vma - 4 * yz.  */
1781	      {
1782		unsigned int yz = (y * 256 + z);
1783		bfd_vma p = vma + 2 - 4 * yz;
1784		asection *fixrsec = mmo_decide_section (abfd, p);
1785		if (fixrsec == NULL)
1786		  goto error_return;
1787		mmo_xore_16 (fixrsec, p, yz);
1788	      }
1789	    break;
1790
1791	    case LOP_FIXRX:
1792	      /* A fixup, similar to lop_fixr, but taking larger numbers
1793		 and can change branches into the opposite direction
1794		 (gasp!).  */
1795	      {
1796		bfd_vma delta;
1797		bfd_vma p;
1798		asection *fixrsec;
1799
1800		if (y != 0)
1801		  {
1802		    (*_bfd_error_handler)
1803		      (_("%s: invalid mmo file: expected y = 0, got y = %d for lop_fixrx\n"),
1804		       bfd_get_filename (abfd), y);
1805		    bfd_set_error (bfd_error_bad_value);
1806		    goto error_return;
1807		  }
1808
1809		if (z != 16 && z != 24)
1810		  {
1811		    (*_bfd_error_handler)
1812		      (_("%s: invalid mmo file: expected z = 16 or z = 24, got z = %d for lop_fixrx\n"),
1813		       bfd_get_filename (abfd), z);
1814		    bfd_set_error (bfd_error_bad_value);
1815		    goto error_return;
1816		  }
1817
1818		/* Get the next 32-bit value.  */
1819		if (bfd_bread (buf, 4, abfd) != 4)
1820		  goto error_return;
1821
1822		delta = bfd_get_32 (abfd, buf);
1823
1824		/* Do an, ehm, involved calculation for the location of
1825		   the fixup.  See mmixal documentation for a verbose
1826		   explanation.  We follow it verbosely here for the
1827		   readers delight.  */
1828		if (buf[0] == 0)
1829		  p = vma - 4 * delta;
1830		else if (buf[0] == 1)
1831		  p = vma - 4 * ((delta & 0xffffff) - (1 << z));
1832		else
1833		  {
1834		    (*_bfd_error_handler)
1835		      (_("%s: invalid mmo file: leading byte of operand word must be 0 or 1, got %d for lop_fixrx\n"),
1836		       bfd_get_filename (abfd), buf[0]);
1837		    bfd_set_error (bfd_error_bad_value);
1838		    goto error_return;
1839		  }
1840
1841		fixrsec = mmo_decide_section (abfd, vma);
1842		if (fixrsec == NULL)
1843		  goto error_return;
1844		mmo_xore_32 (fixrsec, p, delta);
1845	      }
1846	    break;
1847
1848	    case LOP_FILE:
1849	      /* Set current file and perhaps the file name.  Reset line
1850		 number.  */
1851	      if (z != 0)
1852		{
1853		  char *fname = bfd_malloc (z * 4 + 1);
1854
1855		  if (fname == NULL)
1856		    {
1857		      (*_bfd_error_handler)
1858			(_("%s: cannot allocate file name for file number %d, %d bytes\n"),
1859			 bfd_get_filename (abfd), y, z * 4 + 1);
1860		      bfd_set_error (bfd_error_system_call);
1861		      goto error_return;
1862		    }
1863
1864		  fname[z * 4] = 0;
1865
1866		  for (i = 0; i < z; i++)
1867		    {
1868		      if (bfd_bread (fname + i * 4, 4, abfd) != 4)
1869			{
1870			  free (fname);
1871			  goto error_return;
1872			}
1873		    }
1874
1875		  if (file_names[y] != NULL)
1876		    {
1877		      (*_bfd_error_handler)
1878			(_("%s: invalid mmo file: file number %d `%s',\
1879 was already entered as `%s'\n"),
1880			 bfd_get_filename (abfd), y, fname, file_names[y]);
1881		      bfd_set_error (bfd_error_bad_value);
1882		      goto error_return;
1883		    }
1884
1885		  file_names[y] = fname;
1886		}
1887
1888	      if (file_names[y] == NULL)
1889		{
1890		  (*_bfd_error_handler)
1891		    (_("%s: invalid mmo file: file name for number %d\
1892 was not specified before use\n"),
1893		     bfd_get_filename (abfd), y);
1894		  bfd_set_error (bfd_error_bad_value);
1895		  goto error_return;
1896		}
1897
1898	      current_filename = file_names[y];
1899	      lineno = 0;
1900	      break;
1901
1902	    case LOP_LINE:
1903	      /* Set line number.  */
1904	      lineno = y * 256 + z;
1905	      /* FIXME: Create a sequence of mmo-specific line number
1906		 entries for each section, then translate into canonical
1907		 format.  */
1908	      break;
1909
1910	    case LOP_SPEC:
1911	      /* Special data follows until the next non-lop_quote
1912		 lopcode.  */
1913	      non_spec_sec = sec;
1914	      non_spec_vma = vma;
1915	      sec = mmo_get_spec_section (abfd, y * 256 + z);
1916	      if (sec == NULL)
1917		goto error_return;
1918
1919	      vma = sec->vma;
1920	      break;
1921
1922	    case LOP_PRE:
1923	      {
1924		/* We ignore header information, except we read in the
1925		   creation time from the first 32-bit word with the time
1926		   in seconds since era.  */
1927		if (z >= 1
1928		    && bfd_bread (abfd->tdata.mmo_data->created, 4,
1929				 abfd) != 4)
1930		  goto error_return;
1931
1932		for (i = 1; i < z; i++)
1933		  if (bfd_bread (buf, 4, abfd) != 4)
1934		    goto error_return;
1935	      }
1936	      break;
1937
1938	    case LOP_POST:
1939	      /* This tells of the contents of registers $Z..$255 at
1940		 startup.  We make a section out of it, with VMA = Z * 8,
1941		 but only if Z != 255 or the contents is non-zero.  */
1942	      {
1943		asection *rsec;
1944		bfd_byte *loc;
1945		bfd_vma first_octa;
1946		bfd_vma startaddr_octa;
1947
1948		/* Read first octaword outside loop to simplify logic when
1949		   excluding the Z == 255, octa == 0 case.  */
1950		if (bfd_bread (buf, 8, abfd) != 8)
1951		  goto error_return;
1952
1953		first_octa = bfd_get_64 (abfd, buf);
1954
1955		/* Don't emit contents for the trivial case which is
1956		   always present; $255 pointing to Main.  */
1957		if (z != 255)
1958		  {
1959		    rsec
1960		      = bfd_make_section_old_way (abfd,
1961						  MMIX_REG_CONTENTS_SECTION_NAME);
1962		    rsec->vma = z * 8;
1963		    loc = mmo_get_loc (rsec, z * 8, (255 - z) * 8);
1964		    bfd_put_64 (abfd, first_octa, loc);
1965
1966		    for (i = z + 1; i < 255; i++)
1967		      {
1968			if (bfd_bread (loc + (i - z) * 8, 8, abfd) != 8)
1969			  goto error_return;
1970		      }
1971
1972		    /* Read out the last octabyte, and use it to set the
1973		       start address.  */
1974		    if (bfd_bread (buf, 8, abfd) != 8)
1975		      goto error_return;
1976
1977		    startaddr_octa = bfd_get_64 (abfd, buf);
1978		  }
1979		else
1980		  startaddr_octa = first_octa;
1981
1982		if (! bfd_set_start_address (abfd, startaddr_octa))
1983		  {
1984		    /* Currently this can't fail, but this should handle
1985		       future failures.  */
1986		    bfd_set_error (bfd_error_bad_value);
1987		    goto error_return;
1988		  }
1989	      }
1990	      break;
1991
1992	    case LOP_STAB:
1993	      /* We read in the symbols now, not later.  */
1994	      if (y != 0 || z != 0)
1995		{
1996		  (*_bfd_error_handler)
1997		    (_("%s: invalid mmo file: fields y and z of lop_stab\
1998 non-zero, y: %d, z: %d\n"),
1999		     bfd_get_filename (abfd), y, z);
2000		  bfd_set_error (bfd_error_bad_value);
2001		  goto error_return;
2002		}
2003
2004	      /* Save the location, so we can check that YZ in the LOP_END
2005		 is correct.  */
2006	      stab_loc = bfd_tell (abfd);
2007
2008	      /* It's not said that an MMO can be without symbols (though
2009		 mmixal will refuse to assemble files without Main), but
2010		 it seems it would still be a valid mmo-file, so allow it.
2011		 We detect the absence of a symbol area in that the upper
2012		 limit is computed (from the lop_end YZ field) as 0.
2013		 Don't call mmo_get_symbols; it can only detect the end of
2014		 a valid symbol trie, not the absence of one.  */
2015	      if (abfd->tdata.mmo_data->max_symbol_length != 0
2016		  && ! mmo_get_symbols (abfd))
2017		goto error_return;
2018	      break;
2019
2020	    case LOP_END:
2021	      {
2022		/* This must be the last 32-bit word in an mmo file.
2023		   Let's find out.  */
2024		struct stat statbuf;
2025		long curpos = bfd_tell (abfd);
2026
2027		if (bfd_stat (abfd, &statbuf) < 0)
2028		  goto error_return;
2029
2030		if (statbuf.st_size != curpos)
2031		  {
2032		    (*_bfd_error_handler)
2033		      (_("%s: invalid mmo file: lop_end not last item in\
2034 file\n"),
2035		       bfd_get_filename (abfd));
2036		    bfd_set_error (bfd_error_bad_value);
2037		    goto error_return;
2038		  }
2039
2040		/* Check that the YZ field is right.  Subtract the size of
2041		   this LOP_END in the calculation; YZ does not include
2042		   it.  */
2043		if ((long) (y * 256 + z) * 4 != (curpos - stab_loc) - 4)
2044		  {
2045		    (*_bfd_error_handler)
2046		      (_("%s: invalid mmo file: YZ of lop_end (%ld)\
2047 not equal to the number of tetras to the preceding lop_stab (%ld)\n"),
2048		       bfd_get_filename (abfd), (long) (y * 256 + z),
2049		       (curpos - stab_loc - 4)/4);
2050		    bfd_set_error (bfd_error_bad_value);
2051		    goto error_return;
2052		  }
2053
2054		bfd_map_over_sections (abfd, mmo_map_set_sizes, NULL);
2055		goto done;
2056	      }
2057	    }
2058	}
2059      else
2060	{
2061	  /* This wasn't a lopcode, so store it in the current section.  */
2062	  mmo_xore_32 (sec, vma & ~3, bfd_get_32 (abfd, buf));
2063	  vma += 4;
2064	  vma &= ~3;
2065	  lineno++;
2066	}
2067    }
2068
2069  /* We know this file is a multiple of four bytes (checked in
2070     mmo_object_p), so if we got something other than 0, this was a bad
2071     file (although it's more likely we'll get 0 in that case too).
2072     If we got end-of-file, then there was no lop_stab, so the file has
2073     invalid format.  */
2074
2075  if (nbytes_read != 0)
2076    bfd_set_error (bfd_error_system_call);
2077  else
2078    bfd_set_error (bfd_error_bad_value);
2079
2080 error_return:
2081  error = TRUE;
2082 done:
2083  /* Mark the .text and .data section with their normal attribute if they
2084     contain anything.  This is not redundant wrt. mmo_decide_section,
2085     since that code might never execute, and conversely the alloc+code
2086     section flags must be set then.  */
2087  sec = bfd_get_section_by_name (abfd, MMO_TEXT_SECTION_NAME);
2088  if (sec != NULL
2089      && (bfd_get_section_flags (abfd, sec) & SEC_HAS_CONTENTS)
2090      && ! bfd_set_section_flags (abfd, sec,
2091				  bfd_get_section_flags (abfd, sec)
2092				  | SEC_ALLOC | SEC_LOAD | SEC_CODE))
2093    error = TRUE;
2094
2095  sec = bfd_get_section_by_name (abfd, MMO_DATA_SECTION_NAME);
2096  if (sec != NULL
2097      && (bfd_get_section_flags (abfd, sec) & SEC_HAS_CONTENTS)
2098      && ! bfd_set_section_flags (abfd, sec,
2099				  bfd_get_section_flags (abfd, sec)
2100				  | SEC_ALLOC | SEC_LOAD))
2101    error = TRUE;
2102
2103  /* Free whatever resources we took.  */
2104  for (i = 0; i < sizeof (file_names) / sizeof (file_names[0]); i++)
2105    if (file_names[i])
2106      free (file_names[i]);
2107  return ! error;
2108}
2109
2110/* A hook to set up object file dependent section information.  For mmo,
2111   we point out the shape of allocated section contents.  */
2112
2113static bfd_boolean
2114mmo_new_section_hook (abfd, newsect)
2115     bfd *abfd ATTRIBUTE_UNUSED;
2116     asection *newsect;
2117{
2118  /* We zero-fill all fields and assume NULL is represented by an all
2119     zero-bit pattern.  */
2120  newsect->used_by_bfd =
2121    (PTR) bfd_zalloc (abfd, sizeof (struct mmo_section_data_struct));
2122
2123  if (!newsect->used_by_bfd)
2124    return FALSE;
2125
2126  /* Always align to at least 32-bit words.  */
2127  newsect->alignment_power = 2;
2128  return TRUE;
2129}
2130
2131/* We already have section contents loaded for sections that have
2132   contents.  */
2133
2134static bfd_boolean
2135mmo_get_section_contents (abfd, sec, location, offset, bytes_to_do)
2136     bfd *abfd ATTRIBUTE_UNUSED;
2137     asection *sec ATTRIBUTE_UNUSED;
2138     PTR location ATTRIBUTE_UNUSED;
2139     file_ptr offset ATTRIBUTE_UNUSED;
2140     bfd_size_type bytes_to_do ATTRIBUTE_UNUSED;
2141{
2142  /* Iterate over diminishing chunk sizes, copying contents, like
2143     mmo_set_section_contents.  */
2144  while (bytes_to_do)
2145    {
2146      /* A minor song-and-dance to make sure we're not bitten by the
2147	 distant possibility of the cast from bfd_vma to int making the
2148	 chunk zero-sized.  */
2149      int chunk_size
2150	= (int) bytes_to_do != 0 ? bytes_to_do : MMO_SEC_CONTENTS_CHUNK_SIZE;
2151      bfd_byte *loc;
2152
2153      do
2154	loc = mmo_get_loc (sec, sec->vma + offset, chunk_size);
2155      while (loc == NULL && (chunk_size /= 2) != 0);
2156
2157      if (chunk_size == 0)
2158	return FALSE;
2159
2160      memcpy (location, loc, chunk_size);
2161
2162      location += chunk_size;
2163      bytes_to_do -= chunk_size;
2164      offset += chunk_size;
2165    }
2166  return TRUE;
2167}
2168
2169/* Return the amount of memory needed to read the symbol table.  */
2170
2171static long
2172mmo_get_symtab_upper_bound (abfd)
2173     bfd *abfd ATTRIBUTE_UNUSED;
2174{
2175  return (abfd->symcount + 1) * sizeof (asymbol *);
2176}
2177
2178/* Sort mmo symbols by serial number.  */
2179
2180static int
2181mmo_sort_mmo_symbols (arg1, arg2)
2182     const PTR arg1;
2183     const PTR arg2;
2184{
2185  const struct mmo_symbol *sym1 = *(const struct mmo_symbol **) arg1;
2186  const struct mmo_symbol *sym2 = *(const struct mmo_symbol **) arg2;
2187
2188  /* Sort by serial number first.  */
2189  if (sym1->serno < sym2->serno)
2190    return -1;
2191  else if (sym1->serno > sym2->serno)
2192    return 1;
2193
2194  /* Then sort by address of the table entries.  */
2195  return ((const char *) arg1 - (const char *) arg2);
2196}
2197
2198/* Translate the symbol table.  */
2199
2200static long
2201mmo_canonicalize_symtab (abfd, alocation)
2202     bfd *abfd;
2203     asymbol **alocation;
2204{
2205  unsigned int symcount = bfd_get_symcount (abfd);
2206  asymbol *csymbols;
2207  unsigned int i;
2208
2209  csymbols = abfd->tdata.mmo_data->csymbols;
2210  if (csymbols == NULL)
2211    {
2212      asymbol *c;
2213      struct mmo_symbol *s;
2214      struct mmo_symbol **msp;
2215
2216      /* First we store the symbols into the table we'll return, then we
2217	 qsort it on the serial number, with secondary on the address of
2218	 the symbol, to preserve order if there would be non-unique serial
2219	 numbers.  */
2220      for (s = abfd->tdata.mmo_data->symbols,
2221	     msp = (struct mmo_symbol **) alocation;
2222	   s != NULL;
2223	   s = s->next, ++msp)
2224	*msp = s;
2225
2226      *msp = NULL;
2227
2228      qsort (alocation, symcount, sizeof (struct mmo_symbol *),
2229	     mmo_sort_mmo_symbols);
2230
2231      csymbols = (asymbol *) bfd_alloc (abfd, symcount * sizeof (asymbol));
2232      if (csymbols == NULL && symcount != 0)
2233	return FALSE;
2234      abfd->tdata.mmo_data->csymbols = csymbols;
2235
2236      for (msp = (struct mmo_symbol **) alocation, c = csymbols;
2237	   *msp != NULL;
2238	   msp++, ++c)
2239	{
2240	  s = *msp;
2241	  c->the_bfd = abfd;
2242	  c->name = s->name;
2243	  c->value = s->value;
2244	  c->flags = BSF_GLOBAL;
2245
2246	  if (s->sym_type == mmo_data_sym)
2247	    {
2248	      c->section
2249		= bfd_get_section_by_name (abfd, MMO_DATA_SECTION_NAME);
2250
2251	      if (c->section == NULL)
2252		c->section = bfd_abs_section_ptr;
2253	      else
2254		c->value -= c->section->vma;
2255	    }
2256	  else if (s->sym_type == mmo_undef_sym)
2257	    c->section = bfd_und_section_ptr;
2258	  else if (s->sym_type == mmo_reg_sym)
2259	    {
2260	      c->section
2261		= bfd_make_section_old_way (abfd, MMIX_REG_SECTION_NAME);
2262	    }
2263	  else
2264	    {
2265	      asection *textsec
2266		= bfd_get_section_by_name (abfd, MMO_TEXT_SECTION_NAME);
2267
2268	      if (textsec != NULL
2269		  && c->value >= textsec->vma
2270		  && c->value <= textsec->vma + textsec->size)
2271		{
2272		  c->section = textsec;
2273		  c->value -= c->section->vma;
2274		}
2275	      else
2276		c->section = bfd_abs_section_ptr;
2277	    }
2278
2279	  c->udata.p = NULL;
2280	}
2281    }
2282
2283  /* Last, overwrite the incoming table with the right-type entries.  */
2284  for (i = 0; i < symcount; i++)
2285    *alocation++ = csymbols++;
2286  *alocation = NULL;
2287
2288  return symcount;
2289}
2290
2291/* Get information about a symbol.  */
2292
2293static void
2294mmo_get_symbol_info (ignore_abfd, symbol, ret)
2295     bfd *ignore_abfd ATTRIBUTE_UNUSED;
2296     asymbol *symbol;
2297     symbol_info *ret;
2298{
2299  bfd_symbol_info (symbol, ret);
2300}
2301
2302static void
2303mmo_print_symbol (abfd, afile, symbol, how)
2304     bfd *abfd;
2305     PTR afile;
2306     asymbol *symbol;
2307     bfd_print_symbol_type how;
2308{
2309  FILE *file = (FILE *) afile;
2310
2311  switch (how)
2312    {
2313    case bfd_print_symbol_name:
2314      fprintf (file, "%s", symbol->name);
2315      break;
2316    default:
2317      bfd_print_symbol_vandf (abfd, (PTR) file, symbol);
2318
2319      fprintf (file, " %-5s %s",
2320	       symbol->section->name,
2321	       symbol->name);
2322    }
2323}
2324
2325/* We can't map a file directly into executable code, so the
2326   size of header information is irrelevant.  */
2327
2328static int
2329mmo_sizeof_headers (abfd, exec)
2330     bfd *abfd ATTRIBUTE_UNUSED;
2331     bfd_boolean exec ATTRIBUTE_UNUSED;
2332{
2333  return 0;
2334}
2335
2336/* Write the (section-neutral) file preamble.  */
2337
2338static bfd_boolean
2339mmo_internal_write_header (abfd)
2340     bfd *abfd;
2341{
2342  const char lop_pre_bfd[] = { LOP, LOP_PRE, 1, 1};
2343
2344  if (bfd_bwrite (lop_pre_bfd, 4, abfd) != 4)
2345    return FALSE;
2346
2347  /* Copy creation time of original file.  */
2348  if (bfd_bwrite (abfd->tdata.mmo_data->created, 4, abfd) != 4)
2349    return FALSE;
2350
2351  return TRUE;
2352}
2353
2354/* Write the LOP_POST record, with global register initializations.
2355   Z is the Z field of the LOP_POST, corresponding to 255 - number of
2356   registers at DATA.  The Z = 255 field is filled in with the
2357   start-address.  */
2358
2359static bfd_boolean
2360mmo_internal_write_post (abfd, z, sec)
2361     bfd *abfd;
2362     int z;
2363     asection *sec;
2364{
2365  int i;
2366  bfd_byte buf[8];
2367  mmo_write_tetra_raw (abfd, (LOP << 24) | (LOP_POST << 16) | z);
2368
2369  for (i = z; i < 255; i++)
2370    {
2371      bfd_byte *data = mmo_get_loc (sec, i * 8, 8);
2372
2373      if (bfd_bwrite (data, 8, abfd) != 8)
2374	return FALSE;
2375    }
2376
2377  /* For Z == $255, we always emit the start location; supposedly Main,
2378     but we have it handy at bfd_get_start_address.  If we're called with
2379     Z == 255, don't assume DATA is valid.  */
2380  bfd_put_64 (abfd, bfd_get_start_address (abfd), buf);
2381
2382  return ! abfd->tdata.mmo_data->have_error && bfd_bwrite (buf, 8, abfd) == 8;
2383}
2384
2385/* Translate to and from BFD flags.  This is to make sure that we don't
2386   get bitten by BFD flag number changes.  */
2387
2388static flagword
2389mmo_sec_flags_from_bfd_flags (flags)
2390     flagword flags;
2391{
2392  flagword oflags = 0;
2393
2394  if (flags & SEC_ALLOC)
2395    oflags |= MMO_SEC_ALLOC;
2396  if (flags & SEC_LOAD)
2397    oflags |= MMO_SEC_LOAD;
2398  if (flags & SEC_RELOC)
2399    oflags |= MMO_SEC_RELOC;
2400  if (flags & SEC_READONLY)
2401    oflags |= MMO_SEC_READONLY;
2402  if (flags & SEC_CODE)
2403    oflags |= MMO_SEC_CODE;
2404  if (flags & SEC_DATA)
2405    oflags |= MMO_SEC_DATA;
2406  if (flags & SEC_NEVER_LOAD)
2407    oflags |= MMO_SEC_NEVER_LOAD;
2408  if (flags & SEC_IS_COMMON)
2409    oflags |= MMO_SEC_IS_COMMON;
2410  if (flags & SEC_DEBUGGING)
2411    oflags |= MMO_SEC_DEBUGGING;
2412
2413  return oflags;
2414}
2415
2416static flagword
2417bfd_sec_flags_from_mmo_flags (flags)
2418     flagword flags;
2419{
2420  flagword oflags = 0;
2421
2422  if (flags & MMO_SEC_ALLOC)
2423    oflags |= SEC_ALLOC;
2424  if (flags & MMO_SEC_LOAD)
2425    oflags |= SEC_LOAD;
2426  if (flags & MMO_SEC_RELOC)
2427    oflags |= SEC_RELOC;
2428  if (flags & MMO_SEC_READONLY)
2429    oflags |= SEC_READONLY;
2430  if (flags & MMO_SEC_CODE)
2431    oflags |= SEC_CODE;
2432  if (flags & MMO_SEC_DATA)
2433    oflags |= SEC_DATA;
2434  if (flags & MMO_SEC_NEVER_LOAD)
2435    oflags |= SEC_NEVER_LOAD;
2436  if (flags & MMO_SEC_IS_COMMON)
2437    oflags |= SEC_IS_COMMON;
2438  if (flags & MMO_SEC_DEBUGGING)
2439    oflags |= SEC_DEBUGGING;
2440
2441  return oflags;
2442}
2443
2444/* Write a section.  */
2445
2446static bfd_boolean
2447mmo_internal_write_section (abfd, sec)
2448     bfd *abfd;
2449     asection *sec;
2450{
2451  /* We do it differently depending on what section this is:
2452
2453   ".text": Output, prepended by information about the first source file
2454   (not yet implemented.)
2455
2456   ".data": Output.
2457
2458   (".MMIX.reg_contents": Not handled here.)
2459
2460   Anything else: Output inside a lop_spec 80, in the format described
2461   above.  */
2462
2463  if (strcmp (sec->name, MMO_TEXT_SECTION_NAME) == 0)
2464    /* FIXME: Output source file name and line number.  */
2465    return mmo_write_loc_chunk_list (abfd, mmo_section_data (sec)->head);
2466  else if (strcmp (sec->name, MMO_DATA_SECTION_NAME) == 0)
2467    return mmo_write_loc_chunk_list (abfd, mmo_section_data (sec)->head);
2468  else if (strcmp (sec->name, MMIX_REG_CONTENTS_SECTION_NAME) == 0)
2469    /* Not handled here.  */
2470    {
2471      /* This would normally be an abort call since this can't happen, but
2472         we don't do that.  */
2473      bfd_set_error (bfd_error_bad_value);
2474      return FALSE;
2475    }
2476  else if (strncmp (sec->name, MMIX_OTHER_SPEC_SECTION_PREFIX,
2477		    strlen (MMIX_OTHER_SPEC_SECTION_PREFIX)) == 0)
2478    {
2479      int n = atoi (sec->name + strlen (MMIX_OTHER_SPEC_SECTION_PREFIX));
2480      mmo_write_tetra_raw (abfd, (LOP << 24) | (LOP_SPEC << 16) | n);
2481      return (! abfd->tdata.mmo_data->have_error
2482	      && mmo_write_chunk_list (abfd, mmo_section_data (sec)->head));
2483    }
2484  /* Ignore sections that are just allocated or empty; we write out
2485     _contents_ here.  */
2486  else if ((bfd_get_section_flags (abfd, sec) & SEC_HAS_CONTENTS) != 0
2487	   && sec->size != 0)
2488    {
2489      /* Keep the document-comment formatted the way it is.  */
2490/*
2491INODE
2492mmo section mapping, , Symbol-table, mmo
2493SUBSECTION
2494	mmo section mapping
2495
2496	The implementation in BFD uses special data type 80 (decimal) to
2497	encapsulate and describe named sections, containing e.g.@: debug
2498	information.  If needed, any datum in the encapsulation will be
2499	quoted using lop_quote.  First comes a 32-bit word holding the
2500	number of 32-bit words containing the zero-terminated zero-padded
2501	segment name.  After the name there's a 32-bit word holding flags
2502	describing the section type.  Then comes a 64-bit big-endian word
2503	with the section length (in bytes), then another with the section
2504	start address.  Depending on the type of section, the contents
2505	might follow, zero-padded to 32-bit boundary.  For a loadable
2506	section (such as data or code), the contents might follow at some
2507	later point, not necessarily immediately, as a lop_loc with the
2508	same start address as in the section description, followed by the
2509	contents.  This in effect forms a descriptor that must be emitted
2510	before the actual contents.  Sections described this way must not
2511	overlap.
2512
2513	For areas that don't have such descriptors, synthetic sections are
2514	formed by BFD.  Consecutive contents in the two memory areas
2515	@samp{0x0000@dots{}00} to @samp{0x01ff@dots{}ff} and
2516	@samp{0x2000@dots{}00} to @samp{0x20ff@dots{}ff} are entered in
2517	sections named <<.text>> and <<.data>> respectively.  If an area
2518	is not otherwise described, but would together with a neighboring
2519	lower area be less than @samp{0x40000000} bytes long, it is joined
2520	with the lower area and the gap is zero-filled.  For other cases,
2521	a new section is formed, named <<.MMIX.sec.@var{n}>>.  Here,
2522	@var{n} is a number, a running count through the mmo file,
2523	starting at 0.
2524
2525EXAMPLE
2526	A loadable section specified as:
2527
2528| .section secname,"ax"
2529| TETRA 1,2,3,4,-1,-2009
2530| BYTE 80
2531
2532	and linked to address @samp{0x4}, is represented by the sequence:
2533
2534| 0x98080050 - lop_spec 80
2535| 0x00000002 - two 32-bit words for the section name
2536| 0x7365636e - "secn"
2537| 0x616d6500 - "ame\0"
2538| 0x00000033 - flags CODE, READONLY, LOAD, ALLOC
2539| 0x00000000 - high 32 bits of section length
2540| 0x0000001c - section length is 28 bytes; 6 * 4 + 1 + alignment to 32 bits
2541| 0x00000000 - high 32 bits of section address
2542| 0x00000004 - section address is 4
2543| 0x98010002 - 64 bits with address of following data
2544| 0x00000000 - high 32 bits of address
2545| 0x00000004 - low 32 bits: data starts at address 4
2546| 0x00000001 - 1
2547| 0x00000002 - 2
2548| 0x00000003 - 3
2549| 0x00000004 - 4
2550| 0xffffffff - -1
2551| 0xfffff827 - -2009
2552| 0x50000000 - 80 as a byte, padded with zeros.
2553
2554	Note that the lop_spec wrapping does not include the section
2555	contents.  Compare this to a non-loaded section specified as:
2556
2557| .section thirdsec
2558| TETRA 200001,100002
2559| BYTE 38,40
2560
2561	This, when linked to address @samp{0x200000000000001c}, is
2562	represented by:
2563
2564| 0x98080050 - lop_spec 80
2565| 0x00000002 - two 32-bit words for the section name
2566| 0x7365636e - "thir"
2567| 0x616d6500 - "dsec"
2568| 0x00000010 - flag READONLY
2569| 0x00000000 - high 32 bits of section length
2570| 0x0000000c - section length is 12 bytes; 2 * 4 + 2 + alignment to 32 bits
2571| 0x20000000 - high 32 bits of address
2572| 0x0000001c - low 32 bits of address 0x200000000000001c
2573| 0x00030d41 - 200001
2574| 0x000186a2 - 100002
2575| 0x26280000 - 38, 40 as bytes, padded with zeros
2576
2577	For the latter example, the section contents must not be
2578	loaded in memory, and is therefore specified as part of the
2579	special data.  The address is usually unimportant but might
2580	provide information for e.g.@: the DWARF 2 debugging format.  */
2581
2582      mmo_write_tetra_raw (abfd, LOP_SPEC_SECTION);
2583      mmo_write_tetra (abfd, (strlen (sec->name) + 3) / 4);
2584      mmo_write_chunk (abfd, sec->name, strlen (sec->name));
2585      mmo_flush_chunk (abfd);
2586      /* FIXME: We can get debug sections (.debug_line & Co.) with a
2587	 section flag still having SEC_RELOC set.  Investigate.  This
2588	 might be true for all alien sections; perhaps mmo.em should clear
2589	 that flag.  Might be related to weak references.  */
2590      mmo_write_tetra (abfd,
2591		       mmo_sec_flags_from_bfd_flags
2592		       (bfd_get_section_flags (abfd, sec)));
2593      mmo_write_octa (abfd, sec->size);
2594      mmo_write_octa (abfd, bfd_get_section_vma (abfd, sec));
2595
2596      /* Writing a LOP_LOC ends the LOP_SPEC data, and makes data actually
2597	 loaded.  */
2598      if (bfd_get_section_flags (abfd, sec) & SEC_LOAD)
2599	return (! abfd->tdata.mmo_data->have_error
2600		&& mmo_write_loc_chunk_list (abfd,
2601					     mmo_section_data (sec)->head));
2602      return (! abfd->tdata.mmo_data->have_error
2603	      && mmo_write_chunk_list (abfd, mmo_section_data (sec)->head));
2604    }
2605  return TRUE;
2606}
2607
2608/* We save up all data before output.  */
2609
2610static bfd_boolean
2611mmo_set_section_contents (abfd, sec, location, offset, bytes_to_do)
2612     bfd *abfd ATTRIBUTE_UNUSED;
2613     sec_ptr sec;
2614     const PTR location;
2615     file_ptr offset;
2616     bfd_size_type bytes_to_do;
2617{
2618  /* Iterate over diminishing chunk sizes, copying contents.  */
2619  while (bytes_to_do)
2620    {
2621      /* A minor song-and-dance to make sure we're not bitten by the
2622	 distant possibility of the cast from bfd_vma to int making the
2623	 chunk zero-sized.  */
2624      int chunk_size
2625	= (int) bytes_to_do != 0 ? bytes_to_do : MMO_SEC_CONTENTS_CHUNK_SIZE;
2626      bfd_byte *loc;
2627
2628      do
2629	loc = mmo_get_loc (sec, sec->vma + offset, chunk_size);
2630      while (loc == NULL && (chunk_size /= 2) != 0);
2631
2632      if (chunk_size == 0)
2633	return FALSE;
2634
2635      memcpy (loc, location, chunk_size);
2636
2637      location += chunk_size;
2638      bytes_to_do -= chunk_size;
2639      offset += chunk_size;
2640    }
2641  return TRUE;
2642}
2643
2644/* Add a symbol to a trie-tree.  */
2645
2646static bfd_boolean
2647mmo_internal_add_3_sym (abfd, rootp, symp)
2648     bfd *abfd;
2649     struct mmo_symbol_trie *rootp;
2650     const struct mmo_symbol *symp;
2651{
2652  const char *name = symp->name;
2653  struct mmo_symbol_trie *trie = rootp;
2654  struct mmo_symbol_trie **triep = NULL;
2655
2656  while (*name && trie != NULL)
2657    {
2658      if (*name < trie->symchar)
2659	{
2660	  triep = &trie->left;
2661	  trie = trie->left;
2662	}
2663      else if (*name > trie->symchar)
2664	{
2665	  triep = &trie->right;
2666	  trie = trie->right;
2667	}
2668      else if (*name == trie->symchar)
2669	{
2670	  triep = &trie->middle;
2671	  name++;
2672
2673	  /* Make sure "trie" points to where we should fill in the
2674	     current symbol whenever we've iterated through "name".  We
2675	     would lose the right position if we encounter "foobar" then
2676	     "foo".  */
2677	  if (*name)
2678	    trie = trie->middle;
2679	}
2680    }
2681
2682  while (*name != 0)
2683    {
2684      /* Create middle branches for the rest of the characters.  */
2685      trie = bfd_zalloc (abfd, sizeof (struct mmo_symbol_trie));
2686      *triep = trie;
2687      trie->symchar = *name++;
2688      triep = &trie->middle;
2689    }
2690
2691  /* We discover a duplicate symbol rather late in the process, but still;
2692     we discover it and bail out.  */
2693  if (trie->sym.name != NULL)
2694    {
2695      (*_bfd_error_handler)
2696	(_("%s: invalid symbol table: duplicate symbol `%s'\n"),
2697	 bfd_get_filename (abfd), trie->sym.name);
2698      bfd_set_error (bfd_error_bad_value);
2699      return FALSE;
2700    }
2701
2702  memcpy (&trie->sym, symp, sizeof *symp);
2703  return TRUE;
2704}
2705
2706/* Find out the length of the serialized version of a trie in bytes.  */
2707
2708static unsigned int
2709mmo_internal_3_length (abfd, trie)
2710     bfd *abfd;
2711     struct mmo_symbol_trie *trie;
2712{
2713  /* First, one for the control byte.  */
2714  unsigned int length = 1;
2715
2716  if (trie == NULL)
2717    return 0;
2718
2719  /* Add in the recursion to the left.  */
2720  length += mmo_internal_3_length (abfd, trie->left);
2721
2722  /* Add in the middle trie and the character.  */
2723  length += 1 + mmo_internal_3_length (abfd, trie->middle);
2724
2725  /* Add in the recursion to the right.  */
2726  length += mmo_internal_3_length (abfd, trie->right);
2727
2728  /* Add in bytes for the symbol (if this is an endnode). */
2729  if (trie->sym.name != NULL)
2730    {
2731      unsigned int serno = trie->sym.serno;
2732
2733      /* First what it takes to encode the value. */
2734      if (trie->sym.sym_type == mmo_reg_sym)
2735	length++;
2736      else if (trie->sym.sym_type == mmo_undef_sym)
2737	length += 2;
2738      else
2739	{
2740	  bfd_vma value = trie->sym.value;
2741
2742	  /* Coded in one to eight following bytes.  */
2743	  if (trie->sym.sym_type == mmo_data_sym)
2744	    value -= (bfd_vma) 0x20 << 56;
2745
2746	  do
2747	    {
2748	      value >>= 8;
2749	      length++;
2750	    }
2751	  while (value != 0);
2752	}
2753
2754      /* Find out what it takes to encode the serial number.  */
2755      do
2756	{
2757	  serno >>= 7;
2758	  length++;
2759	}
2760      while (serno != 0);
2761    }
2762
2763  return length;
2764}
2765
2766/* Helper function for outputting the serial number of a symbol, output as
2767   a variant of leb128 (see dwarf2 documentation) which could be called
2768   beb128.  Using a helper function and recursion simplifies debugging.  */
2769
2770static void
2771mmo_beb128_out (abfd, serno, marker)
2772     bfd *abfd;
2773     int serno;
2774     int marker;
2775{
2776  if (serno & ~0x7f)
2777    mmo_beb128_out (abfd, serno >> 7, 0);
2778  mmo_write_byte (abfd, marker | (serno & 0x7f));
2779}
2780
2781/* Serialize a trie.  */
2782
2783static void
2784mmo_internal_3_dump (abfd, trie)
2785     bfd *abfd;
2786     struct mmo_symbol_trie *trie;
2787{
2788  bfd_byte control = 0;
2789
2790  if (trie == NULL)
2791    return;
2792
2793  if (trie->left)
2794    control |= MMO3_LEFT;
2795
2796  if (trie->middle)
2797    control |= MMO3_MIDDLE;
2798
2799  if (trie->right)
2800    control |= MMO3_RIGHT;
2801
2802  if (trie->sym.name != NULL)
2803    {
2804      /* Encode the symbol type and length of value bytes.  */
2805      if (trie->sym.sym_type == mmo_reg_sym)
2806	control |= MMO3_REGQUAL_BITS;
2807      else if (trie->sym.sym_type == mmo_undef_sym)
2808	control |= MMO3_UNDEF;
2809      else
2810	{
2811	  bfd_vma value = trie->sym.value;
2812
2813	  /* Coded in 1..8 following bytes.  */
2814	  if (trie->sym.sym_type == mmo_data_sym)
2815	    {
2816	      control |= MMO3_DATA;
2817	      value -= (bfd_vma) 0x20 << 56;
2818	    }
2819
2820	  do
2821	    {
2822	      value >>= 8;
2823	      control++;
2824	    }
2825	  while (value != 0);
2826	}
2827    }
2828
2829  /* The control byte is output before recursing.  */
2830  mmo_write_byte (abfd, control);
2831
2832  mmo_internal_3_dump (abfd, trie->left);
2833
2834  if (control & MMO3_SYMBITS)
2835    {
2836      mmo_write_byte (abfd, trie->symchar);
2837
2838      if (trie->sym.name != NULL)
2839	{
2840	  if (trie->sym.sym_type == mmo_reg_sym)
2841	    mmo_write_byte (abfd, trie->sym.value);
2842	  else if (trie->sym.sym_type == mmo_undef_sym)
2843	    {
2844	      mmo_write_byte (abfd, 0);
2845	      mmo_write_byte (abfd, 0);
2846	    }
2847	  else
2848	    {
2849	      bfd_vma value = trie->sym.value;
2850
2851	      bfd_byte byte_n = control & 15;
2852
2853	      /* Coded in 1..8 following bytes.  Note that the value is
2854		 shifted out big-endian.  */
2855	      if (trie->sym.sym_type == mmo_data_sym)
2856		{
2857		  value -= (bfd_vma) 0x20 << 56;
2858		  byte_n -= 8;
2859		}
2860
2861	      do
2862		{
2863		  mmo_write_byte (abfd, (value >> ((byte_n - 1) * 8)) & 0xff);
2864		  byte_n--;
2865		}
2866	      while (byte_n != 0);
2867	    }
2868
2869	  mmo_beb128_out (abfd, trie->sym.serno, 128);
2870	}
2871      mmo_internal_3_dump (abfd, trie->middle);
2872    }
2873  mmo_internal_3_dump (abfd, trie->right);
2874}
2875
2876/* Write symbols in mmo format.  Also write the lop_end terminator.  */
2877
2878static bfd_boolean
2879mmo_write_symbols_and_terminator (abfd)
2880     bfd *abfd;
2881{
2882  int count = bfd_get_symcount (abfd);
2883  asymbol *maintable[2];
2884  asymbol **table;
2885  asymbol **orig_table = bfd_get_outsymbols (abfd);
2886  int serno;
2887  struct mmo_symbol_trie root;
2888  int trie_len;
2889  int i;
2890  bfd_byte buf[4];
2891
2892  /* Create a symbol for "Main".  */
2893  asymbol *fakemain = bfd_make_empty_symbol (abfd);
2894
2895  fakemain->flags = BSF_GLOBAL;
2896  fakemain->value = bfd_get_start_address (abfd);
2897  fakemain->name = MMIX_START_SYMBOL_NAME;
2898  fakemain->section = bfd_abs_section_ptr;
2899  maintable[0] = fakemain;
2900  maintable[1] = NULL;
2901
2902  memset (&root, 0, sizeof (root));
2903
2904  /* Make all symbols take a left turn.  */
2905  root.symchar = 0xff;
2906
2907  /* There must always be a ":Main", so we'll add one if there are no
2908     symbols.  Make sure we have room for it.  */
2909  table = bfd_alloc (abfd, (count + 1) * sizeof (asymbol *));
2910  if (table == NULL)
2911    return FALSE;
2912
2913  memcpy (table, orig_table, count * sizeof (asymbol *));
2914
2915  /* Move :Main (if there is one) to the first position.  This is
2916     necessary to get the same layout of the trie-tree when linking as
2917     when objcopying the result as in the objcopy.exp test "simple objcopy
2918     of executable".  It also automatically takes care of assigning serial
2919     number 1 to :Main (as is mandatory).  */
2920  for (i = 0; i < count; i++)
2921    if (table[i] != NULL
2922	&& strcmp (table[i]->name, MMIX_START_SYMBOL_NAME) == 0
2923	&& (table[i]->flags & (BSF_DEBUGGING|BSF_GLOBAL)) == BSF_GLOBAL)
2924      {
2925	asymbol *mainsym = table[i];
2926	memcpy (table + 1, orig_table, i * sizeof (asymbol *));
2927	table[0] = mainsym;
2928
2929	/* Check that the value assigned to :Main is the same as the entry
2930	   address.  The default linker script asserts this.  This is as
2931	   good a place as any to check this consistency. */
2932	if ((mainsym->value
2933	     + mainsym->section->output_section->vma
2934	     + mainsym->section->output_offset)
2935	    != bfd_get_start_address (abfd))
2936	  {
2937	    /* Arbitrary buffer to hold the printable representation of a
2938	       vma.  */
2939	    char vmas_main[40];
2940	    char vmas_start[40];
2941	    bfd_vma vma_start = bfd_get_start_address (abfd);
2942
2943	    sprintf_vma (vmas_main, mainsym->value);
2944	    sprintf_vma (vmas_start, vma_start);
2945
2946	    (*_bfd_error_handler)
2947	      (_("%s: Bad symbol definition: `Main' set to %s rather\
2948 than the start address %s\n"),
2949	       bfd_get_filename (abfd), vmas_main, vmas_start);
2950	    bfd_set_error (bfd_error_bad_value);
2951	    return FALSE;
2952	  }
2953	break;
2954      }
2955  if (i == count && count != 0)
2956    {
2957      /* When there are symbols, there must be a :Main.  There was no
2958	 :Main, so we need to add it manually.  */
2959      memcpy (table + 1, orig_table, count * sizeof (asymbol *));
2960      table[0] = fakemain;
2961      count++;
2962    }
2963
2964  for (i = 0, serno = 1; i < count && table[i] != NULL; i++)
2965    {
2966      asymbol *s = table[i];
2967
2968      /* It's not enough to consult bfd_is_local_label, since it does not
2969	 mean "local" in the sense of linkable-and-observable-after-link.
2970	 Let's just check the BSF_GLOBAL flag.
2971
2972	 Also, don't export symbols with characters not in the allowed set.  */
2973      if ((s->flags & (BSF_DEBUGGING|BSF_GLOBAL)) == BSF_GLOBAL
2974	  && strspn (s->name,
2975		     valid_mmo_symbol_character_set) == strlen (s->name))
2976	{
2977	  struct mmo_symbol sym;
2978	  memset (&sym, 0, sizeof (sym));
2979
2980	  sym.name = s->name;
2981	  sym.value =
2982	    s->value
2983	    + s->section->output_section->vma
2984	    + s->section->output_offset;
2985
2986	  if (bfd_is_und_section (s->section))
2987	    sym.sym_type = mmo_undef_sym;
2988	  else if (strcmp (s->section->name, MMO_DATA_SECTION_NAME) == 0
2989		   /* The encoding of data symbols require that the "rest"
2990		      of the value fits in 6 bytes, so the upper two bytes
2991		      must be 0x2000.  All other symbols get to be the
2992		      absolute type.  */
2993		   && (sym.value >> 48) == 0x2000)
2994	    sym.sym_type = mmo_data_sym;
2995	  else if (strcmp (s->section->name, MMIX_REG_SECTION_NAME) == 0)
2996	    sym.sym_type = mmo_reg_sym;
2997	  else if (strcmp (s->section->name,
2998			   MMIX_REG_CONTENTS_SECTION_NAME) == 0)
2999	    {
3000	      sym.sym_type = mmo_reg_sym;
3001	      sym.value /= 8;
3002	    }
3003	  else
3004	    sym.sym_type = mmo_abs_sym;
3005
3006	  /* FIXME: We assume the order of the received symbols is an
3007	     ordered mapping of the serial numbers.  This is not
3008	     necessarily true if we e.g. objcopy a mmo file to another and
3009	     there are gaps in the numbering.  Not sure if this can
3010	     happen.  Not sure what to do.  */
3011	  sym.serno = serno++;
3012
3013	  if (! mmo_internal_add_3_sym (abfd, &root, &sym))
3014	    return FALSE;
3015	}
3016    }
3017
3018  /* Change the root node to be a ":"-prefix.  */
3019  root.symchar = ':';
3020  root.middle = root.left;
3021  root.right = NULL;
3022  root.left = NULL;
3023
3024  /* We have to find out if we can fit the whole symbol table in the mmo
3025     symtab.  It would be bad to assume we can always fit it in 262144
3026     bytes.  If we can't, just leave the Main symbol.  */
3027  trie_len = (mmo_internal_3_length (abfd, &root) + 3)/4;
3028
3029  if (trie_len > 0xffff)
3030    {
3031      /* Test this code by using a lower limit in the test above and check
3032	 that the single "Main" symbol is emitted and handled properly.
3033	 There's no specific test-case.  */
3034      struct mmo_symbol sym;
3035
3036      (*_bfd_error_handler)
3037	(_("%s: warning: symbol table too large for mmo, larger than 65535\
3038 32-bit words: %d.  Only `Main' will be emitted.\n"),
3039	 bfd_get_filename (abfd), trie_len);
3040
3041      memset (&sym, 0, sizeof (sym));
3042      sym.sym_type = mmo_abs_sym;
3043      sym.name = MMIX_START_SYMBOL_NAME;
3044      sym.serno = 1;
3045      sym.value = bfd_get_start_address (abfd);
3046
3047      /* Then patch up a symbol table to be just the ":Main" symbol.  */
3048      memset (&root, 0, sizeof (root));
3049      root.left = root.middle;
3050      root.symchar = 0xff;
3051      root.middle = NULL;
3052      root.right = NULL;
3053
3054      if (! mmo_internal_add_3_sym (abfd, &root, &sym))
3055	return FALSE;
3056
3057      root.symchar = ':';
3058      root.middle = root.left;
3059      root.right = NULL;
3060      root.left = NULL;
3061
3062      trie_len = (mmo_internal_3_length (abfd, &root) + 3)/4;
3063    }
3064
3065  /* Reset the written-bytes counter.  */
3066  abfd->tdata.mmo_data->byte_no = 0;
3067
3068  /* Put out the lop_stab mark.  */
3069  bfd_put_32 (abfd, (LOP << 24) | (LOP_STAB << 16), buf);
3070  if (bfd_bwrite (buf, 4, abfd) != 4)
3071    return FALSE;
3072
3073  /* Dump out symbols.  */
3074  mmo_internal_3_dump (abfd, &root);
3075
3076  if (trie_len != (abfd->tdata.mmo_data->byte_no + 3)/4)
3077    {
3078      /* I haven't seen this trig.  It seems no use claiming this case
3079	 isn't debugged and abort if we get here.  Instead emit a
3080	 diagnostic and fail "normally".  */
3081      (*_bfd_error_handler)
3082	(_("%s: internal error, symbol table changed size from %d to %d\
3083 words\n"),
3084	 bfd_get_filename (abfd), trie_len,
3085	 (abfd->tdata.mmo_data->byte_no + 3)/4);
3086      bfd_set_error (bfd_error_bad_value);
3087      return FALSE;
3088    }
3089
3090  /* Dump out remaining bytes in the buffer and handle I/O errors by
3091     propagating errors.  */
3092  if ((abfd->tdata.mmo_data->byte_no % 4) != 0
3093      || abfd->tdata.mmo_data->have_error)
3094    {
3095      memset (abfd->tdata.mmo_data->buf + (abfd->tdata.mmo_data->byte_no % 4),
3096	      0, 4 - (abfd->tdata.mmo_data->byte_no % 4));
3097
3098      if (abfd->tdata.mmo_data->have_error
3099	  || bfd_bwrite (abfd->tdata.mmo_data->buf, 4, abfd) != 4)
3100	return FALSE;
3101    }
3102
3103  bfd_put_32 (abfd, (LOP << 24) | (LOP_END << 16) | trie_len, buf);
3104  return bfd_bwrite (buf, 4, abfd) == 4;
3105}
3106
3107/* Write section unless it is the register contents section.  For that, we
3108   instead store the section in the supplied pointer.  This function is
3109   used through bfd_map_over_sections.  */
3110
3111static void
3112mmo_write_section_unless_reg_contents (abfd, sec, p)
3113     bfd *abfd;
3114     asection *sec;
3115     PTR p;
3116{
3117  struct mmo_write_sec_info *infop = (struct mmo_write_sec_info *) p;
3118
3119  if (! infop->retval)
3120    return;
3121
3122  if (strcmp (sec->name, MMIX_REG_CONTENTS_SECTION_NAME) == 0)
3123    {
3124      infop->reg_section = sec;
3125      return;
3126    }
3127
3128  /* Exclude the convenience register section.  */
3129  if (strcmp (sec->name, MMIX_REG_SECTION_NAME) == 0)
3130    {
3131      if (bfd_get_section_flags (abfd, sec) & SEC_HAS_CONTENTS)
3132	{
3133	  /* Make sure it hasn't got contents.  It seems impossible to
3134	     make it carry contents, so we don't have a test-case for
3135	     this.  */
3136	  (*_bfd_error_handler)
3137	    (_("%s: internal error, internal register section %s had\
3138 contents\n"),
3139	     bfd_get_filename (abfd), sec->name);
3140	  bfd_set_error (bfd_error_bad_value);
3141	  infop->retval = FALSE;
3142	  return;
3143	}
3144
3145      return;
3146    }
3147
3148  infop->retval = mmo_internal_write_section (abfd, sec);
3149}
3150
3151/* Do the actual output of a file.  Assumes mmo_set_section_contents is
3152   already called. */
3153
3154static bfd_boolean
3155mmo_write_object_contents (abfd)
3156     bfd *abfd;
3157{
3158  struct mmo_write_sec_info wsecinfo;
3159
3160  /* First, there are a few words of preamble.  */
3161  if (! mmo_internal_write_header (abfd))
3162    return FALSE;
3163
3164  wsecinfo.reg_section = NULL;
3165  wsecinfo.retval = TRUE;
3166
3167  bfd_map_over_sections (abfd, mmo_write_section_unless_reg_contents,
3168			 (PTR) &wsecinfo);
3169
3170  if (! wsecinfo.retval)
3171    return FALSE;
3172
3173  if (wsecinfo.reg_section != NULL)
3174    {
3175      asection *sec = wsecinfo.reg_section;
3176      unsigned int z = (unsigned int) (sec->vma / 8);
3177
3178      /* Registers 0..31 must not be global.  Do sanity check on the "vma"
3179	 of the register contents section and check that it corresponds to
3180	 the length of the section.  */
3181      if (z < 32 || z >= 255 || (sec->vma & 7) != 0
3182	  || sec->vma != 256 * 8 - sec->size - 8)
3183	{
3184	  bfd_set_error (bfd_error_bad_value);
3185
3186	  if (sec->size == 0)
3187	    /* There must always be at least one such register.  */
3188	    (*_bfd_error_handler)
3189	      (_("%s: no initialized registers; section length 0\n"),
3190	       bfd_get_filename (abfd));
3191	  else if (sec->vma > (256 - 32) * 8)
3192	    /* Provide better error message for the case of too many
3193	       global registers.  */
3194	    (*_bfd_error_handler)
3195	      (_("%s: too many initialized registers; section length %ld\n"),
3196	       bfd_get_filename (abfd),
3197	       (long) sec->size);
3198	  else
3199	    (*_bfd_error_handler)
3200	      (_("%s: invalid start address for initialized registers of\
3201 length %ld: 0x%lx%08lx\n"),
3202	       bfd_get_filename (abfd),
3203	       (long) sec->size,
3204	       (unsigned long) (sec->vma >> 32), (unsigned long) (sec->vma));
3205
3206	  return FALSE;
3207	}
3208
3209      if (! mmo_internal_write_post (abfd, z, sec))
3210	return FALSE;
3211    }
3212  else
3213    if (! mmo_internal_write_post (abfd, 255, NULL))
3214      return FALSE;
3215
3216  return mmo_write_symbols_and_terminator (abfd);
3217}
3218
3219/* Return the size of a NULL pointer, so we support linking in an mmo
3220   object.  */
3221
3222static long
3223mmo_get_reloc_upper_bound (abfd, sec)
3224     bfd *abfd ATTRIBUTE_UNUSED;
3225     asection *sec ATTRIBUTE_UNUSED;
3226{
3227  return sizeof (PTR);
3228}
3229
3230/* Similarly canonicalize relocs to empty, filling in the terminating NULL
3231   pointer.  */
3232
3233long
3234mmo_canonicalize_reloc (abfd, section, relptr, symbols)
3235     bfd *abfd ATTRIBUTE_UNUSED;
3236     sec_ptr section ATTRIBUTE_UNUSED;
3237     arelent **relptr;
3238     asymbol **symbols ATTRIBUTE_UNUSED;
3239{
3240  *relptr = NULL;
3241  return 0;
3242}
3243
3244/* If there's anything in particular in a mmo bfd that we want to free,
3245   make this a real function.  Only do this if you see major memory
3246   thrashing; zealous free:ing will cause unwanted behavior, especially if
3247   you "free" memory allocated with "bfd_alloc", or even "bfd_release" a
3248   block allocated with "bfd_alloc"; they're really allocated from an
3249   obstack, and we don't know what was allocated there since this
3250   particular allocation.  */
3251
3252#define	mmo_close_and_cleanup _bfd_generic_close_and_cleanup
3253#define mmo_bfd_free_cached_info _bfd_generic_bfd_free_cached_info
3254
3255/* Perhaps we need to adjust this one; mmo labels (originally) without a
3256   leading ':' might more appropriately be called local.  */
3257#define mmo_bfd_is_local_label_name bfd_generic_is_local_label_name
3258#define mmo_bfd_is_target_special_symbol  \
3259  ((bfd_boolean (*) (bfd *, asymbol *)) bfd_false)
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#define mmo_section_already_linked \
3292  _bfd_generic_section_already_linked
3293
3294/* objcopy will be upset if we return -1 from bfd_get_reloc_upper_bound by
3295   using BFD_JUMP_TABLE_RELOCS (_bfd_norelocs) rather than 0.  FIXME: Most
3296   likely a bug in the _bfd_norelocs definition.
3297
3298   On the other hand, we smuggle in an mmo object (because setting up ELF
3299   is too cumbersome) when linking (from other formats, presumably ELF) to
3300   represent the g255 entry.  We need to link that object, so need to say
3301   it has no relocs.  Upper bound for the size of the relocation table is
3302   the size of a NULL pointer, and we support "canonicalization" for that
3303   pointer.  */
3304#define mmo_bfd_reloc_type_lookup _bfd_norelocs_bfd_reloc_type_lookup
3305
3306/* We want to copy time of creation, otherwise we'd use
3307   BFD_JUMP_TABLE_COPY (_bfd_generic).  */
3308#define mmo_bfd_merge_private_bfd_data _bfd_generic_bfd_merge_private_bfd_data
3309#define mmo_bfd_copy_private_section_data _bfd_generic_bfd_copy_private_section_data
3310#define mmo_bfd_copy_private_symbol_data _bfd_generic_bfd_copy_private_symbol_data
3311#define mmo_bfd_copy_private_header_data _bfd_generic_bfd_copy_private_header_data
3312#define mmo_bfd_set_private_flags _bfd_generic_bfd_set_private_flags
3313#define mmo_bfd_print_private_bfd_data _bfd_generic_bfd_print_private_bfd_data
3314
3315const bfd_target bfd_mmo_vec =
3316{
3317  "mmo",			/* name */
3318  bfd_target_mmo_flavour,
3319  BFD_ENDIAN_BIG,		/* target byte order */
3320  BFD_ENDIAN_BIG,		/* target headers byte order */
3321
3322  /* FIXME: Might need adjustments.  */
3323  (HAS_RELOC | EXEC_P |		/* object flags */
3324   HAS_LINENO | HAS_DEBUG |
3325   HAS_SYMS | HAS_LOCALS | WP_TEXT),
3326
3327  /* FIXME: Might need adjustments.  */
3328  (SEC_CODE | SEC_DATA | SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD
3329   | SEC_READONLY | SEC_EXCLUDE | SEC_DEBUGGING | SEC_IN_MEMORY),
3330				/* section flags */
3331  0,				/* leading underscore */
3332  ' ',				/* ar_pad_char */
3333  16,				/* ar_max_namelen */
3334  bfd_getb64, bfd_getb_signed_64, bfd_putb64,
3335  bfd_getb32, bfd_getb_signed_32, bfd_putb32,
3336  bfd_getb16, bfd_getb_signed_16, bfd_putb16,	/* data */
3337  bfd_getb64, bfd_getb_signed_64, bfd_putb64,
3338  bfd_getb32, bfd_getb_signed_32, bfd_putb32,
3339  bfd_getb16, bfd_getb_signed_16, bfd_putb16,	/* hdrs */
3340
3341  {
3342    _bfd_dummy_target,
3343    mmo_object_p,		/* bfd_check_format */
3344    _bfd_dummy_target,
3345    _bfd_dummy_target,
3346  },
3347  {
3348    bfd_false,
3349    mmo_mkobject,
3350    bfd_false,
3351    bfd_false,
3352  },
3353  {				/* bfd_write_contents */
3354    bfd_false,
3355    mmo_write_object_contents,
3356    bfd_false,
3357    bfd_false,
3358  },
3359
3360  BFD_JUMP_TABLE_GENERIC (mmo),
3361  BFD_JUMP_TABLE_COPY (mmo),
3362  BFD_JUMP_TABLE_CORE (_bfd_nocore),
3363  BFD_JUMP_TABLE_ARCHIVE (_bfd_noarchive),
3364  BFD_JUMP_TABLE_SYMBOLS (mmo),
3365  /* We have to provide a valid method for getting relocs, returning zero,
3366     so we can't say BFD_JUMP_TABLE_RELOCS (_bfd_norelocs).  */
3367  BFD_JUMP_TABLE_RELOCS (mmo),
3368  BFD_JUMP_TABLE_WRITE (mmo),
3369  BFD_JUMP_TABLE_LINK (mmo),
3370  BFD_JUMP_TABLE_DYNAMIC (_bfd_nodynamic),
3371
3372  NULL,
3373
3374  NULL
3375};
3376