1#include <stdlib.h>
2#include <string.h>
3#include <ctype.h>
4#include <sys/file.h>
5#include <libc.h>
6#include <mach/mach.h>
7#include "arch64_32.h"
8#include "stuff/openstep_mach.h"
9#include <mach-o/loader.h>
10#include <mach-o/reloc.h>
11#include <mach-o/stab.h>
12#ifdef I860
13#include <mach-o/i860/reloc.h>
14#endif
15#ifdef M88K
16#include <mach-o/m88k/reloc.h>
17#endif
18#ifdef PPC
19#include <mach-o/ppc/reloc.h>
20#endif
21#ifdef HPPA
22#include <mach-o/hppa/reloc.h>
23#include "stuff/hppa.h"
24#endif
25#ifdef SPARC
26#include <mach-o/sparc/reloc.h>
27#endif
28#ifdef ARM
29#include <mach-o/arm/reloc.h>
30#include "arm_reloc.h"
31#endif
32#if defined(I386) && defined(ARCH64)
33#include <mach-o/x86_64/reloc.h>
34#endif
35#include "stuff/rnd.h"
36#include "stuff/bytesex.h"
37#include "stuff/errors.h"
38#include "as.h"
39#include "struc-symbol.h"
40#include "symbols.h"
41#include "frags.h"
42#include "fixes.h"
43#include "md.h"
44#include "sections.h"
45#include "messages.h"
46#include "xmalloc.h"
47#include "input-scrub.h"
48#if defined(I386) && defined(ARCH64)
49#include "i386.h"
50#endif
51#ifdef I860
52#define RELOC_SECTDIFF		I860_RELOC_SECTDIFF
53#define RELOC_LOCAL_SECTDIFF	I860_RELOC_SECTDIFF
54#define RELOC_PAIR		I860_RELOC_PAIR
55#endif
56#ifdef M88K
57#define RELOC_SECTDIFF		M88K_RELOC_SECTDIFF
58#define RELOC_LOCAL_SECTDIFF	M88K_RELOC_SECTDIFF
59#define RELOC_PAIR		M88K_RELOC_PAIR
60#endif
61#ifdef PPC
62#define RELOC_SECTDIFF		PPC_RELOC_SECTDIFF
63#define RELOC_LOCAL_SECTDIFF	PPC_RELOC_LOCAL_SECTDIFF
64#define RELOC_PAIR		PPC_RELOC_PAIR
65#define PPC_RELOC_BR14_predicted (0x10 | PPC_RELOC_BR14)
66#endif
67#ifdef HPPA
68#define RELOC_SECTDIFF		HPPA_RELOC_SECTDIFF
69#define RELOC_LOCAL_SECTDIFF	HPPA_RELOC_SECTDIFF
70#define RELOC_PAIR		HPPA_RELOC_PAIR
71#endif
72#ifdef SPARC
73#define RELOC_SECTDIFF		SPARC_RELOC_SECTDIFF
74#define RELOC_LOCAL_SECTDIFF	SPARC_RELOC_SECTDIFF
75#define RELOC_PAIR		SPARC_RELOC_PAIR
76#endif
77#if defined(M68K) || defined(I386)
78#define RELOC_SECTDIFF		GENERIC_RELOC_SECTDIFF
79#define RELOC_LOCAL_SECTDIFF	GENERIC_RELOC_LOCAL_SECTDIFF
80#define RELOC_PAIR		GENERIC_RELOC_PAIR
81#endif
82#ifdef ARM
83#define RELOC_SECTDIFF		ARM_RELOC_SECTDIFF
84#define RELOC_LOCAL_SECTDIFF	ARM_RELOC_SECTDIFF
85#define RELOC_PAIR		ARM_RELOC_PAIR
86#endif
87
88/*
89 * These variables are set by layout_symbols() to organize the symbol table and
90 * string table in order the dynamic linker expects.  They are then used in
91 * write_object() to put out the symbols and strings in that order.
92 * The order of the symbol table is:
93 *	local symbols
94 *	defined external symbols (sorted by name)
95 *	undefined external symbols (sorted by name)
96 * The order of the string table is:
97 *	strings for external symbols
98 *	strings for local symbols
99 */
100/* index to and number of local symbols */
101static uint32_t ilocalsym = 0;
102static uint32_t nlocalsym = 0;
103/* index to, number of and array of sorted externally defined symbols */
104static uint32_t iextdefsym = 0;
105static uint32_t nextdefsym = 0;
106static symbolS **extdefsyms = NULL;
107/* index to, number of and array of sorted undefined symbols */
108static uint32_t iundefsym = 0;
109static uint32_t nundefsym = 0;
110static symbolS **undefsyms = NULL;
111
112static uint32_t layout_indirect_symbols(
113     void);
114static void layout_symbols(
115    int32_t *symbol_number,
116    int32_t *string_byte_count);
117static int qsort_compare(
118    const symbolS **sym1,
119    const symbolS **sym2);
120static uint32_t nrelocs_for_fix(
121    struct fix *fixP);
122static uint32_t fix_to_relocation_entries(
123    struct fix *fixP,
124    uint64_t sect_addr,
125    struct relocation_info *riP,
126    uint32_t debug_section);
127#ifdef I860
128static void
129    I860_tweeks(void);
130#endif
131
132/*
133 * write_object() writes a Mach-O object file from the built up data structures.
134 */
135void
136write_object(
137char *out_file_name)
138{
139    /* The structures for Mach-O relocatables */
140    mach_header_t		header;
141    segment_command_t		reloc_segment;
142    struct symtab_command	symbol_table;
143    struct dysymtab_command	dynamic_symbol_table;
144    uint32_t			section_type;
145    uint32_t			*indirect_symbols;
146    isymbolS			*isymbolP;
147    uint32_t			i, j, nsects, nsyms, strsize, nindirectsyms;
148
149    /* locals to fill in section struct fields */
150    uint32_t offset, zero;
151
152    /* The GAS data structures */
153    struct frchain *frchainP, *p;
154    struct symbol *symbolP;
155    struct frag *fragP;
156    struct fix *fixP;
157
158    uint32_t output_size;
159    char *output_addr;
160    kern_return_t r;
161
162    enum byte_sex host_byte_sex;
163    uint32_t reloff, nrelocs;
164    int32_t count;
165    char *fill_literal;
166    int32_t fill_size;
167    int32_t num_bytes;
168    char *symbol_name;
169    int fd;
170    uint32_t local;
171    struct stat stat_buf;
172
173#ifdef I860
174	I860_tweeks();
175#endif
176	i = 0; /* to shut up a compiler "may be used uninitialized" warning */
177
178	/*
179	 * The first group of things to do is to set all the fields in the
180	 * header structures which includes offsets and determining the final
181	 * sizes of things.
182	 */
183
184	/*
185	 * Fill in the addr and size fields of each section structure and count
186	 * the number of sections.
187	 */
188	nsects = 0;
189	for(frchainP = frchain_root; frchainP; frchainP = frchainP->frch_next){
190	    frchainP->frch_section.addr = frchainP->frch_root->fr_address;
191	    frchainP->frch_section.size = frchainP->frch_last->fr_address -
192		   			  frchainP->frch_root->fr_address;
193	    nsects++;
194	}
195
196	/*
197	 * Setup the indirect symbol tables by looking up or creating symbol
198	 * from the indirect symbol names and recording the symbol pointers.
199	 */
200	nindirectsyms = layout_indirect_symbols();
201
202	/*
203	 * Setup the symbol table to include only those symbols that will be in
204	 * the object file, assign the string table offsets into the symbols
205	 * and size the string table.
206	 */
207	nsyms = 0;
208	strsize = 0;
209	layout_symbols((int32_t *)&nsyms, (int32_t *)&strsize);
210
211	/* fill in the Mach-O header */
212	header.magic = MH_MAGIC_VALUE;
213	header.cputype = md_cputype;
214	if(archflag_cpusubtype != -1)
215	    header.cpusubtype = archflag_cpusubtype;
216	else
217	    header.cpusubtype = md_cpusubtype;
218
219	header.filetype = MH_OBJECT;
220	header.ncmds = 0;
221	header.sizeofcmds = 0;
222	if(nsects != 0){
223	    header.ncmds += 1;
224	    header.sizeofcmds += sizeof(segment_command_t) +
225				 nsects * sizeof(section_t);
226	}
227	if(nsyms != 0){
228	    header.ncmds += 1;
229	    header.sizeofcmds += sizeof(struct symtab_command);
230	    if(flagseen['k']){
231		header.ncmds += 1;
232		header.sizeofcmds += sizeof(struct dysymtab_command);
233	    }
234	}
235	else
236	    strsize = 0;
237	header.flags = 0;
238	if(subsections_via_symbols == TRUE)
239	    header.flags |= MH_SUBSECTIONS_VIA_SYMBOLS;
240#ifdef ARCH64
241	header.reserved = 0;
242#endif
243
244	/* fill in the segment command */
245	memset(&reloc_segment, '\0', sizeof(segment_command_t));
246	reloc_segment.cmd = LC_SEGMENT_VALUE;
247	reloc_segment.cmdsize = sizeof(segment_command_t) +
248				nsects * sizeof(section_t);
249	/* leave reloc_segment.segname full of zeros */
250	reloc_segment.vmaddr = 0;
251	reloc_segment.vmsize = 0;
252	reloc_segment.filesize = 0;
253	offset = header.sizeofcmds + sizeof(mach_header_t);
254	reloc_segment.fileoff = offset;
255	reloc_segment.maxprot = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
256	reloc_segment.initprot= VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
257	reloc_segment.nsects = nsects;
258	reloc_segment.flags = 0;
259	/*
260	 * Set the offsets to the contents of the sections (for non-zerofill
261	 * sections) and set the filesize and vmsize of the segment.  This is
262	 * complicated by the fact that all the zerofill sections have addresses
263	 * after the non-zerofill sections and that the alignment of sections
264	 * produces gaps that are not in any section.  For the vmsize we rely on
265	 * the fact the the sections start at address 0 so it is just the last
266	 * zerofill section or the last not-zerofill section.
267	 */
268	for(frchainP = frchain_root; frchainP; frchainP = frchainP->frch_next){
269	    section_type = frchainP->frch_section.flags & SECTION_TYPE;
270	    if(section_type == S_ZEROFILL ||
271	       section_type == S_THREAD_LOCAL_ZEROFILL)
272		continue;
273	    for(p = frchainP->frch_next; p != NULL; p = p->frch_next){
274		section_type = p->frch_section.flags & SECTION_TYPE;
275		if(section_type != S_ZEROFILL &&
276		   section_type != S_THREAD_LOCAL_ZEROFILL)
277		    break;
278	    }
279	    if(p != NULL)
280		i = p->frch_section.addr - frchainP->frch_section.addr;
281	    else
282		i = frchainP->frch_section.size;
283	    reloc_segment.filesize += i;
284	    frchainP->frch_section.offset = offset;
285	    offset += i;
286	    reloc_segment.vmsize = frchainP->frch_section.addr +
287				   frchainP->frch_section.size;
288	}
289	for(frchainP = frchain_root; frchainP; frchainP = frchainP->frch_next){
290	    section_type = frchainP->frch_section.flags & SECTION_TYPE;
291	    if(section_type != S_ZEROFILL &&
292	       section_type != S_THREAD_LOCAL_ZEROFILL)
293		continue;
294	    reloc_segment.vmsize = frchainP->frch_section.addr +
295				   frchainP->frch_section.size;
296	}
297	offset = rnd(offset, sizeof(int32_t));
298
299	/*
300	 * Count the number of relocation entries for each section.
301	 */
302	for(frchainP = frchain_root; frchainP; frchainP = frchainP->frch_next){
303	    frchainP->frch_section.nreloc = 0;
304	    for(fixP = frchainP->frch_fix_root; fixP; fixP = fixP->fx_next){
305		frchainP->frch_section.nreloc += nrelocs_for_fix(fixP);
306	    }
307	}
308
309	/*
310	 * Fill in the offset to the relocation entries of the sections.
311	 */
312	offset = rnd(offset, sizeof(int32_t));
313	reloff = offset;
314	nrelocs = 0;
315	for(frchainP = frchain_root; frchainP; frchainP = frchainP->frch_next){
316	    if(frchainP->frch_section.nreloc == 0)
317		frchainP->frch_section.reloff = 0;
318	    else
319		frchainP->frch_section.reloff = offset;
320	    offset += frchainP->frch_section.nreloc *
321		      sizeof(struct relocation_info);
322	    nrelocs += frchainP->frch_section.nreloc;
323	}
324
325	if(flagseen['k']){
326	    /* fill in the fields of the dysymtab_command */
327	    dynamic_symbol_table.cmd = LC_DYSYMTAB;
328	    dynamic_symbol_table.cmdsize = sizeof(struct dysymtab_command);
329
330	    dynamic_symbol_table.ilocalsym = ilocalsym;
331	    dynamic_symbol_table.nlocalsym = nlocalsym;
332	    dynamic_symbol_table.iextdefsym = iextdefsym;
333	    dynamic_symbol_table.nextdefsym = nextdefsym;
334	    dynamic_symbol_table.iundefsym = iundefsym;
335	    dynamic_symbol_table.nundefsym = nundefsym;
336
337	    if(nindirectsyms == 0){
338		dynamic_symbol_table.nindirectsyms = 0;
339		dynamic_symbol_table.indirectsymoff = 0;
340	    }
341	    else{
342		dynamic_symbol_table.nindirectsyms = nindirectsyms;
343		dynamic_symbol_table.indirectsymoff = offset;
344		offset += nindirectsyms * sizeof(uint32_t);
345	    }
346
347	    dynamic_symbol_table.tocoff = 0;
348	    dynamic_symbol_table.ntoc = 0;
349	    dynamic_symbol_table.modtaboff = 0;
350	    dynamic_symbol_table.nmodtab = 0;
351	    dynamic_symbol_table.extrefsymoff = 0;
352	    dynamic_symbol_table.nextrefsyms = 0;
353	    dynamic_symbol_table.extreloff = 0;
354	    dynamic_symbol_table.nextrel = 0;
355	    dynamic_symbol_table.locreloff = 0;
356	    dynamic_symbol_table.nlocrel = 0;
357	}
358
359	/* fill in the fields of the symtab_command (except the string table) */
360	symbol_table.cmd = LC_SYMTAB;
361	symbol_table.cmdsize = sizeof(struct symtab_command);
362	if(nsyms == 0)
363	    symbol_table.symoff = 0;
364	else
365	    symbol_table.symoff = offset;
366	symbol_table.nsyms = nsyms;
367	offset += symbol_table.nsyms * sizeof(nlist_t);
368
369	/* fill in the string table fields of the symtab_command */
370	if(strsize == 0)
371	    symbol_table.stroff = 0;
372	else
373	    symbol_table.stroff = offset;
374	symbol_table.strsize = rnd(strsize, sizeof(uint32_t));
375	offset += rnd(strsize, sizeof(uint32_t));
376
377	/*
378	 * The second group of things to do is now with the size of everything
379	 * known the object file and the offsets set in the various structures
380	 * the contents of the object file can be created.
381	 */
382
383	/*
384	 * Create the buffer to copy the parts of the output file into.
385	 */
386	output_size = offset;
387	if((r = vm_allocate(mach_task_self(), (vm_address_t *)&output_addr,
388			    output_size, TRUE)) != KERN_SUCCESS)
389	    as_fatal("can't vm_allocate() buffer for output file of size %u",
390		     output_size);
391
392	/* put the headers in the output file's buffer */
393	host_byte_sex = get_host_byte_sex();
394	offset = 0;
395
396	/* put the mach_header in the buffer */
397	memcpy(output_addr + offset, &header, sizeof(mach_header_t));
398	if(host_byte_sex != md_target_byte_sex)
399	    swap_mach_header_t((mach_header_t *)(output_addr + offset),
400			       md_target_byte_sex);
401	offset += sizeof(mach_header_t);
402
403	/* put the segment_command in the buffer */
404	if(nsects != 0){
405	    memcpy(output_addr + offset, &reloc_segment,
406		   sizeof(segment_command_t));
407	    if(host_byte_sex != md_target_byte_sex)
408		swap_segment_command_t((segment_command_t *)
409				       (output_addr + offset),
410				       md_target_byte_sex);
411	    offset += sizeof(segment_command_t);
412	}
413
414	/* put the segment_command's section structures in the buffer */
415	for(frchainP = frchain_root; frchainP; frchainP = frchainP->frch_next){
416	    memcpy(output_addr + offset, &(frchainP->frch_section),
417		   sizeof(section_t));
418	    if(host_byte_sex != md_target_byte_sex)
419		swap_section_t((section_t *)(output_addr + offset), 1,
420			       md_target_byte_sex);
421	    offset += sizeof(section_t);
422	}
423
424	/* put the symbol_command in the buffer */
425	if(nsyms != 0){
426	    memcpy(output_addr + offset, &symbol_table,
427		   sizeof(struct symtab_command));
428	    if(host_byte_sex != md_target_byte_sex)
429		swap_symtab_command((struct symtab_command *)
430				     (output_addr + offset),
431				     md_target_byte_sex);
432	    offset += sizeof(struct symtab_command);
433	}
434
435	if(flagseen['k']){
436	    /* put the dysymbol_command in the buffer */
437	    if(nsyms != 0){
438		memcpy(output_addr + offset, &dynamic_symbol_table,
439		       sizeof(struct dysymtab_command));
440		if(host_byte_sex != md_target_byte_sex)
441		    swap_dysymtab_command((struct dysymtab_command *)
442					  (output_addr + offset),
443					  md_target_byte_sex);
444		offset += sizeof(struct dysymtab_command);
445	    }
446	}
447
448	/* put the section contents (frags) in the buffer */
449	for(frchainP = frchain_root; frchainP; frchainP = frchainP->frch_next){
450	    offset = frchainP->frch_section.offset;
451	    for(fragP = frchainP->frch_root; fragP; fragP = fragP->fr_next){
452		know(fragP->fr_type == rs_fill);
453		/* put the fixed part of the frag in the buffer */
454		memcpy(output_addr + offset, fragP->fr_literal, fragP->fr_fix);
455		offset += fragP->fr_fix;
456
457		/* put the variable repeated part of the frag in the buffer */
458		fill_literal = fragP->fr_literal + fragP->fr_fix;
459		fill_size = fragP->fr_var;
460		num_bytes = fragP->fr_offset * fragP->fr_var;
461		for(count = 0; count < num_bytes; count += fill_size){
462		    memcpy(output_addr + offset, fill_literal, fill_size);
463		    offset += fill_size;
464		}
465	    }
466	}
467
468
469	/* put the symbols in the output file's buffer */
470	offset = symbol_table.symoff;
471	for(symbolP = symbol_rootP; symbolP; symbolP = symbolP->sy_next){
472	    if((symbolP->sy_type & N_EXT) == 0){
473		symbol_name = symbolP->sy_name;
474		symbolP->sy_nlist.n_un.n_strx = symbolP->sy_name_offset;
475		if(symbolP->expression != 0) {
476		    expressionS *exp;
477
478		    exp = (expressionS *)symbolP->expression;
479		    if((exp->X_add_symbol->sy_type & N_TYPE) == N_UNDF)
480	    		as_fatal("undefined symbol `%s' in operation setting "
481				 "`%s'", exp->X_add_symbol->sy_name,
482				 symbol_name);
483		    if((exp->X_subtract_symbol->sy_type & N_TYPE) == N_UNDF)
484	    		as_fatal("undefined symbol `%s' in operation setting "
485				 "`%s'", exp->X_subtract_symbol->sy_name,
486				 symbol_name);
487		    if(exp->X_add_symbol->sy_other !=
488		       exp->X_subtract_symbol->sy_other)
489	    		as_fatal("invalid sections for operation on `%s' and "
490				 "`%s' setting `%s'",exp->X_add_symbol->sy_name,
491				 exp->X_subtract_symbol->sy_name, symbol_name);
492		    symbolP->sy_nlist.n_value +=
493			exp->X_add_symbol->sy_value -
494			exp->X_subtract_symbol->sy_value;
495		}
496		memcpy(output_addr + offset, (char *)(&symbolP->sy_nlist),
497		       sizeof(nlist_t));
498		symbolP->sy_name = symbol_name;
499		offset += sizeof(nlist_t);
500	    }
501	}
502	for(i = 0; i < nextdefsym; i++){
503	    symbol_name = extdefsyms[i]->sy_name;
504	    extdefsyms[i]->sy_nlist.n_un.n_strx = extdefsyms[i]->sy_name_offset;
505	    memcpy(output_addr + offset, (char *)(&extdefsyms[i]->sy_nlist),
506	           sizeof(nlist_t));
507	    extdefsyms[i]->sy_name = symbol_name;
508	    offset += sizeof(nlist_t);
509	}
510	for(j = 0; j < nundefsym; j++){
511	    symbol_name = undefsyms[j]->sy_name;
512	    undefsyms[j]->sy_nlist.n_un.n_strx = undefsyms[j]->sy_name_offset;
513	    memcpy(output_addr + offset, (char *)(&undefsyms[j]->sy_nlist),
514	           sizeof(nlist_t));
515	    undefsyms[j]->sy_name = symbol_name;
516	    offset += sizeof(nlist_t);
517	}
518	if(host_byte_sex != md_target_byte_sex)
519	    swap_nlist_t((nlist_t *)(output_addr + symbol_table.symoff),
520		         symbol_table.nsyms, md_target_byte_sex);
521
522	/*
523	 * Put the relocation entries for each section in the buffer.
524	 */
525	for(frchainP = frchain_root; frchainP; frchainP = frchainP->frch_next){
526	    offset = frchainP->frch_section.reloff;
527	    for(fixP = frchainP->frch_fix_root; fixP; fixP = fixP->fx_next){
528		offset += fix_to_relocation_entries(
529					fixP,
530					frchainP->frch_section.addr,
531					(struct relocation_info *)(output_addr +
532								   offset),
533				        frchainP->frch_section.flags &
534					  S_ATTR_DEBUG);
535	    }
536	}
537	if(host_byte_sex != md_target_byte_sex)
538	    swap_relocation_info((struct relocation_info *)
539		(output_addr + reloff), nrelocs, md_target_byte_sex);
540
541	if(flagseen['k']){
542	    /* put the indirect symbol table in the buffer */
543	    offset = dynamic_symbol_table.indirectsymoff;
544	    for(frchainP = frchain_root;
545		frchainP != NULL;
546		frchainP = frchainP->frch_next){
547		section_type = frchainP->frch_section.flags & SECTION_TYPE;
548		if(section_type == S_NON_LAZY_SYMBOL_POINTERS ||
549		   section_type == S_LAZY_SYMBOL_POINTERS ||
550		   section_type == S_SYMBOL_STUBS){
551		    /*
552		     * For each indirect symbol put out the symbol number.
553		     */
554		    for(isymbolP = frchainP->frch_isym_root;
555			isymbolP != NULL;
556			isymbolP = isymbolP->isy_next){
557			/*
558			 * If this is a non-lazy pointer symbol section and
559			 * if the symbol is a local symbol then put out
560			 * INDIRECT_SYMBOL_LOCAL as the indirect symbol table
561			 * entry.  This is used with code gen for fix-n-continue
562			 * where the compiler generates indirection for static
563			 * data references.  See the comments at the end of
564			 * fixup_section() that explains the assembly code used.
565			 */
566			if(section_type == S_NON_LAZY_SYMBOL_POINTERS &&
567			   (isymbolP->isy_symbol->sy_nlist.n_type & N_EXT) !=
568			    N_EXT){
569    			    local = INDIRECT_SYMBOL_LOCAL;
570			    if((isymbolP->isy_symbol->sy_nlist.n_type &
571				N_TYPE) == N_ABS)
572				local |= INDIRECT_SYMBOL_ABS;
573			    memcpy(output_addr + offset, (char *)(&local),
574	   			   sizeof(uint32_t));
575			}
576			else{
577			    memcpy(output_addr + offset,
578				   (char *)(&isymbolP->isy_symbol->sy_number),
579				   sizeof(uint32_t));
580			}
581			offset += sizeof(uint32_t);
582		    }
583		}
584	    }
585	    if(host_byte_sex != md_target_byte_sex){
586		indirect_symbols = (uint32_t *)(output_addr +
587				    dynamic_symbol_table.indirectsymoff);
588		swap_indirect_symbols(indirect_symbols, nindirectsyms,
589				      md_target_byte_sex);
590	    }
591	}
592
593	/* put the strings in the output file's buffer */
594	offset = symbol_table.stroff;
595	if(symbol_table.strsize != 0){
596	    zero = 0;
597	    memcpy(output_addr + offset, (char *)&zero, sizeof(char));
598	    offset += sizeof(char);
599	}
600	for(symbolP = symbol_rootP; symbolP; symbolP = symbolP->sy_next){
601	    /* Ordinary case: not .stabd. */
602	    if(symbolP->sy_name != NULL){
603		if((symbolP->sy_type & N_EXT) != 0){
604		    memcpy(output_addr + offset, symbolP->sy_name,
605			   strlen(symbolP->sy_name) + 1);
606		    offset += strlen(symbolP->sy_name) + 1;
607		}
608	    }
609	}
610	for(symbolP = symbol_rootP; symbolP; symbolP = symbolP->sy_next){
611	    /* Ordinary case: not .stabd. */
612	    if(symbolP->sy_name != NULL){
613		if((symbolP->sy_type & N_EXT) == 0){
614		    memcpy(output_addr + offset, symbolP->sy_name,
615			   strlen(symbolP->sy_name) + 1);
616		    offset += strlen(symbolP->sy_name) + 1;
617		}
618	    }
619	}
620	/*
621         * Create the output file.  The unlink() is done to handle the problem
622         * when the out_file_name is not writable but the directory allows the
623         * file to be removed (since the file may not be there the return code
624         * of the unlink() is ignored).
625         */
626	if(bad_error != 0)
627	    return;
628	/*
629	 * Avoid doing the unlink() on special files, just unlink regular files
630	 * that exist.
631	 */
632	if(stat(out_file_name, &stat_buf) != -1){
633	    if(stat_buf.st_mode & S_IFREG)
634		(void)unlink(out_file_name);
635	}
636	if((fd = open(out_file_name, O_WRONLY | O_CREAT | O_TRUNC, 0666)) == -1)
637	    as_fatal("can't create output file: %s", out_file_name);
638	if(write(fd, output_addr, output_size) != (int)output_size)
639	    as_fatal("can't write output file");
640	if(close(fd) == -1)
641	    as_fatal("can't close output file");
642}
643
644/*
645 * layout_indirect_symbols() setups the indirect symbol tables by looking up or
646 * creating symbol from the indirect symbol names and recording the symbol
647 * pointers.  It returns the total count of indirect symbol table entries.
648 */
649static
650uint32_t
651layout_indirect_symbols(void)
652{
653    struct frchain *frchainP;
654    uint32_t section_type, total, count, stride;
655    isymbolS *isymbolP;
656    symbolS *symbolP;
657
658	/*
659	 * Mark symbols that only appear in a lazy section with
660	 * REFERENCE_FLAG_UNDEFINED_LAZY.  To do this we first make sure a
661	 * symbol exists for all non-lazy symbols.  Then we make a pass looking
662	 * up the lazy symbols and if not there we make the symbol and mark it
663	 * with REFERENCE_FLAG_UNDEFINED_LAZY.
664	 */
665	for(frchainP = frchain_root; frchainP; frchainP = frchainP->frch_next){
666	    section_type = frchainP->frch_section.flags & SECTION_TYPE;
667	    if(section_type == S_NON_LAZY_SYMBOL_POINTERS){
668		for(isymbolP = frchainP->frch_isym_root;
669		    isymbolP != NULL;
670		    isymbolP = isymbolP->isy_next){
671/*
672(void)symbol_find_or_make(isymbolP->isy_name);
673*/
674		    symbolP = symbol_find(isymbolP->isy_name);
675		    if(symbolP == NULL){
676			symbolP = symbol_new(isymbolP->isy_name, N_UNDF, 0, 0,
677					     0, &zero_address_frag);
678			symbol_table_insert(symbolP);
679		    }
680		}
681	    }
682	}
683	for(frchainP = frchain_root; frchainP; frchainP = frchainP->frch_next){
684	    section_type = frchainP->frch_section.flags & SECTION_TYPE;
685	    if(section_type == S_LAZY_SYMBOL_POINTERS ||
686	       section_type == S_SYMBOL_STUBS){
687		for(isymbolP = frchainP->frch_isym_root;
688		    isymbolP != NULL;
689		    isymbolP = isymbolP->isy_next){
690
691		    symbolP = symbol_find(isymbolP->isy_name);
692		    if(symbolP == NULL){
693			symbolP = symbol_find_or_make(isymbolP->isy_name);
694			symbolP->sy_desc |= REFERENCE_FLAG_UNDEFINED_LAZY;
695		    }
696		}
697	    }
698	}
699
700	total = 0;
701	for(frchainP = frchain_root; frchainP; frchainP = frchainP->frch_next){
702	    section_type = frchainP->frch_section.flags & SECTION_TYPE;
703	    if(section_type == S_LAZY_SYMBOL_POINTERS ||
704	       section_type == S_NON_LAZY_SYMBOL_POINTERS ||
705	       section_type == S_SYMBOL_STUBS){
706		count = 0;
707		for(isymbolP = frchainP->frch_isym_root;
708		    isymbolP != NULL;
709		    isymbolP = isymbolP->isy_next){
710
711/*
712symbolP = symbol_find_or_make(isymbolP->isy_name);
713*/
714		    symbolP = symbol_find(isymbolP->isy_name);
715		    if(symbolP == NULL){
716			symbolP = symbol_new(isymbolP->isy_name, N_UNDF, 0, 0,
717					     0, &zero_address_frag);
718			symbol_table_insert(symbolP);
719		    }
720		    isymbolP->isy_symbol = symbolP;
721		    count++;
722		}
723		/*
724		 * Check for missing indirect symbols.
725		 */
726		if(section_type == S_SYMBOL_STUBS)
727		    stride = frchainP->frch_section.reserved2;
728		else
729		    stride = sizeof(signed_target_addr_t);
730		if(frchainP->frch_section.size / stride != count)
731		    as_bad("missing indirect symbols for section (%s,%s)",
732			    frchainP->frch_section.segname,
733			    frchainP->frch_section.sectname);
734		/*
735		 * Set the index into the indirect symbol table for this
736		 * section into the reserved1 field.
737		 */
738		frchainP->frch_section.reserved1 = total;
739		total += count;
740	    }
741	}
742	return(total);
743}
744
745
746/*
747 * set_BINCL_checksums() walks through all STABS and calculate BINCL checksums. This will improve
748 * linking performance because the linker will not need to touch and sum STABS
749 * strings to do the BINCL/EINCL duplicate removal.
750 *
751 * A BINCL checksum is a sum of all stabs strings within a BINCL/EINCL pair.
752 * Since BINCL/EINCL can be nested, a stab string contributes to only the
753 * innermost BINCL/EINCL enclosing it.
754 *
755 * The checksum excludes the first number after an open paren.
756 *
757 * Some stabs (e.g. SLINE) when found within a BINCL/EINCL disqualify the EXCL
758 * optimization and therefore disable this checksumming.
759 */
760static
761void
762set_BINCL_checksums()
763{
764    struct HeaderRange {
765	symbolS*		bincl;
766	struct HeaderRange*	parentRange;
767	unsigned int		sum;
768	int			okToChecksum;
769    };
770    symbolS *symbolP;
771    struct HeaderRange* curRange = NULL;
772
773	for(symbolP = symbol_rootP; symbolP; symbolP = symbolP->sy_next){
774	    if((symbolP->sy_nlist.n_type & N_STAB) != 0){
775		switch(symbolP->sy_nlist.n_type){
776		case N_BINCL:
777		    {
778			struct HeaderRange* range =
779			    xmalloc(sizeof(struct HeaderRange));
780			range->bincl = symbolP;
781			range->parentRange = curRange;
782			range->sum = 0;
783			range->okToChecksum = (symbolP->sy_nlist.n_value == 0);
784			curRange = range;
785		    }
786		    break;
787		case N_EINCL:
788		    if(curRange != NULL){
789			struct HeaderRange* tmp = curRange;
790			if (curRange->okToChecksum)
791			    curRange->bincl->sy_nlist.n_value = curRange->sum;
792			curRange = tmp->parentRange;
793			free(tmp);
794		    }
795		    break;
796		case N_FUN:
797		case N_BNSYM:
798		case N_ENSYM:
799		case N_LBRAC:
800		case N_RBRAC:
801		case N_SLINE:
802		case N_STSYM:
803		case N_LCSYM:
804		    if(curRange != NULL){
805			curRange->okToChecksum = FALSE;
806		    }
807		    break;
808		case N_EXCL:
809			break;
810		default:
811		    if(curRange != NULL){
812			if(curRange->okToChecksum){
813			    unsigned int sum = 0;
814			    const char* s = symbolP->sy_name;
815			    char c;
816			    while((c = *s++) != '\0'){
817				sum += c;
818				/*
819				 * Don't checkusm first number (file index)
820				 * after open paren in string.
821				 */
822				if(c == '('){
823				    while(isdigit(*s))
824					++s;
825				}
826			    }
827			    curRange->sum += sum;
828			}
829		    }
830		}
831	    }
832	}
833}
834
835/*
836 * layout_symbols() removes temporary symbols (symbols that are of the form L1
837 * and 1:) if the -L flag is not seen so the symbol table has only the symbols
838 * it will have in the output file.  Then each remaining symbol is given a
839 * symbol number and a string offset for the symbol name which also sizes the
840 * string table.
841 * The order of the symbol table is:
842 *	local symbols
843 *	defined external symbols (sorted by name)
844 *	undefined external symbols (sorted by name)
845 * The order of the string table is:
846 *	strings for external symbols
847 *	strings for local symbols
848 */
849static
850void
851layout_symbols(
852int32_t *symbol_number,
853int32_t *string_byte_count)
854{
855    uint32_t i, j;
856    symbolS *symbolP;
857    symbolS **symbolPP;
858    char *name;
859	int seenBINCL = FALSE;
860
861	*symbol_number = 0;
862	*string_byte_count = sizeof(char);
863
864	/*
865	 * First pass through the symbols remove temporary symbols that are not
866	 * going to be in the output file.  Also number the local symbols and
867	 * assign string offset to external symbols.
868	 */
869	symbolPP = &symbol_rootP;
870	while((symbolP = *symbolPP)){
871	    name = symbolP->sy_name;
872	    /*
873	     * Deal with temporary symbols.  Temporary symbols start with 'L'
874	     * but are not stabs.  It is an error if they are undefined.  They
875	     * are removed if the -L flag is not seen else they are kept.
876	     */
877	    if(name != NULL &&
878	       (symbolP->sy_nlist.n_type & N_STAB) == 0 &&
879	       name[0] == 'L'){
880
881	        if((symbolP->sy_nlist.n_type & N_TYPE) == N_UNDF){
882		    if(name[1] != '\0' && name[2] == '\001'){
883			as_bad("Undefined local symbol %c (%cf or %cb)",
884				name[1], name[1], name[1]);
885		    }
886		    else{
887			as_bad("Undefined local symbol %s", name);
888		    }
889		    /* don't keep this symbol */
890		    *symbolPP = symbolP->sy_next;
891		}
892	        else if(flagseen['L'] || (symbolP->sy_type & N_EXT) != 0
893#if defined(I386) && defined(ARCH64)
894			|| is_section_cstring_literals(symbolP->sy_other)
895#endif
896		){
897		    if((symbolP->sy_type & N_EXT) == 0){
898			nlocalsym++;
899			symbolP->sy_number = *symbol_number;
900			*symbol_number = *symbol_number + 1;
901		    }
902		    else{
903			nextdefsym++;
904			symbolP->sy_name_offset = *string_byte_count;
905			*string_byte_count += strlen(symbolP->sy_name) + 1;
906		    }
907		    symbolPP = &(symbolP->sy_next);
908		}
909		else{
910		    /* don't keep this symbol */
911		    *symbolPP = symbolP->sy_next;
912		}
913	    }
914	    /*
915	     * All non-temporary symbols will be the symbol table in the output
916	     * file.
917	     */
918	    else{
919		/* Any undefined symbols become N_EXT. */
920		if(symbolP->sy_type == N_UNDF)
921		    symbolP->sy_type |= N_EXT;
922
923		if((symbolP->sy_type & N_EXT) == 0){
924		    symbolP->sy_number = *symbol_number;
925		    *symbol_number = *symbol_number + 1;
926		    nlocalsym++;
927		}
928		else{
929		    if((symbolP->sy_type & N_TYPE) != N_UNDF)
930			nextdefsym++;
931		    else
932			nundefsym++;
933
934		    if(name != NULL){
935			/* the ordinary case (symbol has a name) */
936			symbolP->sy_name_offset = *string_byte_count;
937			*string_byte_count += strlen(symbolP->sy_name) + 1;
938		    }
939		    else{
940			/* the .stabd case (symbol has no name) */
941			symbolP->sy_name_offset = 0;
942		    }
943		}
944		symbolPP = &(symbolP->sy_next);
945	    }
946	}
947
948	/*
949	 * Check to see that any symbol that is marked as a weak_definition
950	 * is a global symbol defined in a coalesced section.
951	 */
952	for(symbolP = symbol_rootP; symbolP; symbolP = symbolP->sy_next){
953	    if((symbolP->sy_nlist.n_type & N_STAB) == 0 &&
954	       (symbolP->sy_desc & N_WEAK_DEF) == N_WEAK_DEF){
955		if((symbolP->sy_type & N_EXT) == 0){
956		    as_bad("Non-global symbol: %s can't be a weak_definition",
957			   symbolP->sy_name);
958		}
959		else if((symbolP->sy_type & N_TYPE) == N_UNDF){
960		    as_bad("Undefined symbol: %s can't be a weak_definition",
961			   symbolP->sy_name);
962		}
963	    }
964	}
965
966	/* Set the indexes for symbol groups into the symbol table */
967	ilocalsym = 0;
968	iextdefsym = nlocalsym;
969	iundefsym = nlocalsym + nextdefsym;
970
971	/* allocate arrays for sorting externals by name */
972	extdefsyms = xmalloc(nextdefsym * sizeof(symbolS *));
973	undefsyms = xmalloc(nundefsym * sizeof(symbolS *));
974
975	i = 0;
976	j = 0;
977	for(symbolP = symbol_rootP; symbolP; symbolP = symbolP->sy_next){
978	    if((symbolP->sy_type & N_EXT) == 0){
979		if(symbolP->sy_name != NULL){
980		    /* the ordinary case (symbol has a name) */
981		    symbolP->sy_name_offset = *string_byte_count;
982		    *string_byte_count += strlen(symbolP->sy_name) + 1;
983		    /* check for existance of BINCL/EINCL */
984		    if(symbolP->sy_nlist.n_type == N_BINCL)
985			seenBINCL = TRUE;
986		}
987		else{
988		    /* the .stabd case (symbol has no name) */
989		    symbolP->sy_name_offset = 0;
990		}
991	    }
992	    else{
993		if((symbolP->sy_type & N_TYPE) != N_UNDF)
994		    extdefsyms[i++] = symbolP;
995		else
996		    undefsyms[j++] = symbolP;
997	    }
998	}
999	qsort(extdefsyms, nextdefsym, sizeof(symbolS *),
1000	      (int (*)(const void *, const void *))qsort_compare);
1001	qsort(undefsyms, nundefsym, sizeof(symbolS *),
1002	      (int (*)(const void *, const void *))qsort_compare);
1003	for(i = 0; i < nextdefsym; i++){
1004	    extdefsyms[i]->sy_number = *symbol_number;
1005	    *symbol_number = *symbol_number + 1;
1006	}
1007	for(j = 0; j < nundefsym; j++){
1008	    undefsyms[j]->sy_number = *symbol_number;
1009	    *symbol_number = *symbol_number + 1;
1010	}
1011
1012	/* calculate BINCL checksums */
1013	if(seenBINCL)
1014	    set_BINCL_checksums();
1015}
1016
1017/*
1018 * Function for qsort to sort symbol structs by their name
1019 */
1020static
1021int
1022qsort_compare(
1023const symbolS **sym1,
1024const symbolS **sym2)
1025{
1026        return(strcmp((*sym1)->sy_name, (*sym2)->sy_name));
1027}
1028
1029/*
1030 * nrelocs_for_fix() returns the number of relocation entries needed for the
1031 * specified fix structure.
1032 */
1033static
1034uint32_t
1035nrelocs_for_fix(
1036struct fix *fixP)
1037{
1038	/*
1039	 * If fx_addsy is NULL then this fix needs no relocation entry.
1040	 */
1041	if(fixP->fx_addsy == NULL)
1042	    return(0);
1043
1044	/*
1045	 * If this fix has a subtract symbol it is a SECTDIFF relocation which
1046	 * takes two relocation entries.
1047	 */
1048	if(fixP->fx_subsy != NULL)
1049	    return(2);
1050
1051	/*
1052	 * For RISC machines whenever we have a relocation item using the half
1053	 * of an address a second a relocation item describing the other
1054	 * half of the address is used.
1055	 */
1056#ifdef I860
1057	if(fixP->fx_r_type == I860_RELOC_HIGH ||
1058	   fixP->fx_r_type == I860_RELOC_HIGHADJ)
1059	    return(2);
1060#endif
1061#ifdef M88K
1062	if(fixP->fx_r_type == M88K_RELOC_HI16 ||
1063	   fixP->fx_r_type == M88K_RELOC_LO16)
1064	    return(2);
1065#endif
1066#ifdef PPC
1067	if(fixP->fx_r_type == PPC_RELOC_HI16 ||
1068	   fixP->fx_r_type == PPC_RELOC_LO16 ||
1069	   fixP->fx_r_type == PPC_RELOC_HA16 ||
1070	   fixP->fx_r_type == PPC_RELOC_LO14 ||
1071	   fixP->fx_r_type == PPC_RELOC_JBSR)
1072	    return(2);
1073#endif
1074#ifdef HPPA
1075	if(fixP->fx_r_type == HPPA_RELOC_HI21 ||
1076	   fixP->fx_r_type == HPPA_RELOC_LO14 ||
1077	   fixP->fx_r_type == HPPA_RELOC_BR17 ||
1078	   fixP->fx_r_type == HPPA_RELOC_JBSR)
1079	    return(2);
1080#endif
1081#ifdef SPARC
1082	if(fixP->fx_r_type == SPARC_RELOC_HI22 ||
1083	   fixP->fx_r_type == SPARC_RELOC_LO10)
1084	    return(2);
1085#endif
1086#ifdef ARM
1087	if(fixP->fx_r_type == ARM_RELOC_LO16 ||
1088	   fixP->fx_r_type == ARM_RELOC_HI16 ||
1089	   fixP->fx_r_type == ARM_THUMB_RELOC_LO16 ||
1090	   fixP->fx_r_type == ARM_THUMB_RELOC_HI16)
1091	    return(2);
1092#endif
1093	return(1);
1094}
1095
1096/*
1097 * fix_to_relocation_entries() creates the needed relocation entries for the
1098 * specified fix structure that is from a section who's address starts at
1099 * sect_addr.  It returns the number of bytes of relocation_info structs it
1100 * placed at riP.
1101 */
1102static
1103uint32_t
1104fix_to_relocation_entries(
1105struct fix *fixP,
1106uint64_t sect_addr,
1107struct relocation_info *riP,
1108uint32_t debug_section)
1109{
1110    struct symbol *symbolP;
1111    uint32_t count;
1112    struct scattered_relocation_info sri;
1113    uint32_t sectdiff;
1114#ifdef HPPA
1115    uint32_t left21, right14;
1116#endif
1117
1118	/*
1119	 * If fx_addsy is NULL then this fix needs no relocation entry.
1120	 */
1121	if(fixP->fx_addsy == NULL)
1122	    return(0);
1123
1124#ifdef TC_VALIDATE_FIX
1125	TC_VALIDATE_FIX(fixP, sect_addr, 0);
1126#endif
1127
1128	memset(riP, '\0', sizeof(struct relocation_info));
1129	symbolP = fixP->fx_addsy;
1130
1131#ifdef ARM
1132	/* see arm_reloc.h for the encodings in the low 2 bits */
1133	if(fixP->fx_r_type == ARM_RELOC_LO16 ||
1134	   fixP->fx_r_type == ARM_RELOC_HI16 ||
1135	   fixP->fx_r_type == ARM_THUMB_RELOC_LO16 ||
1136	   fixP->fx_r_type == ARM_THUMB_RELOC_HI16){
1137	    riP->r_length = fixP->fx_r_type & 0x3;
1138	}
1139	else
1140#endif
1141	switch(fixP->fx_size){
1142	    case 1:
1143		riP->r_length = 0;
1144		break;
1145	    case 2:
1146		riP->r_length = 1;
1147		break;
1148	    case 4:
1149#ifdef PPC
1150		if(fixP->fx_r_type == PPC_RELOC_BR14_predicted)
1151		    riP->r_length = 3;
1152		else
1153#endif
1154		riP->r_length = 2;
1155		break;
1156#if defined(ARCH64)
1157	    case 8:
1158		riP->r_length = 3;
1159		break;
1160#endif /* defined(ARCH64) */
1161	    default:
1162		layout_file = fixP->file;
1163		layout_line = fixP->line;
1164		as_fatal("Bad fx_size (0x%x) in fix_to_relocation_info()\n",
1165			 fixP->fx_size);
1166	}
1167	riP->r_pcrel = fixP->fx_pcrel;
1168	riP->r_address = fixP->fx_frag->fr_address + fixP->fx_where -
1169			 sect_addr;
1170#ifdef ARM
1171	if(fixP->fx_r_type == ARM_RELOC_LO16 ||
1172	   fixP->fx_r_type == ARM_RELOC_HI16 ||
1173	   fixP->fx_r_type == ARM_THUMB_RELOC_LO16 ||
1174	   fixP->fx_r_type == ARM_THUMB_RELOC_HI16){
1175	    riP->r_type = ARM_RELOC_HALF;
1176	}
1177	else
1178#endif
1179	riP->r_type = fixP->fx_r_type;
1180	/*
1181	 * For undefined symbols this will be an external relocation entry.
1182	 * Or if this is an external coalesced symbol or weak symbol.
1183	 */
1184#if defined(I386) && defined(ARCH64)
1185	if(fixP->fx_subsy == NULL &&
1186	   (!debug_section || (symbolP->sy_type & N_TYPE) == N_UNDF) &&
1187	   (!is_local_symbol(symbolP) ||
1188	    ((symbolP->sy_type & N_TYPE) == N_SECT &&
1189	     is_section_cstring_literals(symbolP->sy_other)) ) ) {
1190#else
1191	if((symbolP->sy_type & N_TYPE) == N_UNDF ||
1192	   ((symbolP->sy_type & N_EXT) == N_EXT &&
1193	    (symbolP->sy_type & N_TYPE) == N_SECT &&
1194	    (is_section_coalesced(symbolP->sy_other) ||
1195	     (symbolP->sy_desc & N_WEAK_DEF) == N_WEAK_DEF) &&
1196	    fixP->fx_subsy == NULL)
1197#if defined(I386) && !defined(ARCH64)
1198	   ||
1199	   ((symbolP->sy_type & N_TYPE) == N_SECT &&
1200	    fixP->fx_r_type == GENERIC_RELOC_TLV)
1201#endif
1202        ){
1203#endif
1204	    riP->r_extern = 1;
1205	    riP->r_symbolnum = symbolP->sy_number;
1206	}
1207	else{
1208	    /*
1209	     * For defined symbols this will be a local relocation entry
1210	     * (possibly a section difference or a scattered relocation entry).
1211	     */
1212	    riP->r_extern = 0;
1213	    riP->r_symbolnum = symbolP->sy_other; /* nsect */
1214
1215	    /*
1216	     * Determine if this is left as a local relocation entry or
1217	     * changed to a SECTDIFF relocation entry.  If this comes from a fix
1218	     * that has a subtract symbol it is a SECTDIFF relocation.  Which is
1219	     * "addsy - subsy + constant" where both symbols are defined in
1220	     * sections.  To encode all this information two scattered
1221	     * relocation entries are used.  The first has the add symbol value
1222	     * and the second has the subtract symbol value.
1223	     */
1224	    if(fixP->fx_subsy != NULL){
1225#if defined(I386) && defined(ARCH64)
1226		/* Encode fixP->fx_subsy (B) first, then symbolP (fixP->fx_addsy) (A). */
1227		if (is_local_symbol(fixP->fx_subsy))
1228		{
1229			riP->r_extern = 0;
1230			riP->r_symbolnum = fixP->fx_subsy->sy_other;
1231		}
1232		else
1233		{
1234			riP->r_extern = 1;
1235			riP->r_symbolnum = fixP->fx_subsy->sy_number;
1236		}
1237		riP->r_type = X86_64_RELOC_SUBTRACTOR;
1238
1239		/* Now write out the unsigned relocation entry. */
1240		riP++;
1241		*riP = *(riP - 1);
1242		if (is_local_symbol(fixP->fx_addsy))
1243		{
1244			riP->r_extern = 0;
1245			riP->r_symbolnum = fixP->fx_addsy->sy_other;
1246		}
1247		else
1248		{
1249			riP->r_extern = 1;
1250			riP->r_symbolnum = fixP->fx_addsy->sy_number;
1251		}
1252		riP->r_type = X86_64_RELOC_UNSIGNED;
1253		return(2 * sizeof(struct relocation_info));
1254#endif
1255#ifdef PPC
1256		if(fixP->fx_r_type == PPC_RELOC_HI16)
1257		    sectdiff = PPC_RELOC_HI16_SECTDIFF;
1258		else if(fixP->fx_r_type == PPC_RELOC_LO16)
1259		    sectdiff = PPC_RELOC_LO16_SECTDIFF;
1260		else if(fixP->fx_r_type == PPC_RELOC_HA16)
1261		    sectdiff = PPC_RELOC_HA16_SECTDIFF;
1262		else if(fixP->fx_r_type == PPC_RELOC_LO14)
1263		    sectdiff = PPC_RELOC_LO14_SECTDIFF;
1264		else
1265#endif
1266#ifdef HPPA
1267		if(fixP->fx_r_type == HPPA_RELOC_HI21)
1268		    sectdiff = HPPA_RELOC_HI21_SECTDIFF;
1269		else if(fixP->fx_r_type == HPPA_RELOC_LO14)
1270		    sectdiff = HPPA_RELOC_LO14_SECTDIFF;
1271		else
1272#endif
1273#ifdef SPARC
1274		if(fixP->fx_r_type == SPARC_RELOC_HI22)
1275		    sectdiff = SPARC_RELOC_HI22_SECTDIFF;
1276		else if(fixP->fx_r_type == SPARC_RELOC_LO10)
1277		    sectdiff = SPARC_RELOC_LO10_SECTDIFF;
1278		else
1279#endif
1280#ifdef ARM
1281		if(fixP->fx_r_type == ARM_RELOC_LO16 ||
1282		   fixP->fx_r_type == ARM_RELOC_HI16 ||
1283		   fixP->fx_r_type == ARM_THUMB_RELOC_LO16 ||
1284		   fixP->fx_r_type == ARM_THUMB_RELOC_HI16)
1285		    sectdiff = ARM_RELOC_HALF_SECTDIFF;
1286		else
1287#endif
1288		{
1289		    if(fixP->fx_r_type != 0 && fixP->fx_r_type != NO_RELOC){
1290			layout_file = fixP->file;
1291			layout_line = fixP->line;
1292			as_fatal("Internal error: incorrect fx_r_type (%u) for "
1293				 "fx_subsy != 0 in fix_to_relocation_info()",
1294				 fixP->fx_r_type);
1295		    }
1296		    if((!(fixP->fx_addsy->sy_type & N_EXT)) && flagseen['k'])
1297			sectdiff = RELOC_LOCAL_SECTDIFF;
1298		    else
1299			sectdiff = RELOC_SECTDIFF;
1300		}
1301		memset(&sri, '\0',sizeof(struct scattered_relocation_info));
1302		sri.r_scattered = 1;
1303#ifdef ARM
1304		/* see arm_reloc.h for the encodings in the low 2 bits */
1305		if(fixP->fx_r_type == ARM_RELOC_LO16 ||
1306		   fixP->fx_r_type == ARM_RELOC_HI16 ||
1307		   fixP->fx_r_type == ARM_THUMB_RELOC_LO16 ||
1308		   fixP->fx_r_type == ARM_THUMB_RELOC_HI16)
1309		    sri.r_length = fixP->fx_r_type & 0x3;
1310		else
1311#endif
1312		sri.r_length    = riP->r_length;
1313		sri.r_pcrel     = riP->r_pcrel;
1314		sri.r_address   = riP->r_address;
1315                if(sri.r_address != riP->r_address)
1316		    as_fatal("Section too large, can't encode r_address (0x%x) "
1317			     "into 24-bits of scattered relocation entry",
1318			     riP->r_address);
1319		sri.r_type      = sectdiff;
1320		sri.r_value     = symbolP->sy_value;
1321		*riP = *((struct relocation_info *)&sri);
1322		riP++;
1323
1324		sri.r_type      = RELOC_PAIR;
1325		sri.r_value     = fixP->fx_subsy->sy_value;
1326		if(sectdiff == RELOC_SECTDIFF ||
1327		   sectdiff == RELOC_LOCAL_SECTDIFF)
1328		    sri.r_address = 0;
1329#ifdef PPC
1330		else if(sectdiff == PPC_RELOC_HI16_SECTDIFF ||
1331		        sectdiff == PPC_RELOC_HA16_SECTDIFF){
1332		    sri.r_address = (symbolP->sy_value -
1333				     fixP->fx_subsy->sy_value
1334				     + fixP->fx_offset) & 0xffff;
1335		}
1336		else if(sectdiff == PPC_RELOC_LO16_SECTDIFF ||
1337			sectdiff == PPC_RELOC_LO14_SECTDIFF){
1338		    sri.r_address = ((symbolP->sy_value -
1339				      fixP->fx_subsy->sy_value +
1340				      fixP->fx_offset) >> 16) & 0xffff;
1341		}
1342#endif
1343#ifdef HPPA
1344		else if(sectdiff == HPPA_RELOC_HI21_SECTDIFF){
1345		    calc_hppa_HILO(symbolP->sy_value - fixP->fx_subsy->sy_value,
1346				   fixP->fx_offset, &left21, &right14);
1347		    sri.r_address = right14 & 0x3fff;
1348		}
1349		else if(sectdiff == HPPA_RELOC_LO14_SECTDIFF){
1350		    calc_hppa_HILO(symbolP->sy_value - fixP->fx_subsy->sy_value,
1351				   fixP->fx_offset, &left21, &right14);
1352		    sri.r_address = left21 >> 11;
1353		}
1354#endif
1355#ifdef SPARC
1356		else if(sectdiff == SPARC_RELOC_HI22_SECTDIFF){
1357		    sri.r_address = (symbolP->sy_value -
1358				     fixP->fx_subsy->sy_value
1359				     + fixP->fx_offset) & 0x3ff;
1360		}
1361		else if(sectdiff == SPARC_RELOC_LO10_SECTDIFF){
1362		    sri.r_address = ((symbolP->sy_value -
1363				      fixP->fx_subsy->sy_value +
1364				      fixP->fx_offset) >> 10) & 0x3fffff;
1365		}
1366#endif
1367#ifdef ARM
1368		else if(sectdiff == ARM_RELOC_HALF_SECTDIFF){
1369		    if((sri.r_length & 0x1) == 0x1)
1370			sri.r_address = (symbolP->sy_value -
1371					 fixP->fx_subsy->sy_value
1372					 + fixP->fx_offset) & 0xffff;
1373		    else
1374			sri.r_address = ((symbolP->sy_value -
1375					  fixP->fx_subsy->sy_value +
1376					  fixP->fx_offset) >> 16) & 0xffff;
1377		}
1378#endif
1379		*riP = *((struct relocation_info *)&sri);
1380		return(2 * sizeof(struct relocation_info));
1381	    }
1382	    /*
1383	     * Determine if this is left as a local relocation entry or must be
1384	     * changed to a scattered relocation entry.  These entries allow
1385	     * the link editor to scatter the contents of a section and a local
1386	     * relocation can't be used when an offset is added to the symbol's
1387	     * value (symbol + offset).  This is because the relocation must be
1388	     * based on the value of the symbol not the value of the expression.
1389	     * Thus a scattered relocation entry that encodes the address of the
1390	     * symbol is used when the offset is non-zero.  Unfortunately this
1391	     * encoding only allows for 24 bits in the r_address field and can
1392	     * overflow.  So it if it would overflow we don't create a
1393	     * scattered relocation entry and hope the offset does not reach
1394	     * out of the block or the linker will not be doing scattered
1395	     * loading on this symbol in this object file.
1396	     */
1397#if !defined(I860) && !(defined(I386) && defined(ARCH64))
1398	    /*
1399	     * For processors that don't have all references as unique 32 bits
1400	     * wide references scattered relocation entries are not generated.
1401	     * This is so that the link editor does not get stuck not being able
1402	     * to do the relocation if the high half of the reference is shared
1403	     * by two references to two different symbols.
1404	     */
1405	    if(fixP->fx_offset != 0 &&
1406	       (riP->r_address & 0xff000000) == 0 &&
1407	       ((symbolP->sy_type & N_TYPE) & ~N_EXT) != N_ABS
1408#ifdef M68K
1409	       /*
1410		* Since the m68k's pc relative branch instructions use the
1411		* address of the beginning of the displacement (except for
1412		* byte) the code in m68k.c when generating fixes adds to the
1413		* offset 2 for word and 4 for long displacements.
1414		*/
1415	       && !(fixP->fx_pcrel &&
1416	            ((fixP->fx_size == 2 && fixP->fx_offset == 2) ||
1417	             (fixP->fx_size == 4 && fixP->fx_offset == 4)) )
1418#endif /* M68K */
1419	       ){
1420		memset(&sri, '\0',sizeof(struct scattered_relocation_info));
1421		sri.r_scattered = 1;
1422		sri.r_length    = riP->r_length;
1423		sri.r_pcrel     = riP->r_pcrel;
1424		sri.r_address   = riP->r_address;
1425                if(sri.r_address != riP->r_address)
1426		    as_fatal("Section too large, can't encode r_address (0x%x) "
1427			     "into 24-bits of scattered relocation entry",
1428			     riP->r_address);
1429		sri.r_type      = riP->r_type;
1430		sri.r_value     = symbolP->sy_value;
1431		*riP = *((struct relocation_info *)&sri);
1432	    }
1433#endif /* !defined(I860) && !(defined(I386) && defined(ARCH64)) */
1434	}
1435	count = 1;
1436	riP++;
1437
1438#if !defined(M68K) && !defined(I386)
1439	/*
1440	 * For RISC machines whenever we have a relocation item using the half
1441	 * of an address we also emit a relocation item describing the other
1442	 * half of the address so the linker can reconstruct the address to do
1443	 * the relocation.
1444	 */
1445#ifdef I860
1446	if(fixP->fx_r_type == I860_RELOC_HIGH ||
1447	   fixP->fx_r_type == I860_RELOC_HIGHADJ)
1448#endif
1449#ifdef M88K
1450	if(fixP->fx_r_type == M88K_RELOC_HI16 ||
1451	   fixP->fx_r_type == M88K_RELOC_LO16)
1452#endif
1453#ifdef PPC
1454	if(fixP->fx_r_type == PPC_RELOC_HI16 ||
1455	   fixP->fx_r_type == PPC_RELOC_LO16 ||
1456	   fixP->fx_r_type == PPC_RELOC_HA16 ||
1457	   fixP->fx_r_type == PPC_RELOC_LO14 ||
1458	   fixP->fx_r_type == PPC_RELOC_JBSR)
1459#endif
1460#ifdef HPPA
1461	if(fixP->fx_r_type == HPPA_RELOC_HI21 ||
1462	   fixP->fx_r_type == HPPA_RELOC_LO14 ||
1463	   fixP->fx_r_type == HPPA_RELOC_BR17 ||
1464	   fixP->fx_r_type == HPPA_RELOC_JBSR)
1465#endif
1466#ifdef SPARC
1467	if(fixP->fx_r_type == SPARC_RELOC_HI22 ||
1468	   fixP->fx_r_type == SPARC_RELOC_LO10)
1469#endif
1470#ifdef ARM
1471	if(fixP->fx_r_type == ARM_RELOC_LO16 ||
1472	   fixP->fx_r_type == ARM_RELOC_HI16 ||
1473	   fixP->fx_r_type == ARM_THUMB_RELOC_LO16 ||
1474	   fixP->fx_r_type == ARM_THUMB_RELOC_HI16)
1475#endif
1476	{
1477	    memset(riP, '\0', sizeof(struct relocation_info));
1478#ifdef ARM
1479	    /* see arm_reloc.h for the encodings in the low 2 bits */
1480	    if(fixP->fx_r_type == ARM_RELOC_LO16 ||
1481	       fixP->fx_r_type == ARM_RELOC_HI16 ||
1482	       fixP->fx_r_type == ARM_THUMB_RELOC_LO16 ||
1483	       fixP->fx_r_type == ARM_THUMB_RELOC_HI16){
1484		riP->r_length = fixP->fx_r_type & 0x3;
1485	    }
1486	    else
1487#endif
1488	    switch(fixP->fx_size){
1489		case 1:
1490		    riP->r_length = 0;
1491		    break;
1492		case 2:
1493		    riP->r_length = 1;
1494		    break;
1495		case 4:
1496		    riP->r_length = 2;
1497		    break;
1498#if defined(ARCH64)
1499                case 8:
1500                    riP->r_length = 3;
1501                    break;
1502#endif /* defined(ARCH64) */
1503		default:
1504		    as_fatal("Bad fx_size (0x%x) in fix_to_relocation_info()\n",
1505			     fixP->fx_size);
1506	    }
1507	    riP->r_pcrel = fixP->fx_pcrel;
1508	    /*
1509	     * We set r_extern to 0, so other apps won't try to use r_symbolnum
1510	     * as a symbol table indice.  We set all the bits of r_symbolnum so
1511	     * it is all but guaranteed to be outside the range we use for non-
1512	     * external types to denote what section the relocation is in.
1513	     */
1514	    riP->r_extern = 0;
1515	    riP->r_symbolnum = 0x00ffffff;
1516#ifdef I860
1517	    riP->r_type	= I860_RELOC_PAIR;
1518	    riP->r_address = 0xffff & fixP->fx_value;
1519#endif
1520#ifdef M88K
1521	    riP->r_type = M88K_RELOC_PAIR;
1522	    if(fixP->fx_r_type == M88K_RELOC_HI16)
1523		riP->r_address = 0xffff & fixP->fx_value;
1524	    else if(fixP->fx_r_type == M88K_RELOC_LO16)
1525		riP->r_address = 0xffff & (fixP->fx_value >> 16);
1526#endif
1527#ifdef PPC
1528	    riP->r_type = PPC_RELOC_PAIR;
1529	    if(fixP->fx_r_type == PPC_RELOC_HI16 ||
1530	       fixP->fx_r_type == PPC_RELOC_HA16)
1531		riP->r_address = 0xffff & fixP->fx_value;
1532	    else if(fixP->fx_r_type == PPC_RELOC_LO16 ||
1533		    fixP->fx_r_type == PPC_RELOC_LO14)
1534		riP->r_address = 0xffff & (fixP->fx_value >> 16);
1535	    else if (fixP->fx_r_type == PPC_RELOC_JBSR){
1536		/*
1537		 * To allow the "true target address" to use the full 32 bits
1538		 * we convert this PAIR relocation entry to a scattered
1539		 * relocation entry if the true target address has the
1540		 * high bit (R_SCATTERED) set and store the "true target
1541		 * address" in the r_value field.  Or for an external relocation
1542		 * entry if the "offset" to the symbol has the high bit set
1543		 * we also use a scattered relocation entry.
1544		 */
1545		if((fixP->fx_value & R_SCATTERED) == 0){
1546		    riP->r_address = fixP->fx_value;
1547		}
1548		else{
1549		    memset(&sri, '\0',sizeof(struct scattered_relocation_info));
1550		    sri.r_scattered = 1;
1551		    sri.r_pcrel     = riP->r_pcrel;
1552		    sri.r_length    = riP->r_length;
1553		    sri.r_type      = riP->r_type;
1554		    sri.r_address   = 0;
1555		    sri.r_value     = fixP->fx_value;
1556		    *riP = *((struct relocation_info *)&sri);
1557		}
1558	    }
1559#endif
1560#ifdef HPPA
1561	    riP->r_type	 = HPPA_RELOC_PAIR;
1562	    calc_hppa_HILO(fixP->fx_value - fixP->fx_offset,
1563			   fixP->fx_offset, &left21, &right14);
1564	    if (fixP->fx_r_type == HPPA_RELOC_LO14 ||
1565		fixP->fx_r_type == HPPA_RELOC_BR17)
1566		riP->r_address = left21 >> 11;
1567	    else if (fixP->fx_r_type == HPPA_RELOC_HI21)
1568		riP->r_address = right14 & 0x3fff;
1569	    else if (fixP->fx_r_type == HPPA_RELOC_JBSR){
1570		if((symbolP->sy_type & N_TYPE) == N_UNDF)
1571		    riP->r_address = fixP->fx_value & 0xffffff;
1572		else
1573		    riP->r_address = (fixP->fx_value - sect_addr) & 0xffffff;
1574	    }
1575#endif
1576#ifdef SPARC
1577	    riP->r_type	 = SPARC_RELOC_PAIR;
1578	    if (fixP->fx_r_type == SPARC_RELOC_HI22)
1579		riP->r_address = fixP->fx_value & 0x3ff;
1580	    else if (fixP->fx_r_type == SPARC_RELOC_LO10)
1581		riP->r_address = (fixP->fx_value >> 10) & 0x3fffff;
1582#endif
1583#ifdef ARM
1584	    riP->r_type = ARM_RELOC_PAIR;
1585	    if(fixP->fx_r_type == ARM_RELOC_HI16 ||
1586	       fixP->fx_r_type == ARM_THUMB_RELOC_HI16)
1587		riP->r_address = 0xffff & fixP->fx_value;
1588	    else if(fixP->fx_r_type == ARM_RELOC_LO16 ||
1589		    fixP->fx_r_type == ARM_THUMB_RELOC_LO16)
1590		riP->r_address = 0xffff & (fixP->fx_value >> 16);
1591#endif
1592	    count = 2;
1593	}
1594#endif /* !defined(M68K) && !defined(I386) */
1595	return(count * sizeof(struct relocation_info));
1596}
1597
1598#ifdef I860
1599/*
1600 * set_default_section_align() is used to set a default minimum section
1601 * alignment if the section exist.
1602 */
1603static
1604void
1605set_default_section_align(
1606char *segname,
1607char *sectname,
1608uint32_t align)
1609{
1610    frchainS *frcP;
1611
1612	for(frcP = frchain_root; frcP != NULL; frcP = frcP->frch_next){
1613	    if(strncmp(frcP->frch_section.segname, segname,
1614		       sizeof(frcP->frch_section.segname)) == 0 &&
1615	       strncmp(frcP->frch_section.sectname, sectname,
1616		       sizeof(frcP->frch_section.sectname)) == 0){
1617		if(align > frcP->frch_section.align)
1618		    frcP->frch_section.align = align;
1619		return;
1620	    }
1621	}
1622}
1623
1624/*
1625 * clear_section_flags() clears the section types for literals from the section
1626 * flags field.  This is needed for processors that don't have all references
1627 * to sections as unique 32 bits wide references.  In this case the literal
1628 * flags are not set.  This is so that the link editor does not merge them and
1629 * get stuck not being able to fit the relocated address in the item to be
1630 * relocated or if the high half of the reference is shared by two references
1631 * to different symbols (which can also stick the link editor).
1632 */
1633static
1634void
1635clear_section_flags(void)
1636{
1637    frchainS *frcP;
1638
1639	for(frcP = frchain_root; frcP != NULL; frcP = frcP->frch_next)
1640	    if(frcP->frch_section.flags != S_ZEROFILL &&
1641	       frcP->frch_section.flags != S_THREAD_LOCAL_ZEROFILL)
1642		frcP->frch_section.flags = 0;
1643}
1644
1645/*
1646 * I860_tweeks() preforms the tweeks needed by the I860 processor to get minimum
1647 * section alignments and no merging of literals by the link editor.
1648 */
1649static
1650void
1651I860_tweeks(void)
1652{
1653	set_default_section_align("__TEXT", "__text", 5);
1654	set_default_section_align("__DATA", "__data", 4);
1655	set_default_section_align("__DATA", "__bss",  4);
1656
1657	clear_section_flags();
1658}
1659#endif
1660
1661/* FROM write.c line 2764 */
1662void
1663number_to_chars_bigendian (char *buf, signed_expr_t val, int n)
1664{
1665  if (n <= 0)
1666    abort ();
1667  while (n--)
1668    {
1669      buf[n] = val & 0xff;
1670      val >>= 8;
1671    }
1672}
1673
1674void
1675number_to_chars_littleendian (char *buf, signed_expr_t val, int n)
1676{
1677  if (n <= 0)
1678    abort ();
1679  while (n--)
1680    {
1681      *buf++ = val & 0xff;
1682      val >>= 8;
1683    }
1684}
1685