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