1/*
2 * Copyright (c) 1999-2006 Apple Computer, Inc. All rights reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23#ifdef SHLIB
24#include "shlib.h"
25#endif /* SHLIB */
26/*
27 * This file contains the routines that drives pass1 of the link-editor.  In
28 * pass1 the objects needed from archives are selected for loading and all of
29 * the things that need to be merged from the input objects are merged into
30 * tables (for output and relocation on the second pass).
31 */
32#include <stdlib.h>
33#include <stdarg.h>
34#include <string.h>
35#include <sys/file.h>
36#include <sys/types.h>
37#include <sys/stat.h>
38#include "stuff/openstep_mach.h"
39#include <mach-o/fat.h>
40#include <mach-o/loader.h>
41#include <mach-o/nlist.h>
42#include <mach-o/reloc.h>
43#include <mach-o/ldsyms.h>
44#if !(defined(KLD) && defined(__STATIC__))
45#include <libc.h>
46#include <stdio.h>
47#include <mach/mach.h>
48#include <errno.h>
49#include <limits.h>
50#include <ctype.h>
51#else /* defined(KLD) && defined(__STATIC__) */
52#include <mach/kern_return.h>
53#endif /* !(defined(KLD) && defined(__STATIC__)) */
54#include <ar.h>
55#ifndef AR_EFMT1
56#define	AR_EFMT1	"#1/"		/* extended format #1 */
57#endif
58#include <mach-o/ranlib.h>
59#include "stuff/arch.h"
60#include "stuff/best_arch.h"
61#include "stuff/guess_short_name.h"
62#include "stuff/macosx_deployment_target.h"
63
64#include "ld.h"
65#include "pass1.h"
66#include "live_refs.h"
67#include "objects.h"
68#include "fvmlibs.h"
69#include "dylibs.h"
70#include "sections.h"
71#include "symbols.h"
72#include "sets.h"
73#include "layout.h"
74#ifndef KLD
75#include "debugcompunit.h"
76#include "debugline.h"
77#endif /* ! KLD */
78
79#ifndef RLD
80/* TRUE if -search_paths_first was specified */
81__private_extern__ enum bool search_paths_first = FALSE;
82
83/* the user specified directories to search for -lx names, and the number
84   of them */
85__private_extern__ char **search_dirs = NULL;
86__private_extern__ unsigned long nsearch_dirs = 0;
87
88/*
89 * The user specified directories to search via the environment variable
90 * LD_LIBRARY_PATH.
91 */
92__private_extern__ char **ld_library_paths = NULL;
93__private_extern__ unsigned long nld_library_paths = 0;
94
95/* the standard directories to search for -lx names */
96__private_extern__ char *standard_dirs[] = {
97    "/lib/",
98    "/usr/lib/",
99    "/usr/local/lib/",
100    NULL
101};
102
103/*
104 * The user specified directories to search for "-framework Foo" names, and the
105 * number of them.  These are specified with -F options.
106 */
107__private_extern__ char **framework_dirs = NULL;
108__private_extern__ unsigned long nframework_dirs = 0;
109
110/* the standard framework directories to search for "-framework Foo" names */
111__private_extern__ char *standard_framework_dirs[] = {
112#ifdef __OPENSTEP__
113    "/LocalLibrary/Frameworks/",
114    "/NextLibrary/Frameworks/",
115#else /* !defined(__OPENSTEP__) */
116
117#ifdef __GONZO_BUNSEN_BEAKER__
118    "/Local/Library/Frameworks/",
119#else /* !defined(__BUNSEN_BEAKER__) */
120    "/Library/Frameworks/",
121#endif /* __BUNSEN_BEAKER__ */
122
123    "/Network/Library/Frameworks/",
124    "/System/Library/Frameworks/",
125#endif /* __OPENSTEP__ */
126    NULL
127};
128
129/* The pointer to the head of the base object file's segments */
130__private_extern__ struct merged_segment *base_obj_segments = NULL;
131#endif /* !defined(RLD) */
132
133#if !defined(SA_RLD) && !(defined(KLD) && defined(__STATIC__))
134/*
135 * The stat buffer for input files.  This is needed both by pass1() and
136 * pass1_archive() to check the times.
137 */
138static struct stat stat_buf = { 0 };
139
140/*
141 * These are pointers to strings and symbols used to search of the table of
142 * contents of a library.  These have to be can not be local so that
143 * pass1_archive() and search_dylibs() can set them and that ranlib_bsearch()
144 * and dylib_bsearch() can use them.  This is done instead of assigning to
145 * ran_name so that the library can be mapped read only and thus not get dirty
146 * and maybe written to the swap area by the kernel.
147 */
148__private_extern__ char *bsearch_strings = NULL;
149#ifndef RLD
150__private_extern__ struct nlist *bsearch_symbols = NULL;
151
152/*
153 * The list of dynamic libraries to search.  The list of specified libraries
154 * can contain archive libraries when archive libraries appear after dynamic
155 * libraries on the link line.
156 */
157__private_extern__ struct dynamic_library *dynamic_libs = NULL;
158
159/*
160 * When building two-level-namespace, indirect libraries are not kept
161 * in the dynamic_libs list.  The pre-10.4 prebinding may need to grow
162 * the load commands in an executable proportional to the number of
163 * direct and indirect libraries.  The variable indirect_library_ratio
164 * gives us a scaling factor to multiple by the number of libraries
165 * in dynamic_libs as an estimate of the total number of libraries.
166 */
167__private_extern__ unsigned int indirect_library_ratio = 1;
168
169/*
170 * The variable indirect_dylib is used for search_dynamic_libs() to communicate
171 * with check_cur_obj() to prevent the error message that is generated when
172 * a subframework is directly linked against.  When an umbrella framework is
173 * linked against it subframeworks are indirectly used which are not an error.
174 */
175static enum bool indirect_dylib = FALSE;
176
177static void search_for_file(
178    char *base_name,
179    char **file_name,
180    int *fd);
181static void search_for_framework(
182    char *name,
183    char **file_name,
184    int *fd);
185static void search_paths_for_lname(
186    const char *lname_argument,
187    char **file_name,
188    int *fd);
189static void search_path_for_lname(
190    const char *dir,
191    const char *lname_argument,
192    char **file_name,
193    int *fd);
194#endif /* !defined(RLD) */
195
196static void pass1_fat(
197    char *file_name,
198    char *file_addr,
199    unsigned long file_size,
200    enum bool base_name,
201    enum bool dylib_only,
202    enum bool bundle_loader,
203    enum bool force_weak);
204
205static void pass1_archive(
206    char *file_name,
207    char *file_addr,
208    unsigned long file_size,
209    enum bool base_name,
210    enum bool from_fat_file,
211    enum bool bundle_loader,
212    enum bool force_weak);
213
214static enum bool check_archive_arch(
215    char *file_name,
216    char *file_addr,
217    unsigned long file_size);
218
219static enum bool check_extend_format_1(
220    char *name,
221    struct ar_hdr *ar_hdr,
222    unsigned long size_left,
223    unsigned long *member_name_size);
224
225static void pass1_object(
226    char *file_name,
227    char *file_addr,
228    unsigned long file_size,
229    enum bool base_name,
230    enum bool from_fat_file,
231    enum bool dylib_only,
232    enum bool bundle_loader,
233    enum bool force_weak);
234
235#ifndef RLD
236static void load_init_dylib_module(
237    struct dynamic_library *q);
238static enum bool setup_sub_images(
239    struct dynamic_library *p);
240static void check_dylibs_for_definition(
241    struct merged_symbol *merged_symbol,
242    enum bool prebind_check,
243    enum bool twolevel_namespace_check);
244static enum bool check_dylibs_for_reference(
245    struct merged_symbol *merged_symbol);
246
247static enum bool open_dylib(
248    struct dynamic_library *p);
249
250static enum bool set_sub_frameworks_ordinals(
251    struct dynamic_library *umbrella);
252
253static enum bool set_sub_umbrella_sub_library_ordinal(
254    struct dynamic_library *sub);
255
256static void set_isub_image(
257    struct dynamic_library *p,
258    struct dynamic_library *sub);
259
260static int nlist_bsearch(
261    const char *symbol_name,
262    const struct nlist *symbol);
263#endif /* !defined(RLD) */
264
265static int ranlib_bsearch(
266    const char *symbol_name,
267    const struct ranlib *ran);
268
269#endif /* !defined(SA_RLD) && !(defined(KLD) && defined(__STATIC__)) */
270
271static void check_cur_obj(
272    enum bool dylib_only,
273    enum bool bundle_loader);
274
275#ifndef KLD
276static void read_dwarf_info(void);
277#endif
278
279static void check_size_offset(
280    unsigned long size,
281    unsigned long offset,
282    unsigned long align,
283    char *size_str,
284    char *offset_str,
285    unsigned long cmd);
286
287static void check_size_offset_sect(
288    unsigned long size,
289    unsigned long offset,
290    unsigned long align,
291    char *size_str,
292    char *offset_str,
293    unsigned long cmd,
294    unsigned long sect,
295    char *segname,
296    char *sectname);
297
298#ifndef RLD
299static void collect_base_obj_segments(
300	void);
301
302static void add_base_obj_segment(
303	struct segment_command *sg,
304	char *filename);
305
306static char *mkstr(
307	const char *args,
308	...);
309#endif /* !defined(RLD) */
310
311#if !defined(SA_RLD) && !(defined(KLD) && defined(__STATIC__))
312/*
313 * pass1() is called from main() and is passed the name of a file and a flag
314 * indicating if it is a path searched abbrevated file name (a -lx argument).
315 *
316 * If the name is a path searched abbrevated file name (of the form "-lx")
317 * then it is searched for in the search_dirs list (created from the -Ldir
318 * arguments) and then in the list of standard_dirs.  The string "x" of the
319 * "-lx" argument will be converted to "libx.a" if the string does not end in
320 * ".o", in which case it is left alone.
321 *
322 * If the file is the object file for a the base of an incremental load then
323 * base_name is TRUE and the pointer to the object_file structure for it,
324 * base_obj, is set when it is allocated.
325 *
326 * If the file turns out to be just a plain object then merge() is called to
327 * merge its symbolic information and it will be unconditionally loaded.
328 *
329 * Object files in archives are loaded only if they resolve currently undefined
330 * references or the -ObjC flag is set and their are symbols with the ".objc"
331 * prefix defined.
332 */
333__private_extern__
334void
335pass1(
336char *name,
337enum bool lname,
338enum bool base_name,
339enum bool framework_name,
340enum bool bundle_loader,
341enum bool force_weak)
342{
343    int fd;
344    char *file_name;
345#ifndef RLD
346    char *p, *type;
347#endif /* !defined(RLD) */
348    kern_return_t r;
349    unsigned long file_size;
350    char *file_addr;
351    struct fat_header *fat_header;
352#ifdef __MWERKS__
353    enum bool dummy;
354        dummy = lname;
355        dummy = base_name;
356        dummy = framework_name;
357#endif
358
359#ifdef DEBUG
360	/* The compiler "warning: `file_name' may be used uninitialized in */
361	/* this function" can safely be ignored */
362	file_name = NULL;
363#endif /* DEBUG */
364
365	fd = -1;
366#ifndef RLD
367	if(lname){
368	    if(name[0] != '-' || name[1] != 'l')
369		fatal("Internal error: pass1() called with name of: %s and "
370		      "lname == TRUE", name);
371	    p = &name[2];
372	    p = strrchr(p, '.');
373	    if(p != NULL && strcmp(p, ".o") == 0){
374		p = &name[2];
375		search_for_file(p, &file_name, &fd);
376		if(fd == -1)
377		    fatal("can't locate file for: %s", name);
378	    }
379	    else{
380		p = NULL;
381		if(dynamic == TRUE){
382		    if(search_paths_first == TRUE){
383			search_paths_for_lname(&name[2], &file_name, &fd);
384		    }
385		    else{
386			p = mkstr("lib", &name[2], ".dylib", NULL);
387			search_for_file(p, &file_name, &fd);
388			if(fd == -1){
389			    p = mkstr("lib", &name[2], ".a", NULL);
390			    search_for_file(p, &file_name, &fd);
391			}
392		    }
393		}
394		else{
395		    p = mkstr("lib", &name[2], ".a", NULL);
396		    search_for_file(p, &file_name, &fd);
397		}
398		if(fd == -1)
399		    fatal("can't locate file for: %s", name);
400		if(p != NULL)
401		    free(p);
402	    }
403	}
404	else if(framework_name){
405	    type = strrchr(name, ',');
406	    if(type != NULL && type[1] != '\0'){
407		*type = '\0';
408		type++;
409		p = mkstr(name, ".framework/", name, type, NULL);
410		search_for_framework(p, &file_name, &fd);
411		if(fd == -1)
412		    warning("can't locate framework for: -framework %s,%s "
413			    "using suffix %s", name, type, type);
414	    }
415	    else
416		type = NULL;
417	    if(fd == -1){
418		p = mkstr(name, ".framework/", name, NULL);
419		search_for_framework(p, &file_name, &fd);
420	    }
421	    if(fd == -1){
422		if(type != NULL)
423		    fatal("can't locate framework for: -framework %s,%s",
424			  name, type);
425		else
426		    fatal("can't locate framework for: -framework %s", name);
427	    }
428	}
429	else
430#endif /* !defined(RLD) */
431	{
432	    if((fd = open(name, O_RDONLY, 0)) == -1){
433		system_error("can't open: %s", name);
434		return;
435	    }
436	    file_name = name;
437	}
438
439	/*
440	 * Now that the file_name has been determined and opened get it into
441	 * memory by mapping it.
442	 */
443	if(fstat(fd, &stat_buf) == -1){
444	    system_fatal("can't stat file: %s", file_name);
445	    close(fd);
446	    return;
447	}
448	file_size = stat_buf.st_size;
449	/*
450	 * For some reason mapping files with zero size fails so it has to
451	 * be handled specially.
452	 */
453	if(file_size == 0){
454	    error("file: %s is empty (not an object or archive)", file_name);
455	    close(fd);
456	    return;
457	}
458	if((r = map_fd((int)fd, (vm_offset_t)0, (vm_offset_t *)&file_addr,
459	    (boolean_t)TRUE, (vm_size_t)file_size)) != KERN_SUCCESS){
460	    close(fd);
461	    mach_fatal(r, "can't map file: %s", file_name);
462	}
463#ifdef RLD_VM_ALLOC_DEBUG
464	print("rld() map_fd: addr = 0x%0x size = 0x%x\n",
465	      (unsigned int)file_addr, (unsigned int)file_size);
466#endif /* RLD_VM_ALLOC_DEBUG */
467	/*
468	 * The mapped file can't be made read-only because even in the case of
469	 * errors where a wrong bytesex file is attempted to be loaded it must
470	 * be writeable to detect the error.
471	 *
472	 *  if((r = vm_protect(mach_task_self(), (vm_address_t)file_addr,
473	 * 		file_size, FALSE, VM_PROT_READ)) != KERN_SUCCESS){
474	 *      close(fd);
475	 *      mach_fatal(r, "can't make memory for mapped file: %s read-only",
476	 *      	   file_name);
477	 *  }
478	 */
479	close(fd);
480
481	/*
482	 * Determine what type of file it is (fat, archive or thin object file).
483	 */
484	if(sizeof(struct fat_header) > file_size){
485	    error("truncated or malformed file: %s (file size too small to be "
486		  "any kind of object or library)", file_name);
487	    return;
488	}
489	fat_header = (struct fat_header *)file_addr;
490#ifdef __BIG_ENDIAN__
491	if(fat_header->magic == FAT_MAGIC)
492#endif /* __BIG_ENDIAN__ */
493#ifdef __LITTLE_ENDIAN__
494	if(fat_header->magic == SWAP_LONG(FAT_MAGIC))
495#endif /* __LITTLE_ENDIAN__ */
496	{
497#ifdef RLD
498	    new_archive_or_fat(file_name, file_addr, file_size);
499#endif /* RLD */
500	    pass1_fat(file_name, file_addr, file_size, base_name, FALSE,
501		      bundle_loader, force_weak);
502	}
503	else if(file_size >= SARMAG && strncmp(file_addr, ARMAG, SARMAG) == 0){
504	    pass1_archive(file_name, file_addr, file_size, base_name, FALSE,
505			  bundle_loader, force_weak);
506	}
507	else{
508	    pass1_object(file_name, file_addr, file_size, base_name, FALSE,
509			 FALSE, bundle_loader, force_weak);
510	}
511#ifdef VM_SYNC_DEACTIVATE
512	vm_msync(mach_task_self(), (vm_address_t)file_addr,
513		 (vm_size_t)file_size, VM_SYNC_DEACTIVATE);
514#endif /* VM_SYNC_DEACTIVATE */
515}
516
517#ifndef RLD
518/*
519 * search_for_file() takes base_name and trys to open a file with that base name
520 * in the -L search directories and in the standard directories.  If it is
521 * sucessful it returns a pointer to the file name indirectly through file_name
522 * and the open file descriptor indirectly through fd.
523 */
524static
525void
526search_for_file(
527char *base_name,
528char **file_name,
529int *fd)
530{
531    unsigned long i;
532
533	*fd = -1;
534	for(i = 0; i < nsearch_dirs ; i++){
535	    *file_name = mkstr(search_dirs[i], "/", base_name, NULL);
536	    if((*fd = open(*file_name, O_RDONLY, 0)) != -1)
537		break;
538	    free(*file_name);
539	}
540	if(*fd == -1){
541	    for(i = 0; i < nld_library_paths ; i++){
542		*file_name = mkstr(ld_library_paths[i], "/", base_name, NULL);
543		if((*fd = open(*file_name, O_RDONLY, 0)) != -1)
544		    break;
545		free(*file_name);
546	    }
547	}
548	if(*fd == -1){
549	    for(i = 0; standard_dirs[i] != NULL ; i++){
550		*file_name = mkstr(standard_dirs[i], base_name, NULL);
551		if((*fd = open(*file_name, O_RDONLY, 0)) != -1)
552		    break;
553		free(*file_name);
554	    }
555	}
556}
557
558/*
559 * search_for_framework() takes name and trys to open a file with that name
560 * in the -F search directories and in the standard framework directories.  If
561 * it is sucessful it returns a pointer to the file name indirectly through
562 * file_name and the open file descriptor indirectly through fd.
563 */
564static
565void
566search_for_framework(
567char *name,
568char **file_name,
569int *fd)
570{
571    unsigned long i;
572
573	*fd = -1;
574	for(i = 0; i < nframework_dirs ; i++){
575	    *file_name = mkstr(framework_dirs[i], "/", name, NULL);
576	    if((*fd = open(*file_name, O_RDONLY, 0)) != -1)
577		break;
578	    free(*file_name);
579	}
580	if(*fd == -1){
581	    for(i = 0; standard_framework_dirs[i] != NULL ; i++){
582		*file_name = mkstr(standard_framework_dirs[i], name, NULL);
583		if((*fd = open(*file_name, O_RDONLY, 0)) != -1)
584		    break;
585		free(*file_name);
586	    }
587	}
588}
589
590/*
591 * search_paths_for_lname() takes the argument to a -lx option and and trys to
592 * open a file with the name libx.dylib or libx.a.  This routine is only used
593 * when the -search_paths_first option is specified and -dynamic is in effect.
594 * And looks for a file name ending in .dylib then .a in each directory before
595 * looking in the next directory.  The list of the -L search directories and in
596 * the standard directories are searched in that order.  If this is sucessful
597 * it returns a pointer to the file name indirectly through file_name and the
598 * open file descriptor indirectly through fd.
599 */
600static
601void
602search_paths_for_lname(
603const char *lname_argument,
604char **file_name,
605int *fd)
606{
607    unsigned long i;
608
609	*fd = -1;
610	for(i = 0; i < nsearch_dirs ; i++){
611	    search_path_for_lname(search_dirs[i], lname_argument, file_name,fd);
612	    if(*fd != -1)
613		return;
614	}
615	for(i = 0; i < nld_library_paths ; i++){
616	    search_path_for_lname(ld_library_paths[i], lname_argument,
617				  file_name, fd);
618	    if(*fd != -1)
619		return;
620	}
621	for(i = 0; standard_dirs[i] != NULL ; i++){
622	    search_path_for_lname(standard_dirs[i],lname_argument,file_name,fd);
623	    if(*fd != -1)
624		return;
625	}
626}
627
628/*
629 * search_path_for_lname() takes the argument to a -lx option and and trys to
630 * open a file with the name libx.dylib then libx.a in the specified directory
631 * name.  This routine is only used when the -search_paths_first option is
632 * specified and -dynamic is in effect.  If this is sucessful it returns a
633 * pointer to the file name indirectly through file_name and the open file
634 * descriptor indirectly through fd.
635 */
636static
637void
638search_path_for_lname(
639const char *dir,
640const char *lname_argument,
641char **file_name,
642int *fd)
643{
644	*file_name = mkstr(dir, "/", "lib", lname_argument, ".dylib", NULL);
645	if((*fd = open(*file_name, O_RDONLY)) != -1)
646	    return;
647	free(*file_name);
648
649	*file_name = mkstr(dir, "/", "lib", lname_argument, ".a", NULL);
650	if((*fd = open(*file_name, O_RDONLY)) != -1)
651	    return;
652	free(*file_name);
653}
654#endif /* !defined(RLD) */
655
656/*
657 * pass1_fat() is passed a fat file to process.  The reason the swapping of
658 * the fat headers is not done in place is so that when running native on a
659 * little endian machine and the output is also little endian we don't want
660 * cause the memory for the input files to be written just because of the
661 * fat headers.
662 */
663static
664void
665pass1_fat(
666char *file_name,
667char *file_addr,
668unsigned long file_size,
669enum bool base_name,
670enum bool dylib_only,
671enum bool bundle_loader,
672enum bool force_weak)
673{
674    struct fat_header *fat_header;
675#ifdef __LITTLE_ENDIAN__
676    struct fat_header struct_fat_header;
677#endif /* __LITTLE_ENDIAN__ */
678    struct fat_arch *fat_archs, *best_fat_arch;
679    unsigned long previous_errors;
680    char *arch_addr;
681    unsigned long arch_size;
682#if !(defined(KLD) && defined(__STATIC__))
683    struct arch_flag host_arch_flag;
684#endif /* !(defined(KLD) && defined(__STATIC__)) */
685    const char *prev_arch;
686
687	fat_header = (struct fat_header *)file_addr;
688#ifdef __LITTLE_ENDIAN__
689	struct_fat_header = *fat_header;
690	swap_fat_header(&struct_fat_header, host_byte_sex);
691	fat_header = &struct_fat_header;
692#endif /* __LITTLE_ENDIAN__ */
693
694	if(sizeof(struct fat_header) + fat_header->nfat_arch *
695	   sizeof(struct fat_arch) > file_size){
696	    error("fat file: %s truncated or malformed (fat_arch structs "
697		  "would extend past the end of the file)", file_name);
698	    return;
699	}
700
701#ifdef __BIG_ENDIAN__
702	fat_archs = (struct fat_arch *)(file_addr + sizeof(struct fat_header));
703#endif /* __BIG_ENDIAN__ */
704#ifdef __LITTLE_ENDIAN__
705	fat_archs = allocate(fat_header->nfat_arch * sizeof(struct fat_arch));
706	memcpy(fat_archs, file_addr + sizeof(struct fat_header),
707	       fat_header->nfat_arch * sizeof(struct fat_arch));
708	swap_fat_arch(fat_archs, fat_header->nfat_arch, host_byte_sex);
709#endif /* __LITTLE_ENDIAN__ */
710
711	/*
712	 * save the previous errors and only return out of here if something
713	 * we do in here gets an error.
714	 */
715	previous_errors = errors;
716	errors = 0;
717
718	/* check the fat file */
719	check_fat(file_name, file_size, fat_header, fat_archs, NULL, 0);
720	if(errors)
721	    goto pass1_fat_return;
722
723	/* Now select an architecture out of the fat file to use if any */
724
725	/*
726	 * If the output file's cputype has been set then load the best fat_arch
727	 * from it else it's an error.
728	 */
729	if(arch_flag.cputype != 0){
730	    best_fat_arch = cpusubtype_findbestarch(
731					arch_flag.cputype, arch_flag.cpusubtype,
732					fat_archs, fat_header->nfat_arch);
733	    if(best_fat_arch == NULL){
734		if(no_arch_warnings == TRUE)
735		    goto pass1_fat_return;
736		if(arch_flag.name != NULL){
737		    if(arch_errors_fatal == TRUE){
738			error("fat file: %s does not contain an architecture "
739			      "that matches the specified -arch flag: %s ",
740			      file_name, arch_flag.name);
741		    }
742		    else
743			warning("fat file: %s does not contain an architecture "
744				"that matches the specified -arch flag: %s "
745				"(file ignored)", file_name, arch_flag.name);
746		}
747		else{
748		    prev_arch = get_arch_name_from_types(arch_flag.cputype,
749						         arch_flag.cpusubtype);
750		    if(arch_errors_fatal == TRUE){
751			error("fat file: %s does not contain an architecture "
752			    "that matches the objects files (architecture %s) "
753			    "previously loaded", file_name, prev_arch);
754		    }
755		    else
756			warning("fat file: %s does not contain an architecture "
757			    "that matches the objects files (architecture %s) "
758			    "previously loaded (file ignored)", file_name,
759			    prev_arch);
760		}
761		goto pass1_fat_return;
762	    }
763	    arch_addr = file_addr + best_fat_arch->offset;
764	    arch_size = best_fat_arch->size;
765	    if(arch_size >= SARMAG &&
766	       strncmp(arch_addr, ARMAG, SARMAG) == 0){
767		if(dylib_only == TRUE){
768		    if(arch_flag.name != NULL){
769			error("fat file: %s (for architecture %s) is not a "
770			      "dynamic shared library", file_name,
771			      arch_flag.name);
772		    }
773		    else{
774			prev_arch = get_arch_name_from_types(arch_flag.cputype,
775							 arch_flag.cpusubtype);
776			error("fat file: %s (for architecture %s) is not a "
777			      "dynamic shared library", file_name, prev_arch);
778		    }
779		    goto pass1_fat_return;
780		}
781		pass1_archive(file_name, arch_addr, arch_size,
782			      base_name, TRUE, bundle_loader, force_weak);
783	    }
784	    else{
785		pass1_object(file_name, arch_addr, arch_size, base_name, TRUE,
786			     dylib_only, bundle_loader, force_weak);
787	    }
788	    goto pass1_fat_return;
789	}
790
791#if !(defined(KLD) && defined(__STATIC__))
792	/*
793	 * If the output file's cputype has not been set so if this fat file
794	 * has exactly one type in it then load that type.
795	 */
796	if(fat_header->nfat_arch == 1){
797	    arch_addr = file_addr + fat_archs[0].offset;
798	    arch_size = fat_archs[0].size;
799	    if(arch_size >= SARMAG &&
800	       strncmp(arch_addr, ARMAG, SARMAG) == 0){
801		if(dylib_only == TRUE){
802		    error("fat file: %s (for architecture %s) is not a dynamic "
803			  "shared library", file_name, get_arch_name_from_types(
804			   fat_archs[0].cputype, fat_archs[0].cpusubtype));
805		    goto pass1_fat_return;
806		}
807		pass1_archive(file_name, arch_addr, arch_size, base_name, TRUE,
808			      bundle_loader, force_weak);
809	    }
810	    else{
811		pass1_object(file_name, arch_addr, arch_size, base_name, TRUE,
812			     dylib_only, bundle_loader, force_weak);
813	    }
814	    goto pass1_fat_return;
815	}
816
817	/*
818	 * The output file's cputype has not been set and if this fat file has
819	 * a best arch for the host's specific architecture type then load that
820	 * type and set the output file's cputype to that.
821	 */
822	if(get_arch_from_host(NULL, &host_arch_flag) == 0)
823	    fatal("can't determine the host architecture (specify an "
824		  "-arch flag or fix get_arch_from_host() )");
825	best_fat_arch = cpusubtype_findbestarch(
826			    host_arch_flag.cputype, host_arch_flag.cpusubtype,
827			    fat_archs, fat_header->nfat_arch);
828	if(best_fat_arch != NULL){
829	    arch_addr = file_addr + best_fat_arch->offset;
830	    arch_size = best_fat_arch->size;
831	    if(arch_size >= SARMAG &&
832	       strncmp(arch_addr, ARMAG, SARMAG) == 0){
833		if(dylib_only == TRUE){
834		    error("fat file: %s (for architecture %s) is not a dynamic "
835			  "shared library", file_name, get_arch_name_from_types(
836			   best_fat_arch->cputype, best_fat_arch->cpusubtype));
837		    goto pass1_fat_return;
838		}
839		pass1_archive(file_name, arch_addr, arch_size,
840			      base_name, TRUE, bundle_loader, force_weak);
841	    }
842	    else{
843		pass1_object(file_name, arch_addr, arch_size, base_name, TRUE,
844			     dylib_only, bundle_loader, force_weak);
845	    }
846	    goto pass1_fat_return;
847	}
848
849	/*
850	 * The output file's cputype has not been set and this fat file does not
851	 * have only one architecture or has the host's family architecture so
852	 * we are stuck not knowing what to load if anything from it.
853	 */
854	fatal("-arch flag must be specified (fat file: %s does not contain the "
855	      "host architecture or just one architecture)", file_name);
856#endif /* !(defined(KLD) && defined(__STATIC__)) */
857
858pass1_fat_return:
859	errors += previous_errors;
860#ifdef __LITTLE_ENDIAN__
861	free(fat_archs);
862#endif /* __LITTLE_ENDIAN__ */
863	return;
864}
865
866__private_extern__
867void
868check_fat(
869char *file_name,
870unsigned long file_size,
871struct fat_header *fat_header,
872struct fat_arch *fat_archs,
873char *ar_name,
874unsigned long ar_name_size)
875{
876    unsigned long i, j;
877
878	if(fat_header->nfat_arch == 0){
879	    if(ar_name != NULL)
880		error("fat file: %s(%.*s) malformed (contains zero "
881		      "architecture types)", file_name, (int)ar_name_size,
882		      ar_name);
883	    else
884		error("fat file: %s malformed (contains zero architecture "
885		      "types)", file_name);
886	    return;
887	}
888	for(i = 0; i < fat_header->nfat_arch; i++){
889	    if(fat_archs[i].offset + fat_archs[i].size > file_size){
890		if(ar_name != NULL)
891		    error("fat file: %s(%.*s) truncated or malformed (offset "
892			  "plus size of cputype (%d) cpusubtype (%d) extends "
893			  "past the end of the file)", file_name,
894			  (int)ar_name_size, ar_name, fat_archs[i].cputype,
895			  fat_archs[i].cpusubtype);
896		else
897		    error("fat file: %s truncated or malformed (offset plus "
898			  "size of cputype (%d) cpusubtype (%d) extends past "
899			  "the end of the file)", file_name,
900			  fat_archs[i].cputype, fat_archs[i].cpusubtype);
901		return;
902	    }
903	    if(fat_archs[i].cputype == 0){
904		if(ar_name != NULL)
905		    error("fat file: %s(%.*s) fat_archs %lu cputype is zero (a "
906			  "reserved value)", file_name, (int)ar_name_size,
907			  ar_name, i);
908		else
909		    error("fat file: %s fat_archs %lu cputype is zero (a "
910			  "reserved value)", file_name, i);
911		return;
912	    }
913	    if(fat_archs[i].align > MAXSECTALIGN){
914		if(ar_name != NULL)
915		    error("fat file: %s(%.*s) align (2^%u) too large for "
916			  "cputype (%d) cpusubtype (%d) (maximum 2^%d)",
917			  file_name, (int)ar_name_size, ar_name,
918			  fat_archs[i].align, fat_archs[i].cputype,
919			  fat_archs[i].cpusubtype, MAXSECTALIGN);
920		else
921		    error("fat file: %s align (2^%u) too large for cputype "
922			  "(%d) cpusubtype (%d) (maximum 2^%d)", file_name,
923			  fat_archs[i].align, fat_archs[i].cputype,
924			  fat_archs[i].cpusubtype, MAXSECTALIGN);
925		return;
926	    }
927	    if(fat_archs[i].offset %
928	       (1 << fat_archs[i].align) != 0){
929		if(ar_name != NULL)
930		    error("fat file: %s(%.*s) offset: %u for cputype (%d) "
931			  "cpusubtype (%d)) not aligned on it's alignment "
932			  "(2^%u)", file_name, (int)ar_name_size, ar_name,
933			  fat_archs[i].offset, fat_archs[i].cputype,
934			  fat_archs[i].cpusubtype, fat_archs[i].align);
935		else
936		    error("fat file: %s offset: %u for cputype (%d) "
937			  "cpusubtype (%d)) not aligned on it's alignment "
938			  "(2^%u)", file_name, fat_archs[i].offset,
939			  fat_archs[i].cputype, fat_archs[i].cpusubtype,
940			  fat_archs[i].align);
941		return;
942	    }
943	}
944	for(i = 0; i < fat_header->nfat_arch; i++){
945	    for(j = i + 1; j < fat_header->nfat_arch; j++){
946		if(fat_archs[i].cputype == fat_archs[j].cputype &&
947		   fat_archs[i].cpusubtype == fat_archs[j].cpusubtype){
948		    if(ar_name != NULL)
949			error("fat file: %s(%.*s) contains two of the same "
950			      "architecture (cputype (%d) cpusubtype (%d))",
951			      file_name, (int)ar_name_size, ar_name,
952			      fat_archs[i].cputype, fat_archs[i].cpusubtype);
953		    else
954			error("fat file: %s contains two of the same "
955			      "architecture (cputype (%d) cpusubtype (%d))",
956			      file_name, fat_archs[i].cputype,
957			      fat_archs[i].cpusubtype);
958		    return;
959		}
960	    }
961	}
962	return;
963}
964
965/*
966 * This is an archive so conditionally load those objects that defined
967 * currently undefined symbols and process archives with respect to the
968 * -ObjC and -load_all flags if set.
969 */
970static
971void
972pass1_archive(
973char *file_name,
974char *file_addr,
975unsigned long file_size,
976enum bool base_name,
977enum bool from_fat_file,
978enum bool bundle_loader,
979enum bool force_weak)
980{
981    unsigned long i, j, offset;
982#ifndef RLD
983    unsigned long *loaded_offsets, nloaded_offsets;
984    enum bool loaded_offset;
985    struct ar_hdr *ar_hdr;
986    unsigned long length;
987    struct dynamic_library *p;
988#endif /* !defined(RLD) */
989    struct ar_hdr *symdef_ar_hdr;
990    char *symdef_ar_name, *ar_name;
991    unsigned long symdef_length, nranlibs, string_size, ar_name_size;
992    struct ranlib *ranlibs, *ranlib;
993    struct undefined_list *undefined;
994    struct merged_symbol *merged_symbol;
995    enum bool member_loaded;
996    enum byte_sex toc_byte_sex;
997    enum bool ld_trace_archive_printed;
998
999#ifndef RLD
1000    unsigned long ar_size;
1001    struct fat_header *fat_header;
1002#ifdef __LITTLE_ENDIAN__
1003    struct fat_header struct_fat_header;
1004#endif /* __LITTLE_ENDIAN__ */
1005    struct fat_arch *fat_archs, *best_fat_arch;
1006    char *arch_addr;
1007    unsigned long arch_size;
1008    struct arch_flag host_arch_flag;
1009    const char *prev_arch;
1010
1011	arch_addr = NULL;
1012	arch_size = 0;
1013#endif /* !defined(RLD) */
1014#ifdef __MWERKS__
1015	{
1016	    enum bool dummy;
1017		dummy = base_name;
1018		dummy = from_fat_file;
1019	}
1020#endif
1021
1022	ld_trace_archive_printed = FALSE;
1023	if(check_archive_arch(file_name, file_addr, file_size) == FALSE)
1024	    return;
1025
1026	offset = SARMAG;
1027#ifndef RLD
1028	if(base_name)
1029	    fatal("base file of incremental link (argument of -A): %s should't "
1030		  "be an archive", file_name);
1031	if(bundle_loader)
1032	    fatal("-bundle_loader argument: %s should't be an archive",
1033		  file_name);
1034
1035	/*
1036	 * If the flag to specifiy that all the archive members are to be
1037	 * loaded then load them all.
1038	 */
1039	if(archive_all == TRUE){
1040	    if(offset + sizeof(struct ar_hdr) > file_size){
1041		error("truncated or malformed archive: %s (archive header of "
1042		      "first member extends past the end of the file, can't "
1043		      "load from it)", file_name);
1044		return;
1045	    }
1046	    symdef_ar_hdr = (struct ar_hdr *)(file_addr + offset);
1047	    if(strncmp(symdef_ar_hdr->ar_name, AR_EFMT1,
1048		       sizeof(AR_EFMT1)-1) == 0)
1049		ar_name = file_addr + offset + sizeof(struct ar_hdr);
1050	    else
1051		ar_name = symdef_ar_hdr->ar_name;
1052	    if(strncmp(ar_name, SYMDEF, sizeof(SYMDEF)-1) == 0){
1053		offset += sizeof(struct ar_hdr);
1054		symdef_length = strtol(symdef_ar_hdr->ar_size, NULL, 10);
1055		if(offset + symdef_length > file_size){
1056		    error("truncated or malformed archive: %s (table of "
1057			  "contents extends past the end of the file, can't "
1058			  "load from it)", file_name);
1059		    return;
1060		}
1061		offset += rnd(symdef_length, sizeof(short));
1062	    }
1063	    if(ld_trace_archives == TRUE && ld_trace_archive_printed == FALSE){
1064		char resolvedname[MAXPATHLEN];
1065		if(realpath(file_name, resolvedname) !=
1066		   NULL)
1067		    ld_trace("[Logging for XBS] Used static "
1068			     "archive: %s\n", resolvedname);
1069		else
1070		    ld_trace("[Logging for XBS] Used static "
1071			     "archive: %s\n", file_name);
1072		ld_trace_archive_printed = TRUE;
1073	    }
1074	    while(offset < file_size){
1075		if(offset + sizeof(struct ar_hdr) > file_size){
1076		    error("truncated or malformed archive: %s at offset %lu "
1077			  "(archive header of next member extends past the end "
1078			  "of the file, can't load from it)", file_name,offset);
1079		    return;
1080		}
1081		ar_hdr = (struct ar_hdr *)(file_addr + offset);
1082		if(strncmp(ar_hdr->ar_name, AR_EFMT1, sizeof(AR_EFMT1)-1) == 0){
1083		    ar_name = file_addr + offset + sizeof(struct ar_hdr);
1084		    ar_name_size = strtoul(ar_hdr->ar_name +
1085					   sizeof(AR_EFMT1) - 1, NULL, 10);
1086		    i = ar_name_size;
1087		}
1088		else{
1089		    ar_name = ar_hdr->ar_name;
1090		    ar_name_size = 0;
1091		    i = size_ar_name(ar_hdr);
1092		}
1093		offset += sizeof(struct ar_hdr) + ar_name_size;
1094		ar_size = strtol(ar_hdr->ar_size, NULL, 10) - ar_name_size;
1095		if(offset + ar_size > file_size){
1096		    error("truncated or malformed archive: %s (member %.*s "
1097			  "extends past the end of the file, can't load from "
1098			  "it)", file_name, (int)i, ar_name);
1099		    return;
1100		}
1101		/*
1102		 * For -all_load we allow fat files as archive members, so if
1103		 * this is a fat file load the right architecture.
1104		 */
1105		fat_header = (struct fat_header *)(file_addr + offset);
1106		if(ar_size >= sizeof(struct fat_header) &&
1107#ifdef __BIG_ENDIAN__
1108		   fat_header->magic == FAT_MAGIC)
1109#endif
1110#ifdef __LITTLE_ENDIAN__
1111		   fat_header->magic == SWAP_LONG(FAT_MAGIC))
1112#endif
1113		{
1114#ifdef __LITTLE_ENDIAN__
1115		    struct_fat_header = *fat_header;
1116		    swap_fat_header(&struct_fat_header, host_byte_sex);
1117		    fat_header = &struct_fat_header;
1118#endif
1119		    if(sizeof(struct fat_header) + fat_header->nfat_arch *
1120		       sizeof(struct fat_arch) > ar_size){
1121			error("fat file: %s(%.*s) truncated or malformed "
1122			    "(fat_arch structs would extend past the end of "
1123			    "the file)", file_name, (int)i, ar_name);
1124			return;
1125		    }
1126#ifdef __BIG_ENDIAN__
1127		    fat_archs = (struct fat_arch *)(file_addr + offset +
1128				sizeof(struct fat_header));
1129#endif
1130#ifdef __LITTLE_ENDIAN__
1131		    fat_archs = allocate(fat_header->nfat_arch *
1132					 sizeof(struct fat_arch));
1133		    memcpy(fat_archs, file_addr + offset +
1134				      sizeof(struct fat_header),
1135			   fat_header->nfat_arch * sizeof(struct fat_arch));
1136		    swap_fat_arch(fat_archs, fat_header->nfat_arch,
1137				  host_byte_sex);
1138#endif
1139		    /* check the fat file */
1140		    check_fat(file_name, ar_size, fat_header, fat_archs,
1141			      ar_name, i);
1142		    if(errors)
1143			return;
1144
1145		    /* Now select an architecture out of the fat file to use */
1146
1147		    /*
1148		     * If the output file's cputype has been set then load the
1149		     * best fat_arch from it else it's an error.
1150		     */
1151		    if(arch_flag.cputype != 0){
1152			best_fat_arch = cpusubtype_findbestarch(
1153					arch_flag.cputype, arch_flag.cpusubtype,
1154					fat_archs, fat_header->nfat_arch);
1155			if(best_fat_arch == NULL){
1156			    if(no_arch_warnings == TRUE)
1157				return;
1158			    if(arch_flag.name != NULL){
1159				if(arch_errors_fatal == TRUE){
1160				    error("fat file: %s(%.*s) does not contain "
1161					"an architecture that matches the "
1162					"specified -arch flag: %s", file_name,
1163					(int)i, ar_name, arch_flag.name);
1164				}
1165				else
1166				    warning("fat file: %s(%.*s) does not "
1167					"contain an architecture that matches "
1168					"the specified -arch flag: %s (file "
1169					"ignored)", file_name, (int)i,
1170					ar_name, arch_flag.name);
1171			    }
1172			    else{
1173				prev_arch = get_arch_name_from_types(
1174				    arch_flag.cputype, arch_flag.cpusubtype);
1175				if(arch_errors_fatal == TRUE){
1176				    error("fat file: %s(%.*s) does not contain "
1177					"an architecture that matches the "
1178					"objects files (architecture %s) "
1179					"previously loaded", file_name,
1180					(int)i, ar_name, prev_arch);
1181				}
1182				else
1183				    warning("fat file: %s(%.*s) does not "
1184					"contain an architecture that matches "
1185					"the objects files (architecture %s) "
1186					"previously loaded (file ignored)",
1187					file_name, (int)i, ar_name, prev_arch);
1188			    }
1189			    return;
1190			}
1191			arch_addr = file_addr + offset + best_fat_arch->offset;
1192			arch_size = best_fat_arch->size;
1193		    }
1194		    /*
1195		     * The output file's cputype has not been set so if this
1196		     * fat file has exactly one type in it then load that type.
1197		     */
1198		    else if(fat_header->nfat_arch == 1){
1199			arch_addr = file_addr + offset + fat_archs[0].offset;
1200			arch_size = fat_archs[0].size;
1201		    }
1202		    /*
1203		     * The output file's cputype has not been set and if this
1204		     * fat file has a best arch for the host's specific
1205		     * architecture type then load that type and set the output
1206		     * file's cputype to that.
1207		     */
1208		    else{
1209			if(get_arch_from_host(NULL, &host_arch_flag) == 0)
1210			    fatal("can't determine the host architecture "
1211				"(specify an -arch flag or fix "
1212				"get_arch_from_host() )");
1213			best_fat_arch = cpusubtype_findbestarch(
1214			    host_arch_flag.cputype, host_arch_flag.cpusubtype,
1215			    fat_archs, fat_header->nfat_arch);
1216			if(best_fat_arch != NULL){
1217			    arch_addr = file_addr + offset +
1218					best_fat_arch->offset;
1219			    arch_size = best_fat_arch->size;
1220			}
1221			/*
1222			 * The output file's cputype has not been set and this
1223			 * fat file does not have only one architecture or has
1224			 * the host's family architecture so we are stuck not
1225			 * knowing what to load if anything from it.
1226			 */
1227			else
1228			    fatal("-arch flag must be specified (fat file: "
1229				"%s(%.*s) does not contain the host "
1230				"architecture or just one architecture)",
1231				file_name, (int)i, ar_name);
1232		    }
1233		    cur_obj = new_object_file();
1234		    cur_obj->file_name = file_name;
1235		    cur_obj->obj_addr = arch_addr;
1236		    cur_obj->obj_size = arch_size;
1237		    cur_obj->ar_hdr = ar_hdr;
1238		    cur_obj->ar_name = ar_name;
1239		    cur_obj->ar_name_size = i;
1240#ifdef __LITTLE_ENDIAN__
1241		    free(fat_archs);
1242#endif
1243		    goto down;
1244		}
1245		cur_obj = new_object_file();
1246		cur_obj->file_name = file_name;
1247		cur_obj->obj_addr = file_addr + offset;
1248		cur_obj->ar_hdr = ar_hdr;
1249		cur_obj->ar_name = ar_name;
1250		cur_obj->ar_name_size = i;
1251		cur_obj->obj_size = ar_size;
1252down:
1253		if(whyload){
1254		    print_obj_name(cur_obj);
1255		    print("loaded because of -all_load flag\n");
1256		}
1257		merge(FALSE, FALSE, force_weak);
1258		length = rnd(ar_size + ar_name_size, sizeof(short));
1259		offset = (offset - ar_name_size) + length;
1260	    }
1261	    return;
1262	}
1263#endif /* !defined(RLD) */
1264
1265	/*
1266	 * If there are no undefined symbols then the archive doesn't have
1267	 * to be searched because archive members are only loaded to resolve
1268	 * undefined references unless the -ObjC flag is set.
1269	 */
1270	if(undefined_list.next == &undefined_list && archive_ObjC == FALSE)
1271	    return;
1272
1273#ifdef RLD
1274	if(from_fat_file == FALSE)
1275	    new_archive_or_fat(file_name, file_addr, file_size);
1276#endif /* RLD */
1277	/*
1278	 * The file is an archive so get the symdef file
1279	 */
1280	if(offset == file_size){
1281	    warning("empty archive: %s (can't load from it)", file_name);
1282	    return;
1283	}
1284	if(offset + sizeof(struct ar_hdr) > file_size){
1285	    error("truncated or malformed archive: %s (archive header of first "
1286		  "member extends past the end of the file, can't load from "
1287		  " it)", file_name);
1288	    return;
1289	}
1290	symdef_ar_hdr = (struct ar_hdr *)(file_addr + offset);
1291	if(strncmp(symdef_ar_hdr->ar_name, AR_EFMT1, sizeof(AR_EFMT1)-1) == 0){
1292	    symdef_ar_name = file_addr + offset + sizeof(struct ar_hdr);
1293	    ar_name_size = strtoul(symdef_ar_hdr->ar_name +
1294				   sizeof(AR_EFMT1) - 1, NULL, 10);
1295	}
1296	else{
1297	    symdef_ar_name = symdef_ar_hdr->ar_name;
1298	    ar_name_size = 0;
1299	}
1300	offset += sizeof(struct ar_hdr) + ar_name_size;
1301	if(strncmp(symdef_ar_name, SYMDEF, sizeof(SYMDEF) - 1) != 0){
1302	    error("archive: %s has no table of contents, add one with "
1303		  "ranlib(1) (can't load from it)", file_name);
1304	    return;
1305	}
1306	symdef_length = strtol(symdef_ar_hdr->ar_size, NULL, 10) - ar_name_size;
1307	/*
1308	 * The contents of a __.SYMDEF file is begins with a word giving the
1309	 * size in bytes of ranlib structures which immediately follow, and
1310	 * then continues with a string table consisting of a word giving the
1311	 * number of bytes of strings which follow and then the strings
1312	 * themselves.  So the smallest valid size is two words long.
1313	 */
1314	if(symdef_length < 2 * sizeof(long)){
1315	    error("size of table of contents for archive: %s too small to be "
1316		  "a valid table of contents (can't load from it)", file_name);
1317	    return;
1318	}
1319	if(offset + symdef_length > file_size){
1320	    error("truncated or malformed archive: %s (table of contents "
1321		  "extends past the end of the file, can't load from it)",
1322		  file_name);
1323	    return;
1324	}
1325	toc_byte_sex = get_toc_byte_sex(file_addr, file_size);
1326	nranlibs = *((long *)(file_addr + offset));
1327	if(toc_byte_sex != host_byte_sex)
1328	    nranlibs = SWAP_LONG(nranlibs);
1329	nranlibs = nranlibs / sizeof(struct ranlib);
1330	offset += sizeof(long);
1331	ranlibs = (struct ranlib *)(file_addr + offset);
1332	offset += sizeof(struct ranlib) * nranlibs;
1333	if(nranlibs == 0){
1334	    warning("empty table of contents: %s (can't load from it)",
1335		    file_name);
1336	    return;
1337	}
1338	if(offset - (2 * sizeof(long) + ar_name_size + sizeof(struct ar_hdr) +
1339		     SARMAG) > symdef_length){
1340	    error("truncated or malformed archive: %s (ranlib structures in "
1341		  "table of contents extends past the end of the table of "
1342		  "contents, can't load from it)", file_name);
1343	    return;
1344	}
1345	string_size = *((long *)(file_addr + offset));
1346	if(toc_byte_sex != host_byte_sex)
1347	    string_size = SWAP_LONG(string_size);
1348	offset += sizeof(long);
1349	bsearch_strings = file_addr + offset;
1350	offset += string_size;
1351	if(offset - (2 * sizeof(long) + ar_name_size + sizeof(struct ar_hdr) +
1352		     SARMAG) > symdef_length){
1353	    error("truncated or malformed archive: %s (ranlib strings in "
1354		  "table of contents extends past the end of the table of "
1355		  "contents, can't load from it)", file_name);
1356	    return;
1357	}
1358	if(symdef_length == 2 * sizeof(long)){
1359	    warning("empty table of contents for archive: %s (can't load from "
1360		    "it)", file_name);
1361	    return;
1362	}
1363
1364	/*
1365	 * Check the string offset and the member offsets of the ranlib structs.
1366	 */
1367	if(toc_byte_sex != host_byte_sex)
1368	    swap_ranlib(ranlibs, nranlibs, host_byte_sex);
1369	for(i = 0; i < nranlibs; i++){
1370	    if(ranlibs[i].ran_un.ran_strx >= string_size){
1371		error("malformed table of contents in: %s (ranlib struct %lu "
1372		      "has bad string index, can't load from it)", file_name,i);
1373		return;
1374	    }
1375	    if(ranlibs[i].ran_off + sizeof(struct ar_hdr) >= file_size){
1376		error("malformed table of contents in: %s (ranlib struct %lu "
1377		      "has bad library member offset, can't load from it)",
1378		      file_name, i);
1379		return;
1380	    }
1381	    /*
1382	     * These should be on 4 byte boundaries because the maximum
1383	     * alignment of the header structures and relocation are 4 bytes.
1384	     * But this is has to be 2 bytes because that's the way ar(1) has
1385	     * worked historicly in the past.  Fortunately this works on the
1386	     * 68k machines but will have to change when this is on a real
1387	     * machine.
1388	     */
1389#if defined(mc68000) || defined(__i386__)
1390	    if(ranlibs[i].ran_off % sizeof(short) != 0){
1391		error("malformed table of contents in: %s (ranlib struct %lu "
1392		      "library member offset not a multiple of %lu bytes, can't"
1393		      " load from it)", file_name, i, sizeof(short));
1394		return;
1395	    }
1396#else
1397	    if(ranlibs[i].ran_off % sizeof(long) != 0){
1398		error("malformed table of contents in: %s (ranlib struct %lu "
1399		      "library member offset not a multiple of %lu bytes, can't"
1400		      " load from it)", file_name, i, sizeof(long));
1401		return;
1402	    }
1403#endif
1404	}
1405
1406#ifndef RLD
1407	/*
1408	 * If the objective-C flag is set then load every thing in this archive
1409	 * that defines a symbol that starts with ".objc_class_name" or
1410	 * ".objc_category_name".
1411 	 */
1412	if(archive_ObjC == TRUE){
1413	    loaded_offsets = allocate(nranlibs * sizeof(unsigned long));
1414	    nloaded_offsets = 0;
1415	    for(i = 0; i < nranlibs; i++){
1416		/* See if this symbol is an objective-C symbol */
1417		if(strncmp(bsearch_strings + ranlibs[i].ran_un.ran_strx,
1418		           ".objc_class_name",
1419			   sizeof(".objc_class_name") - 1) != 0 &&
1420		   strncmp(bsearch_strings + ranlibs[i].ran_un.ran_strx,
1421		           ".objc_category_name",
1422			   sizeof(".objc_category_name") - 1) != 0)
1423		    continue;
1424
1425		/* See if the object at this offset has already been loaded */
1426		loaded_offset = FALSE;
1427		for(j = 0; j < nloaded_offsets; j++){
1428		    if(loaded_offsets[j] == ranlibs[i].ran_off){
1429			loaded_offset = TRUE;
1430			break;
1431		    }
1432		}
1433		if(loaded_offset == TRUE)
1434		    continue;
1435		loaded_offsets[nloaded_offsets++] = ranlibs[i].ran_off;
1436
1437		if(ld_trace_archives == TRUE &&
1438		   ld_trace_archive_printed == FALSE){
1439		    char resolvedname[MAXPATHLEN];
1440		    if(realpath(file_name, resolvedname) !=
1441		       NULL)
1442			ld_trace("[Logging for XBS] Used static "
1443				 "archive: %s\n", resolvedname);
1444		    else
1445			ld_trace("[Logging for XBS] Used static "
1446				 "archive: %s\n", file_name);
1447		    ld_trace_archive_printed = TRUE;
1448		}
1449		/*
1450		 * This is an objective-C symbol and the object file at this
1451		 * offset has not been loaded so load it.
1452		 */
1453		cur_obj = new_object_file();
1454		cur_obj->file_name = file_name;
1455		cur_obj->ar_hdr = (struct ar_hdr *)(file_addr +
1456					    ranlibs[i].ran_off);
1457		if(strncmp(cur_obj->ar_hdr->ar_name, AR_EFMT1,
1458			   sizeof(AR_EFMT1) - 1) == 0){
1459		    ar_name = file_addr + ranlibs[i].ran_off +
1460			      sizeof(struct ar_hdr);
1461		    ar_name_size = strtoul(cur_obj->ar_hdr->ar_name +
1462					   sizeof(AR_EFMT1) - 1, NULL, 10);
1463		    j = ar_name_size;
1464		}
1465		else{
1466		    ar_name = cur_obj->ar_hdr->ar_name;
1467		    ar_name_size = 0;
1468		    j = size_ar_name(cur_obj->ar_hdr);
1469		}
1470		cur_obj->ar_name = ar_name;
1471		cur_obj->ar_name_size = j;
1472		cur_obj->obj_addr = file_addr + ranlibs[i].ran_off +
1473				    sizeof(struct ar_hdr) + ar_name_size;
1474		cur_obj->obj_size = strtol(cur_obj->ar_hdr->ar_size,
1475					   NULL, 10) - ar_name_size;
1476		if(ranlibs[i].ran_off + sizeof(struct ar_hdr) + ar_name_size +
1477				    cur_obj->obj_size > file_size){
1478		    error("malformed library: %s (member %.*s "
1479			  "extends past the end of the file, can't "
1480			  "load from it)", file_name, (int)j, ar_name);
1481		    return;
1482		}
1483		if(whyload){
1484		    print_obj_name(cur_obj);
1485		    print("loaded because of -ObjC flag to get symbol: %s\n",
1486			  bsearch_strings + ranlibs[i].ran_un.ran_strx);
1487		}
1488		merge(FALSE, FALSE, force_weak);
1489	    }
1490	    free(loaded_offsets);
1491	}
1492
1493	/*
1494	 * If a dynamic library has been referenced then this archive library
1495	 * is put on the dynamic library search list and it will be loaded
1496	 * from with dynamic library search semantics.
1497	 */
1498	if(dynamic_libs != NULL){
1499	    p = add_dynamic_lib(SORTED_ARCHIVE, NULL, NULL);
1500	    if(strncmp(symdef_ar_name, SYMDEF_SORTED,
1501		       sizeof(SYMDEF_SORTED) - 1) == 0){
1502		p->type = SORTED_ARCHIVE;
1503/*
1504 * With the 4.1mach patch and 4.2mach release, we are putting the libgcc
1505 * functions into a static archive (libcc_dynamic.a) which we will link into
1506 * every image.  So this obscure warning message would then be seen on nearly
1507 * every link.  So the decision is to just remove the warning message.
1508 */
1509#ifdef notdef
1510		warning("archive library: %s appears after reference to "
1511			"dynamic shared library and will be searched as a "
1512			"dynamic shared library which only the first member "
1513			"that defines a symbol will ever be loaded", file_name);
1514#endif /* notdef */
1515	    }
1516	    else{
1517		p->type = UNSORTED_ARCHIVE;
1518#ifdef notdef
1519		warning("table of contents of library: %s not sorted slower "
1520			"link editing will result (use the ranlib(1) -s "
1521			"option), also library appears after reference to "
1522			"dynamic shared library and will be searched as a "
1523			"dynamic shared library which only the first member "
1524			"that defines a symbol will ever be loaded", file_name);
1525#endif /* notdef */
1526	    }
1527	    p->file_name = file_name;
1528	    p->file_addr = file_addr;
1529	    p->file_size = file_size;
1530	    p->nranlibs = nranlibs;
1531	    p->ranlibs = ranlibs;
1532	    p->ranlib_strings = bsearch_strings;
1533	    return;
1534	}
1535#endif /* !defined(RLD) */
1536
1537	/*
1538	 * Two possible algorithms are used to determine which members from the
1539	 * archive are to be loaded.  The first is faster and requires the
1540	 * ranlib structures to be in sorted order (as produced by the ranlib(1)
1541	 * -s option).  The only case this can't be done is when more than one
1542	 * library member in the same archive defines the same symbol.  In this
1543	 * case ranlib(1) will never sort the ranlib structures but will leave
1544	 * them in the order of the archive so that the proper member that
1545	 * defines a symbol that is defined in more that one object is loaded.
1546	 */
1547	if(strncmp(symdef_ar_name, SYMDEF_SORTED,
1548		   sizeof(SYMDEF_SORTED) - 1) == 0){
1549	    /*
1550	     * Now go through the undefined symbol list and look up each symbol
1551	     * in the sorted ranlib structures looking to see it their is a
1552	     * library member that satisfies this undefined symbol.  If so that
1553	     * member is loaded and merge() is called.
1554	     */
1555	    for(undefined = undefined_list.next;
1556		undefined != &undefined_list;
1557		/* no increment expression */){
1558		/* If this symbol is no longer undefined delete it and move on*/
1559		if(undefined->merged_symbol->nlist.n_type != (N_UNDF | N_EXT) ||
1560		   undefined->merged_symbol->nlist.n_value != 0){
1561		    undefined = undefined->next;
1562		    delete_from_undefined_list(undefined->prev);
1563		    continue;
1564		}
1565		ranlib = bsearch(undefined->merged_symbol->nlist.n_un.n_name,
1566			   ranlibs, nranlibs, sizeof(struct ranlib),
1567			   (int (*)(const void *, const void *))ranlib_bsearch);
1568		if(ranlib != NULL){
1569
1570		    if(ld_trace_archives == TRUE &&
1571		       ld_trace_archive_printed == FALSE){
1572			char resolvedname[MAXPATHLEN];
1573			if(realpath(file_name, resolvedname) != NULL)
1574			    ld_trace("[Logging for XBS] Used "
1575				     "static archive: %s\n", resolvedname);
1576			else
1577			    ld_trace("[Logging for XBS] Used "
1578				     "static archive: %s\n", file_name);
1579			ld_trace_archive_printed = TRUE;
1580		    }
1581
1582		    /* there is a member that defineds this symbol so load it */
1583		    cur_obj = new_object_file();
1584#ifdef RLD
1585		    cur_obj->file_name = allocate(strlen(file_name) + 1);
1586		    strcpy(cur_obj->file_name, file_name);
1587		    cur_obj->from_fat_file = from_fat_file;
1588#else
1589		    cur_obj->file_name = file_name;
1590#endif /* RLD */
1591		    cur_obj->ar_hdr = (struct ar_hdr *)(file_addr +
1592							ranlib->ran_off);
1593		    if(strncmp(cur_obj->ar_hdr->ar_name, AR_EFMT1,
1594			       sizeof(AR_EFMT1)-1) == 0){
1595			ar_name = file_addr + ranlib->ran_off +
1596				  sizeof(struct ar_hdr);
1597			ar_name_size = strtoul(cur_obj->ar_hdr->ar_name +
1598					       sizeof(AR_EFMT1) - 1, NULL, 10);
1599			j = ar_name_size;
1600		    }
1601		    else{
1602			ar_name = cur_obj->ar_hdr->ar_name;
1603			ar_name_size = 0;
1604			j = size_ar_name(cur_obj->ar_hdr);
1605		    }
1606		    cur_obj->ar_name = ar_name;
1607		    cur_obj->ar_name_size = j;
1608		    cur_obj->obj_addr = file_addr + ranlib->ran_off +
1609					sizeof(struct ar_hdr) + ar_name_size;
1610		    cur_obj->obj_size = strtol(cur_obj->ar_hdr->ar_size, NULL,
1611					       10) - ar_name_size;
1612		    if(ranlib->ran_off + sizeof(struct ar_hdr) + ar_name_size +
1613						cur_obj->obj_size > file_size){
1614			error("malformed library: %s (member %.*s extends past "
1615			      "the end of the file, can't load from it)",
1616			      file_name, (int)j, ar_name);
1617			return;
1618		    }
1619		    if(whyload){
1620			print_obj_name(cur_obj);
1621			print("loaded to resolve symbol: %s\n",
1622			       undefined->merged_symbol->nlist.n_un.n_name);
1623		    }
1624
1625		    merge(FALSE, FALSE, force_weak);
1626
1627		    /* make sure this symbol got defined */
1628		    if(errors == 0 &&
1629		       undefined->merged_symbol->nlist.n_type == (N_UNDF|N_EXT)
1630		       && undefined->merged_symbol->nlist.n_value == 0){
1631			error("malformed table of contents in library: %s "
1632			      "(member %.*s did not define symbol %s)",
1633			      file_name, (int)j, ar_name,
1634			      undefined->merged_symbol->nlist.n_un.n_name);
1635		    }
1636		    undefined = undefined->next;
1637		    delete_from_undefined_list(undefined->prev);
1638		    continue;
1639		}
1640		undefined = undefined->next;
1641	    }
1642	}
1643	else{
1644	    /*
1645	     * The slower algorithm.  Lookup each symbol in the table of
1646	     * contents to see if is undefined.  If so that member is loaded
1647	     * and merge() is called.  A complete pass over the table of
1648	     * contents without loading a member terminates searching
1649	     * the library.  This could be made faster if this wrote on the
1650	     * ran_off to indicate the member at that offset was loaded and
1651	     * then it's symbol would be not be looked up on later passes.
1652	     * But this is not done because it would dirty the table of contents
1653	     * and cause the possibility of more swapping and if fast linking is
1654	     * wanted then the table of contents can be sorted.
1655	     */
1656	    member_loaded = TRUE;
1657	    while(member_loaded == TRUE && errors == 0){
1658		member_loaded = FALSE;
1659		for(i = 0; i < nranlibs; i++){
1660		    merged_symbol = lookup_symbol(bsearch_strings +
1661						   ranlibs[i].ran_un.ran_strx);
1662		    if(merged_symbol->name_len != 0){
1663			if(merged_symbol->nlist.n_type == (N_UNDF | N_EXT) &&
1664			   merged_symbol->nlist.n_value == 0){
1665
1666			    if(ld_trace_archives == TRUE &&
1667			       ld_trace_archive_printed == FALSE){
1668				char resolvedname[MAXPATHLEN];
1669				if(realpath(file_name, resolvedname) != NULL)
1670				    ld_trace("[Logging for XBS] "
1671					     "Used static archive: %s\n",
1672					     resolvedname);
1673				else
1674				    ld_trace("[Logging for XBS] "
1675					     "Used static archive: %s\n",
1676					     file_name);
1677				ld_trace_archive_printed = TRUE;
1678			    }
1679
1680			    /*
1681			     * This symbol is defined in this member so load it.
1682			     */
1683			    cur_obj = new_object_file();
1684#ifdef RLD
1685			    cur_obj->file_name = allocate(strlen(file_name) +1);
1686			    strcpy(cur_obj->file_name, file_name);
1687			    cur_obj->from_fat_file = from_fat_file;
1688#else
1689			    cur_obj->file_name = file_name;
1690#endif /* RLD */
1691			    cur_obj->ar_hdr = (struct ar_hdr *)(file_addr +
1692							ranlibs[i].ran_off);
1693			    if(strncmp(cur_obj->ar_hdr->ar_name, AR_EFMT1,
1694				       sizeof(AR_EFMT1)-1) == 0){
1695				ar_name = file_addr + ranlibs[i].ran_off +
1696					  sizeof(struct ar_hdr);
1697				ar_name_size =
1698					strtoul(cur_obj->ar_hdr->ar_name +
1699					        sizeof(AR_EFMT1) - 1, NULL, 10);
1700				j = ar_name_size;
1701			    }
1702			    else{
1703				ar_name = cur_obj->ar_hdr->ar_name;
1704				ar_name_size = 0;
1705				j = size_ar_name(cur_obj->ar_hdr);
1706			    }
1707			    cur_obj->ar_name = ar_name;
1708			    cur_obj->ar_name_size = j;
1709			    cur_obj->obj_addr = file_addr + ranlibs[i].ran_off +
1710					sizeof(struct ar_hdr) + ar_name_size;
1711			    cur_obj->obj_size = strtol(cur_obj->ar_hdr->ar_size,
1712						       NULL, 10) - ar_name_size;
1713			    if(ranlibs[i].ran_off + sizeof(struct ar_hdr) +
1714			       ar_name_size + cur_obj->obj_size > file_size){
1715				error("malformed library: %s (member %.*s "
1716				      "extends past the end of the file, can't "
1717				      "load from it)", file_name, (int)j,
1718				      ar_name);
1719				return;
1720			    }
1721			    if(whyload){
1722				print_obj_name(cur_obj);
1723				print("loaded to resolve symbol: %s\n",
1724				       merged_symbol->nlist.n_un.n_name);
1725			    }
1726
1727			    merge(FALSE, FALSE, force_weak);
1728
1729			    /* make sure this symbol got defined */
1730			    if(errors == 0 &&
1731			       merged_symbol->nlist.n_type == (N_UNDF | N_EXT)
1732			       && merged_symbol->nlist.n_value == 0){
1733				error("malformed table of contents in library: "
1734				      "%s (member %.*s did not defined "
1735				      "symbol %s)", file_name, (int)j, ar_name,
1736				      merged_symbol->nlist.n_un.n_name);
1737			    }
1738			    /*
1739			     * Skip any other symbols that are defined in this
1740			     * member since it has just been loaded.
1741			     */
1742			    for(j = i; j + 1 < nranlibs; j++){
1743				if(ranlibs[i].ran_off != ranlibs[j + 1].ran_off)
1744				    break;
1745			    }
1746			    i = j;
1747			    member_loaded = TRUE;
1748			}
1749		    }
1750		}
1751	    }
1752	}
1753}
1754
1755/*
1756 * get_toc_byte_sex() guesses the byte sex of the table of contents of the
1757 * library mapped in at the address, addr, of size, size based on the first
1758 * object file's bytesex.  If it can't figure it out, because the library has
1759 * no object file members or is malformed it will return UNKNOWN_BYTE_SEX.
1760 */
1761__private_extern__
1762enum byte_sex
1763get_toc_byte_sex(
1764char *addr,
1765uint32_t size)
1766{
1767     uint32_t magic;
1768     uint32_t ar_name_size;
1769     struct ar_hdr *ar_hdr;
1770     char *p;
1771
1772	ar_hdr = (struct ar_hdr *)(addr + SARMAG);
1773
1774	p = addr + SARMAG + sizeof(struct ar_hdr) +
1775	    rnd(strtoul(ar_hdr->ar_size, NULL, 10), sizeof(short));
1776	while(p + sizeof(struct ar_hdr) + sizeof(uint32_t) < addr + size){
1777	    ar_hdr = (struct ar_hdr *)p;
1778	    if(strncmp(ar_hdr->ar_name, AR_EFMT1, sizeof(AR_EFMT1) - 1) == 0)
1779		ar_name_size = strtoul(ar_hdr->ar_name + sizeof(AR_EFMT1) - 1,
1780				       NULL, 10);
1781	    else
1782		ar_name_size = 0;
1783	    p += sizeof(struct ar_hdr);
1784	    memcpy(&magic, p + ar_name_size, sizeof(uint32_t));
1785	    if(magic == MH_MAGIC || magic == MH_MAGIC_64)
1786		return(get_host_byte_sex());
1787	    else if(magic == SWAP_INT(MH_MAGIC) ||
1788		    magic == SWAP_INT(MH_MAGIC_64))
1789		return(get_host_byte_sex() == BIG_ENDIAN_BYTE_SEX ?
1790		       LITTLE_ENDIAN_BYTE_SEX : BIG_ENDIAN_BYTE_SEX);
1791	    p += rnd(strtoul(ar_hdr->ar_size, NULL, 10), sizeof(short));
1792	}
1793	return(UNKNOWN_BYTE_SEX);
1794}
1795
1796/*
1797 * check_archive_arch() check the archive specified to see if it's architecture
1798 * does not match that of whats being loaded and if so returns FALSE.  Else it
1799 * returns TRUE and the archive should be attemped to be loaded from.  This is
1800 * done so that the obvious case of an archive that is the wrong architecture
1801 * is not reported an object file at a time but rather one error message is
1802 * printed.
1803 */
1804static
1805enum bool
1806check_archive_arch(
1807char *file_name,
1808char *file_addr,
1809unsigned long file_size)
1810{
1811    unsigned long offset, obj_size, length;
1812    struct ar_hdr *symdef_ar_hdr, *ar_hdr;
1813    unsigned long symdef_length, ar_name_size;
1814    char *obj_addr, *ar_name;
1815    struct mach_header mh;
1816    cpu_type_t cputype;
1817    cpu_subtype_t cpusubtype;
1818    enum bool mixed_types;
1819    const char *new_arch, *prev_arch;
1820
1821	cputype = 0;
1822	cpusubtype = 0;
1823	mixed_types = FALSE;
1824
1825	offset = SARMAG;
1826	if(offset == file_size){
1827	    warning("empty archive: %s (can't load from it)", file_name);
1828	    return(FALSE);
1829	}
1830	if(offset + sizeof(struct ar_hdr) > file_size){
1831	    error("truncated or malformed archive: %s (archive header of "
1832		  "first member extends past the end of the file, can't "
1833		  "load from it)", file_name);
1834	    return(FALSE);
1835	}
1836	symdef_ar_hdr = (struct ar_hdr *)(file_addr + offset);
1837	if(strncmp(symdef_ar_hdr->ar_name, AR_EFMT1, sizeof(AR_EFMT1)-1) == 0){
1838	    if(check_extend_format_1(file_name, symdef_ar_hdr,
1839				    file_size - (offset +sizeof(struct ar_hdr)),
1840				    &ar_name_size) == FALSE)
1841		return(FALSE);
1842	    ar_name = file_addr + offset + sizeof(struct ar_hdr);
1843	}
1844	else{
1845	    ar_name = symdef_ar_hdr->ar_name;
1846	    ar_name_size = 0;
1847	}
1848	if(strncmp(ar_name, SYMDEF, sizeof(SYMDEF) - 1) == 0){
1849	    offset += sizeof(struct ar_hdr);
1850	    symdef_length = strtol(symdef_ar_hdr->ar_size, NULL, 10);
1851	    if(offset + symdef_length > file_size){
1852		error("truncated or malformed archive: %s (table of "
1853		      "contents extends past the end of the file, can't "
1854		      "load from it)", file_name);
1855		return(FALSE);
1856	    }
1857	    offset += rnd(symdef_length, sizeof(short));
1858	}
1859	while(offset < file_size){
1860	    if(offset + sizeof(struct ar_hdr) > file_size){
1861		error("truncated or malformed archive: %s at offset %lu "
1862		      "(archive header of next member extends past the end "
1863		      "of the file, can't load from it)", file_name, offset);
1864		return(FALSE);
1865	    }
1866	    ar_hdr = (struct ar_hdr *)(file_addr + offset);
1867	    offset += sizeof(struct ar_hdr);
1868	    if(strncmp(ar_hdr->ar_name, AR_EFMT1, sizeof(AR_EFMT1) - 1) == 0){
1869		if(check_extend_format_1(file_name, ar_hdr, file_size - offset,
1870					&ar_name_size) == FALSE)
1871		    return(FALSE);
1872		ar_name = file_addr + offset;
1873	    }
1874	    else{
1875		ar_name = ar_hdr->ar_name;
1876		ar_name_size = 0;
1877	    }
1878	    offset += ar_name_size;
1879	    obj_addr = file_addr + offset;
1880	    obj_size = strtol(ar_hdr->ar_size, NULL, 10);
1881	    obj_size -= ar_name_size;
1882	    if(offset + obj_size > file_size){
1883		error("truncated or malformed archive: %s at offset %lu "
1884		      "(member extends past the end of the file, can't load "
1885		      "from it)", file_name, offset);
1886		return(FALSE);
1887	    }
1888	    if(obj_size >= sizeof(struct mach_header)){
1889		memcpy(&mh, obj_addr, sizeof(struct mach_header));
1890		if(mh.magic == SWAP_LONG(MH_MAGIC))
1891		    swap_mach_header(&mh, host_byte_sex);
1892		if(mh.magic == MH_MAGIC){
1893		    if(cputype == 0){
1894			cputype = mh.cputype;
1895			cpusubtype = mh.cpusubtype;
1896		    }
1897		    else if(cputype != mh.cputype){
1898			mixed_types = TRUE;
1899		    }
1900		}
1901	    }
1902	    length = rnd(obj_size, sizeof(short));
1903	    offset += length;
1904	}
1905	if(arch_flag.cputype != 0 && mixed_types == FALSE &&
1906	   arch_flag.cputype != cputype && cputype != 0){
1907	    if(no_arch_warnings == TRUE)
1908		return(FALSE);
1909	    new_arch = get_arch_name_from_types(cputype, cpusubtype);
1910	    prev_arch = get_arch_name_from_types(arch_flag.cputype,
1911						 arch_flag.cpusubtype);
1912	    if(arch_flag.name != NULL)
1913		warning("%s archive's cputype (%d, architecture %s) does "
1914		    "not match cputype (%d) for specified -arch flag: "
1915		    "%s (can't load from it)", file_name, cputype, new_arch,
1916		    arch_flag.cputype, arch_flag.name);
1917	    else
1918		warning("%s archive's cputype (%d, architecture %s) does "
1919		    "not match cputype (%d architecture %s) of objects "
1920		    "files previously loaded (can't load from it)", file_name,
1921		    cputype, new_arch, arch_flag.cputype, prev_arch);
1922	    return(FALSE);
1923	}
1924	return(TRUE);
1925}
1926
1927/*
1928 * check_extend_format_1() checks the archive header for extended format #1.
1929 */
1930static
1931enum bool
1932check_extend_format_1(
1933char *name,
1934struct ar_hdr *ar_hdr,
1935unsigned long size_left,
1936unsigned long *member_name_size)
1937{
1938    char *p, *endp, buf[sizeof(ar_hdr->ar_name)+1];
1939    unsigned long ar_name_size;
1940
1941	*member_name_size = 0;
1942
1943	buf[sizeof(ar_hdr->ar_name)] = '\0';
1944	memcpy(buf, ar_hdr->ar_name, sizeof(ar_hdr->ar_name));
1945	p = buf + sizeof(AR_EFMT1) - 1;
1946	if(isdigit(*p) == 0){
1947	    error("truncated or malformed archive: %s (ar_name: %.*s for "
1948		  "archive extend format #1 starts with non-digit)", name,
1949		  (int)sizeof(ar_hdr->ar_name), ar_hdr->ar_name);
1950	    return(FALSE);
1951	}
1952	ar_name_size = strtoul(p, &endp, 10);
1953	if(ar_name_size == ULONG_MAX && errno == ERANGE){
1954	    error("truncated or malformed archive: %s (size in ar_name: %.*s "
1955		  "for archive extend format #1 overflows unsigned long)",
1956		  name, (int)sizeof(ar_hdr->ar_name), ar_hdr->ar_name);
1957	    return(FALSE);
1958	}
1959	while(*endp == ' ' && *endp != '\0')
1960	    endp++;
1961	if(*endp != '\0'){
1962	    error("truncated or malformed archive: %s (size in ar_name: %.*s "
1963		  "for archive extend format #1 contains non-digit and "
1964		  "non-space characters)", name, (int)sizeof(ar_hdr->ar_name),
1965		  ar_hdr->ar_name);
1966	    return(FALSE);
1967	}
1968	if(ar_name_size > size_left){
1969	    error("truncated or malformed archive: %s (archive name of member "
1970		  "extends past the end of the file)", name);
1971	    return(FALSE);
1972	}
1973	*member_name_size = ar_name_size;
1974	return(TRUE);
1975}
1976
1977
1978/* This is an object file so it is unconditionally loaded */
1979static
1980void
1981pass1_object(
1982char *file_name,
1983char *file_addr,
1984unsigned long file_size,
1985enum bool base_name,
1986enum bool from_fat_file,
1987enum bool dylib_only,
1988enum bool bundle_loader,
1989enum bool force_weak)
1990{
1991#ifdef __MWERKS__
1992    enum bool dummy;
1993        dummy = base_name;
1994        dummy = from_fat_file;
1995#endif
1996	cur_obj = new_object_file();
1997#ifdef RLD
1998	cur_obj->file_name = allocate(strlen(file_name) + 1);
1999	strcpy(cur_obj->file_name, file_name);
2000	cur_obj->from_fat_file = from_fat_file;
2001#else
2002	cur_obj->file_name = file_name;
2003#endif /* RLD */
2004	cur_obj->obj_addr = file_addr;
2005	cur_obj->obj_size = file_size;
2006#ifndef RLD
2007	/*
2008	 * If this is the base file of an incremental link then set the
2009	 * pointer to the object file.
2010	 */
2011	if(base_name == TRUE)
2012	    base_obj = cur_obj;
2013#endif /* !defined(RLD) */
2014
2015	merge(dylib_only, bundle_loader, force_weak);
2016
2017#ifndef RLD
2018	/*
2019	 * If this is the base file of an incremental link then collect it's
2020	 * segments for overlap checking.
2021	 */
2022	if(base_name == TRUE)
2023	    collect_base_obj_segments();
2024#endif /* !defined(RLD) */
2025	return;
2026}
2027
2028#ifndef RLD
2029/*
2030 * search_dynamic_libs() searches the libraries on the list of dynamic libraries
2031 * to resolve undefined symbols.  This is mostly done for static checking of
2032 * undefined symbols.  If an archive library appears after a dynamic library
2033 * on the static link line then it will be on the list of dynamic libraries
2034 * to search and be searched with dynamic library search semantics.  Dynamic
2035 * library search semantics here mimic what happens in the dynamic link editor.
2036 * For each undefined symbol a module that defines this symbol is searched for
2037 * throught the list of libraries to be searched.  That is for each symbol the
2038 * search starts at the begining of the list of libraries to be searched.  This
2039 * is unlike archive library search semantic when each library is search once
2040 * when encountered.
2041 */
2042__private_extern__
2043void
2044search_dynamic_libs(
2045void)
2046{
2047    struct dynamic_library *p, *q, *dep, *prev;
2048    unsigned long i, j, nmodules, size, ar_name_size;
2049    enum bool removed, some_images_setup;
2050    char *ar_name;
2051
2052    struct mach_header *mh;
2053    struct load_command *lc;
2054    struct dylib_command *dl;
2055    struct segment_command *sg;
2056
2057    struct undefined_list *undefined;
2058    enum bool found;
2059    struct dylib_table_of_contents *toc;
2060    struct ranlib *ranlib;
2061
2062    enum bool bind_at_load_warning;
2063    struct merged_symbol_list *merged_symbol_list;
2064    struct merged_symbol *merged_symbol;
2065
2066    unsigned long library_ordinal;
2067    char *umbrella_install_name, *short_name, *has_suffix;
2068    enum bool is_framework, set_some_ordinals, non_set_ordinals;
2069
2070    struct nlist *extdef_symbols, *extdef;
2071
2072	/*
2073	 * If -twolevel_namespace is in effect assign the library ordinals to
2074	 * all of the dynamic libraries specified on the command line and
2075	 * already entered on the dynamic_libs list.  These are the primary
2076	 * libraries and only these ordinals will be recoded in the symbols.
2077	 * any dependent library added will use the library ordinal from the
2078	 * primary library that depended on it.  Then when an undefined symbol
2079	 * is referenced from a dynamic library then its library_ordinal is
2080	 * recorded in the symbol table nlist struct in the n_desc field with
2081	 * the macro SET_LIBRARY_ORDINAL(nlist.n_desc, library_ordinal).
2082	 */
2083	library_ordinal = 1;
2084	for(p = dynamic_libs; p != NULL; p = p->next){
2085	    if(p->type == DYLIB && p->dl->cmd == LC_ID_DYLIB){
2086		if(twolevel_namespace == TRUE){
2087		    if(library_ordinal > MAX_LIBRARY_ORDINAL)
2088			fatal("too many dynamic libraries used, maximum is: %d "
2089			      "when -twolevel_namespace is in effect",
2090			      MAX_LIBRARY_ORDINAL);
2091		}
2092		p->definition_obj->library_ordinal = library_ordinal;
2093		library_ordinal++;
2094		p->dependent_images =
2095		    allocate(p->definition_obj->nload_dylibs *
2096			     sizeof(struct dynamic_library *));
2097	    }
2098	    else if(p->type == BUNDLE_LOADER){
2099		p->definition_obj->library_ordinal = EXECUTABLE_ORDINAL;
2100	    }
2101	}
2102
2103	/*
2104	 * The code in the following loop adds dynamic libraries to the search
2105	 * list and this ordering matches the library search order dyld uses
2106	 * for flat-level namespace images and lookups.
2107	 *
2108	 * But for two-level namespace lookups ld(1) and dyld lookup symbols in
2109	 * all the sub_images of a dynamic library when it is encountered in the
2110	 * search list.  So this can get different symbols in the flat and
2111	 * two-level namespace cases if there are multiple definitions of the
2112	 * same symbol in a framework's sub-images.  Or if there are multiple
2113	 * umbrella frameworks where their sub-frameworks have multiple
2114	 * definitions of the same symbol.
2115	 *
2116	 * Also to record two-level namespace hints ld(1) must exactly match the
2117	 * list of sub-images created for each library so it can assign the
2118	 * sub-image indexes and then record them.
2119	 */
2120
2121	/*
2122	 * For dynamic libraries on the dynamic library search list that are
2123	 * from LC_LOAD_DYLIB, LC_LOAD_WEAK_DYLIB or LC_REEXPORT_DYLIB
2124	 * references convert them into using a dylib file so it can be
2125	 * searched.  Or remove them from the search list if it can't be
2126	 * converted.  Then add all the dependent libraries for that library to
2127	 * the search list.
2128	 */
2129	indirect_dylib = TRUE;
2130	prev = NULL;
2131	for(p = dynamic_libs; p != NULL; p = p->next){
2132	    removed = FALSE;
2133	    /*
2134	     * If this element on the dynamic library list comes from a
2135	     * LC_LOAD_DYLIB, LC_LOAD_WEAK_DYLIB or LC_REEXPORT_DYLIB reference
2136	     * try to convert them into using a dylib file so it can be
2137	     * searched.  If not take it off the list.
2138	     */
2139	    if(p->type == DYLIB &&
2140	       (p->dl->cmd == LC_LOAD_DYLIB ||
2141		p->dl->cmd == LC_LOAD_WEAK_DYLIB ||
2142		p->dl->cmd == LC_REEXPORT_DYLIB)){
2143		if(open_dylib(p) == FALSE){
2144		    if(prebinding == TRUE){
2145			warning("prebinding disabled because dependent "
2146			    "library: %s can't be searched", p->dylib_file !=
2147			    NULL ? p->file_name : p->dylib_name);
2148			if(ld_trace_prebinding_disabled == TRUE)
2149			    ld_trace("[Logging for XBS] prebinding"
2150				     " disabled for %s because dependent library: "
2151				     "%s can't be searched\n", final_output !=
2152				     NULL ? final_output : outputfile,
2153				     p->dylib_file != NULL ? p->file_name :
2154				     p->dylib_name);
2155			prebinding = FALSE;
2156		    }
2157		    /* remove this dynamic library from the search list */
2158		    if(prev == NULL)
2159			dynamic_libs = p->next;
2160		    else
2161			prev->next = p->next;
2162		    removed = TRUE;
2163		}
2164		else{
2165		    p->dependent_images =
2166			allocate(p->definition_obj->nload_dylibs *
2167			         sizeof(struct dynamic_library *));
2168		}
2169	    }
2170	    /*
2171	     * If this element on the dynamic library list is a dylib file
2172	     * add all of it's dependent libraries to the list.
2173	     */
2174	    if(removed == FALSE &&
2175	       p->type == DYLIB && p->dl->cmd == LC_ID_DYLIB){
2176		mh = (struct mach_header *)p->definition_obj->obj_addr;
2177		if(prebinding == TRUE &&
2178		   (mh->flags & MH_PREBOUND) != MH_PREBOUND){
2179		    warning("prebinding disabled because dependent library: %s "
2180			"is not prebound", p->dylib_file != NULL ?
2181			p->file_name : p->dylib_name);
2182		    if(ld_trace_prebinding_disabled == TRUE)
2183			ld_trace("[Logging for XBS] prebinding "
2184				 "disabled for %s because dependent library: %s "
2185				 "is not prebound\n", final_output != NULL ?
2186				 final_output : outputfile, p->dylib_file !=
2187				 NULL ? p->file_name : p->dylib_name);
2188		    prebinding = FALSE;
2189		}
2190		lc = (struct load_command *)
2191			((char *)p->definition_obj->obj_addr +
2192			 sizeof(struct mach_header));
2193		for(i = 0; i < mh->ncmds; i++){
2194		    if(lc->cmd == LC_LOAD_DYLIB ||
2195		       lc->cmd == LC_LOAD_WEAK_DYLIB ||
2196		       lc->cmd == LC_REEXPORT_DYLIB){
2197			dl = (struct dylib_command *)lc;
2198			dep = add_dynamic_lib(DYLIB, dl, p->definition_obj);
2199			p->dependent_images[p->ndependent_images++] = dep;
2200		    }
2201		    lc = (struct load_command *)((char *)lc + lc->cmdsize);
2202		}
2203	    }
2204	    if(removed == FALSE)
2205		prev = p;
2206	}
2207	indirect_dylib = FALSE;
2208
2209#ifdef DEBUG
2210	if(debug & (1 << 22)){
2211	    print("dynamic library search list and ordinals before sub "
2212		  "assignments:\n");
2213	    for(p = dynamic_libs; p != NULL; p = p->next){
2214		if(p->type == DYLIB){
2215		    if(p->dylib_file != NULL)
2216			printf("  %s ordinal %lu (using file %s)\n",
2217			   p->dylib_name, p->definition_obj->library_ordinal,
2218			   p->file_name);
2219		    else{
2220			short_name = guess_short_name(p->dylib_name,
2221						&is_framework, &has_suffix);
2222			printf("  %s oridinal %lu\n", short_name != NULL ?
2223			       short_name : p->dylib_name,
2224			       p->definition_obj->library_ordinal);
2225		    }
2226		}
2227		else
2228		    printf("  %s (archive)\n", p->file_name);
2229	    }
2230	}
2231#endif /* DEBUG */
2232
2233	/*
2234	 * If we are creating or using two-level namespace images now that all
2235	 * the indirect libraries have been found and opened go through and set
2236	 * the library_ordinal for those that are used indirectly via a
2237	 * sub-umbrella, sub-library or sub-framework.
2238	 */
2239
2240	/*
2241	 * Set up the umbrella and library names (if any) for all dynamic
2242	 * libraries.
2243	 */
2244	for(p = dynamic_libs; p != NULL; p = p->next){
2245	    if(p->type != DYLIB)
2246		continue;
2247	    if(p->umbrella_name == NULL){
2248		umbrella_install_name = (char *)p->dl +
2249					p->dl->dylib.name.offset;
2250		short_name = guess_short_name(umbrella_install_name,
2251					      &is_framework, &has_suffix);
2252		if(short_name != NULL && is_framework == TRUE)
2253		    p->umbrella_name = short_name;
2254		else if(short_name != NULL && is_framework == FALSE)
2255		    p->library_name = short_name;
2256	    }
2257	}
2258	/*
2259	 * Now with all the indirect libraries loaded and the
2260	 * dependent_images set up set up the sub_images for any dynamic
2261	 * library that does not have this set up yet.  Since sub_images
2262	 * include sub_umbrellas and sub_librarys any dynamic library that
2263	 * has sub_umbrellas or sub_librarys must have their sub_umbrella
2264	 * and sub_librarys images set up first. To do this
2265	 * setup_sub_images() will return FALSE for a dynamic library that
2266	 * needed one of its sub_umbrellas or sub_libraries set up and we
2267	 * will loop here until we get a clean pass with no more dynamic
2268	 * libraries needing setup.
2269	 */
2270	do{
2271	    some_images_setup = FALSE;
2272	    for(p = dynamic_libs; p != NULL; p = p->next){
2273		if(p->type != DYLIB)
2274		    continue;
2275		if(p->sub_images_setup == FALSE)
2276		    some_images_setup |= setup_sub_images(p);
2277	    }
2278	}while(some_images_setup == TRUE);
2279	/*
2280	 * Set the library ordinals for libraries that are not set.
2281	 */
2282	do{
2283	    /*
2284	     * Set the library ordinals of sub-frameworks who's umbrella
2285	     * framework has its library ordinal set.
2286	     */
2287	    set_some_ordinals = FALSE;
2288	    non_set_ordinals = FALSE;
2289	    for(p = dynamic_libs; p != NULL; p = p->next){
2290		if(p->type != DYLIB)
2291		    continue;
2292		if(p->definition_obj->library_ordinal != 0 &&
2293		   p->umbrella_name != NULL)
2294		    set_some_ordinals |= set_sub_frameworks_ordinals(p);
2295		else
2296		    non_set_ordinals = TRUE;
2297	    }
2298	    /*
2299	     * If there are still some not set ordinals then set the dylibs
2300	     * that are sub-umbrella's or sub-libraries that are not set.
2301	     */
2302	    if(non_set_ordinals == TRUE){
2303		for(p = dynamic_libs; p != NULL; p = p->next){
2304		    if(p->type != DYLIB)
2305			continue;
2306		    if(p->definition_obj->library_ordinal == 0 &&
2307		       (p->umbrella_name != NULL ||
2308			p->library_name != NULL)){
2309			set_some_ordinals |=
2310			    set_sub_umbrella_sub_library_ordinal(p);
2311		    }
2312		}
2313	    }
2314	}while(set_some_ordinals == TRUE);
2315
2316#ifdef DEBUG
2317	if(debug & (1 << 22)){
2318	    print("dynamic library search list and ordinals after sub "
2319		  "assignments:\n");
2320	    for(p = dynamic_libs; p != NULL; p = p->next){
2321		if(p->type == DYLIB){
2322		    if(p->dylib_file != NULL)
2323			printf("  %s ordinal %lu isub_image %lu "
2324			       "(using file %s)\n", p->dylib_name,
2325			       p->definition_obj->library_ordinal,
2326			       p->definition_obj->isub_image, p->file_name);
2327		    else{
2328			short_name = guess_short_name(p->dylib_name,
2329						&is_framework, &has_suffix);
2330			printf("  %s oridinal %lu isub_image %lu\n",
2331			       short_name != NULL ?  short_name : p->dylib_name,
2332			       p->definition_obj->library_ordinal,
2333			       p->definition_obj->isub_image);
2334		    }
2335		    print("    ndependent_images = %lu\n",p->ndependent_images);
2336		    for(i = 0; i < p->ndependent_images; i++){
2337			dep = p->dependent_images[i];
2338			short_name = guess_short_name(dep->dylib_name,
2339						&is_framework, &has_suffix);
2340			printf("      [%lu] %s\n", i, short_name != NULL ?
2341			       short_name : dep->dylib_name);
2342
2343		    }
2344		    print("    nsub_images = %lu\n",p->nsub_images);
2345		    for(i = 0; i < p->nsub_images; i++){
2346			dep = p->sub_images[i];
2347			short_name = guess_short_name(dep->dylib_name,
2348						&is_framework, &has_suffix);
2349			printf("      [%lu] %s\n", i, short_name != NULL ?
2350			       short_name : dep->dylib_name);
2351
2352		    }
2353		}
2354		else
2355		    printf("  %s (archive)\n", p->file_name);
2356	    }
2357	}
2358#endif /* DEBUG */
2359
2360	/*
2361	 * When building for two-level-namespace, remove from the search path
2362	 * indirect libraries that cannot be encoded in a library ordinal.
2363	 *
2364	 * It is unclear what the reason for this part of the logic:
2365	 *  && (force_flat_namespace == FALSE) && (filetype != MH_OBJECT)
2366	 * is here for and is likely wrong.
2367	 */
2368	if((twolevel_namespace == TRUE) &&
2369	   (force_flat_namespace == FALSE) &&
2370	   (filetype != MH_OBJECT)){
2371	    struct dynamic_library* last_library;
2372	    unsigned int total_library_count;
2373	    unsigned int direct_library_count;
2374
2375	    last_library = NULL;
2376	    total_library_count = 0;
2377	    direct_library_count = 0;
2378	    for(p = dynamic_libs; p != NULL; p = p->next){
2379		total_library_count += 1;
2380		if((p->type == DYLIB) &&
2381		   (p->definition_obj->library_ordinal == 0)){
2382		    if(last_library == NULL)
2383			dynamic_libs = p->next;
2384		    else
2385			last_library->next = p->next;
2386		}
2387		else{
2388		    last_library = p;
2389		    direct_library_count += 1;
2390		}
2391	    }
2392	    if(direct_library_count != 0)
2393		indirect_library_ratio =
2394		    total_library_count / direct_library_count;
2395	}
2396
2397	/*
2398	 * Go through the specified dynamic libraries setting up their table of
2399	 * contents data.
2400	 */
2401	for(p = dynamic_libs; p != NULL; p = p->next){
2402	    if(p->type == DYLIB){
2403		if(p->dl->cmd == LC_ID_DYLIB){
2404		    p->tocs = (struct dylib_table_of_contents *)(
2405			       p->definition_obj->obj_addr +
2406			       p->definition_obj->dysymtab->tocoff);
2407		    p->strings = p->definition_obj->obj_addr +
2408				 p->definition_obj->symtab->stroff;
2409		    p->symbols = (struct nlist *)(
2410				  p->definition_obj->obj_addr +
2411				  p->definition_obj->symtab->symoff);
2412		    if(p->definition_obj->swapped)
2413	    		swap_nlist(p->symbols,
2414				   p->definition_obj->symtab->nsyms,
2415				   host_byte_sex);
2416		    p->mods = (struct dylib_module *)(
2417			       p->definition_obj->obj_addr +
2418			       p->definition_obj->dysymtab->modtaboff);
2419		    /*
2420		     * If prebinding an executable create a LC_PREBOUND_DYLIB
2421		     * load command for each dynamic library.  To allow the
2422		     * prebinding to be redone when the library has more
2423		     * modules the bit vector for the linked modules is padded
2424		     * to 125% of the number of modules with a minimum of 64
2425		     * modules.
2426		     */
2427		    if(prebinding == TRUE && filetype == MH_EXECUTE){
2428			nmodules = p->definition_obj->dysymtab->nmodtab +
2429				   (p->definition_obj->dysymtab->nmodtab >> 2);
2430			if(nmodules < 64)
2431			    nmodules = 64;
2432			size = sizeof(struct prebound_dylib_command) +
2433			       rnd(strlen(p->dylib_name) + 1, sizeof(long)) +
2434			       rnd(nmodules / 8, sizeof(long));
2435			p->pbdylib = allocate(size);
2436			memset(p->pbdylib, '\0', size);
2437			p->pbdylib->cmd = LC_PREBOUND_DYLIB;
2438			p->pbdylib->cmdsize = size;
2439			p->pbdylib->name.offset =
2440				sizeof(struct prebound_dylib_command);
2441			strcpy(((char *)p->pbdylib) +
2442				sizeof(struct prebound_dylib_command),
2443				p->dylib_name);
2444			p->pbdylib->nmodules =
2445				p->definition_obj->dysymtab->nmodtab;
2446			p->pbdylib->linked_modules.offset =
2447				sizeof(struct prebound_dylib_command) +
2448				rnd(strlen(p->dylib_name) + 1, sizeof(long));
2449			p->linked_modules = ((char *)p->pbdylib) +
2450				sizeof(struct prebound_dylib_command) +
2451				rnd(strlen(p->dylib_name) + 1, sizeof(long));
2452		    }
2453		}
2454	    }
2455	    if(p->type == BUNDLE_LOADER){
2456		p->strings = p->definition_obj->obj_addr +
2457			     p->definition_obj->symtab->stroff;
2458		p->symbols = (struct nlist *)(
2459			      p->definition_obj->obj_addr +
2460			      p->definition_obj->symtab->symoff);
2461		if(p->definition_obj->swapped)
2462		    swap_nlist(p->symbols,
2463			       p->definition_obj->symtab->nsyms,
2464			       host_byte_sex);
2465	    }
2466	}
2467
2468	/*
2469	 * If we are going to attempt to prebind we save away the segments of
2470	 * the dylibs so they can be checked for overlap after layout.
2471	 */
2472	if(prebinding == TRUE){
2473	    for(p = dynamic_libs; p != NULL; p = p->next){
2474		if(p->type == DYLIB && p->dl->cmd == LC_ID_DYLIB){
2475		    mh = (struct mach_header *)p->definition_obj->obj_addr;
2476		    lc = (struct load_command *)
2477			    ((char *)p->definition_obj->obj_addr +
2478			     sizeof(struct mach_header));
2479		    for(i = 0; i < mh->ncmds; i++){
2480			if(lc->cmd == LC_SEGMENT){
2481		    	    sg = (struct segment_command *)lc;
2482			    add_dylib_segment(sg, p->dylib_name,
2483				(mh->flags & MH_SPLIT_SEGS) == MH_SPLIT_SEGS);
2484			}
2485			lc = (struct load_command *)((char *)lc + lc->cmdsize);
2486		    }
2487		}
2488	    }
2489	}
2490
2491#ifdef DEBUG
2492	if(debug & (1 << 22)){
2493	    print("dynamic library search list:\n");
2494	    for(p = dynamic_libs; p != NULL; p = p->next){
2495		if(p->type == DYLIB){
2496		    if(p->dylib_file != NULL)
2497			printf("\t%s (using file %s)\n", p->dylib_name,
2498			       p->file_name);
2499		    else{
2500			short_name = guess_short_name(p->dylib_name,
2501						&is_framework, &has_suffix);
2502			printf("\t%s\n", short_name != NULL ?
2503			       short_name : p->dylib_name);
2504		    }
2505		}
2506		else
2507		    printf("\t%s (archive)\n", p->file_name);
2508	    }
2509	}
2510#endif
2511	if(ld_trace_dylibs == TRUE){
2512	    for(p = dynamic_libs; p != NULL; p = p->next){
2513		if(p->type == DYLIB){
2514		    char resolvedname[MAXPATHLEN];
2515		    if(realpath(p->definition_obj->file_name, resolvedname) !=
2516		       NULL)
2517			ld_trace("[Logging for XBS] Used dynamic "
2518				 "library: %s\n", resolvedname);
2519		    else
2520		        ld_trace("[Logging for XBS] Used dynamic "
2521				 "library: %s\n", p->definition_obj->file_name);
2522		}
2523	    }
2524	}
2525
2526	/*
2527	 * Now go through the undefined symbol list and look up each symbol
2528	 * in the table of contents of each library on the dynamic library
2529	 * search list.
2530	 */
2531	for(undefined = undefined_list.next;
2532	    undefined != &undefined_list;
2533	    /* no increment expression */){
2534
2535	    /*
2536	     * If this symbol is a twolevel_reference placed on the undefined
2537	     * list by merge_dylib_module_symbols() in symbols.c then we
2538	     * determine which dylib module needs to be loaded and if it is not
2539	     * yet loaded we load it.  Note the merged symbol pointed to by
2540	     * this undefined entry is a fake and not entered into the symbol
2541	     * symbol table.  This merged symbol's nlist is a copy of the nlist
2542	     * from the referencing_library.
2543	     */
2544	    if(undefined->merged_symbol->twolevel_reference == TRUE){
2545		library_ordinal = GET_LIBRARY_ORDINAL(
2546				    undefined->merged_symbol->nlist.n_desc);
2547		if(library_ordinal == SELF_LIBRARY_ORDINAL)
2548		    p = undefined->merged_symbol->referencing_library;
2549		/*
2550		 * Note that if library_ordinal was DYNAMIC_LOOKUP_ORDINAL then
2551		 * merge_dylib_module_symbols() in symbols.c would not have
2552		 * set the twolevel_reference field to TRUE in the merged_symbol
2553		 * and if we get here it with this it is an internal error.
2554		 */
2555		else if(library_ordinal == DYNAMIC_LOOKUP_ORDINAL)
2556		    fatal("internal error: search_dynamic_libs() with a "
2557			  "merged_symbol (%s) on the undefined list with "
2558			  "twolevel_reference == TRUE and library_ordinal == "
2559			  "DYNAMIC_LOOKUP_ORDINAL", undefined->merged_symbol->
2560			  nlist.n_un.n_name);
2561		else
2562		    p = undefined->merged_symbol->referencing_library->
2563			    dependent_images[library_ordinal - 1];
2564		q = p;
2565		/*
2566		 * This could be a dylib that was missing so its dynamic_library
2567		 * struct will be just an LC_LOAD_DYLIB, LC_LOAD_WEAK_DYLIB,
2568		 * LC_REEXPORT_DYLIB command and a name with no strings,
2569		 * symbols, sub_images, etc.
2570	 	 */
2571		if(p->dl->cmd == LC_LOAD_DYLIB ||
2572		   p->dl->cmd == LC_LOAD_WEAK_DYLIB ||
2573		   p->dl->cmd == LC_REEXPORT_DYLIB)
2574		    goto undefined_twolevel_reference;
2575		bsearch_strings = q->strings;
2576		bsearch_symbols = q->symbols;
2577		toc = bsearch(undefined->merged_symbol->nlist.n_un.n_name,
2578			      q->tocs, q->definition_obj->dysymtab->ntoc,
2579			      sizeof(struct dylib_table_of_contents),
2580			      (int (*)(const void *, const void *))
2581				dylib_bsearch);
2582		if(toc == NULL){
2583		    for(i = 0; toc == NULL && i < p->nsub_images; i++){
2584			q = p->sub_images[i];
2585			if(q->dl->cmd == LC_LOAD_DYLIB ||
2586			   q->dl->cmd == LC_LOAD_WEAK_DYLIB ||
2587			   q->dl->cmd == LC_REEXPORT_DYLIB)
2588			    break;
2589			bsearch_strings = q->strings;
2590			bsearch_symbols = q->symbols;
2591			toc = bsearch(undefined->merged_symbol->
2592				  nlist.n_un.n_name, q->tocs,
2593				  q->definition_obj->dysymtab->ntoc,
2594				  sizeof(struct dylib_table_of_contents),
2595				  (int (*)(const void *, const void *))
2596				    dylib_bsearch);
2597		    }
2598		}
2599		if(toc != NULL){
2600		    /*
2601		     * There is a module that defineds this symbol so see if it
2602		     * has been loaded and if not load it.
2603		     */
2604		    if(is_dylib_module_loaded(q->mods + toc->module_index) ==
2605		       FALSE){
2606			cur_obj = new_object_file();
2607			*cur_obj = *(q->definition_obj);
2608			cur_obj->dylib_module = q->mods + toc->module_index;
2609			if(q->linked_modules != NULL)
2610			    q->linked_modules[toc->module_index / 8] |=
2611				1 << toc->module_index % 8;
2612			if(whyload){
2613			    print_obj_name(cur_obj);
2614			    print("loaded to resolve symbol: %s ",
2615			       undefined->merged_symbol->nlist.n_un.n_name);
2616			    dep = undefined->merged_symbol->referencing_library;
2617			    if(dep->umbrella_name != NULL)
2618				short_name = dep->umbrella_name;
2619			    else if(dep->library_name != NULL)
2620				short_name = dep->library_name;
2621			    else
2622				short_name = dep->dylib_name;
2623			    print("referenced from %s\n", short_name);
2624			}
2625			merge_dylib_module_symbols(q);
2626			/*
2627			 * We would like to make sure this symbol got defined
2628			 * from this dylib module.  But since this is a
2629			 * two-level reference the symbol in this dylib module
2630			 * may or may not be used by the output file being
2631			 * created (the symbol entered in the merged symbol
2632			 * table not this fake one).
2633			 */
2634
2635			/*
2636			 * Since something from this dynamic library is being
2637			 * used, if there is a library initialization routine
2638			 * make sure that the module that defines it is loaded.
2639			 */
2640			load_init_dylib_module(q);
2641		    }
2642		    /*
2643		     * If the -Y flag is not set free the memory for this fake
2644		     * merged_symbol which was for a two-level reference, move
2645		     * to the next undefined, and take this off the undefined
2646		     * list.
2647		     */
2648		    if(!Yflag)
2649			free(undefined->merged_symbol);
2650		    undefined = undefined->next;
2651		    delete_from_undefined_list(undefined->prev);
2652		}
2653		else{
2654		    /*
2655		     * The library expected to define this symbol did not define
2656		     * it so it must remain undefined and should result in an
2657		     * undefined symbol error.  In process_undefineds() in
2658		     * symbols.c it loops over the undefined list looking for
2659		     * these fake merged_symbols.
2660		     */
2661undefined_twolevel_reference:
2662		    undefined = undefined->next;
2663		}
2664		continue;
2665	    }
2666
2667	    /* If this symbol is no longer undefined delete it and move on*/
2668	    if(undefined->merged_symbol->nlist.n_type != (N_UNDF | N_EXT) ||
2669	       undefined->merged_symbol->nlist.n_value != 0){
2670		undefined = undefined->next;
2671		delete_from_undefined_list(undefined->prev);
2672		continue;
2673	    }
2674
2675	    /*
2676	     * If -twolevel_namespace is in effect then when each dynamic
2677	     * library is seen all of its sub-images are searched at that
2678	     * point.  So to avoid searching a dynamic library more than once
2679	     * per symbol the twolevel_searched field is set to TRUE when
2680	     * searched and the library is skipped if it is encountered again
2681	     * when looking for the same symbol.
2682	     */
2683	    if(twolevel_namespace == TRUE){
2684		for(p = dynamic_libs; p != NULL; p = p->next)
2685		    p->twolevel_searched = FALSE;
2686	    }
2687	    found = FALSE;
2688	    for(p = dynamic_libs; p != NULL && found == FALSE; p = p->next){
2689		switch(p->type){
2690
2691		case DYLIB:
2692		    if(twolevel_namespace == TRUE &&
2693		       p->twolevel_searched == TRUE)
2694			break;
2695		    /*
2696		     * This could be a dylib that was missing so its
2697		     * dynamic_library struct will be just an LC_LOAD_DYLIB,
2698		     * LC_LOAD_WEAK_DYLIB or LC_REEXPORT_DYLIB command and a
2699		     * name with no strings, symbols, sub_images, etc.
2700		     */
2701		    if(p->dl->cmd == LC_LOAD_DYLIB ||
2702		       p->dl->cmd == LC_LOAD_WEAK_DYLIB ||
2703		       p->dl->cmd == LC_REEXPORT_DYLIB)
2704			break;
2705		    q = p;
2706		    bsearch_strings = q->strings;
2707		    bsearch_symbols = q->symbols;
2708		    toc = bsearch(undefined->merged_symbol->nlist.n_un.n_name,
2709				  q->tocs, q->definition_obj->dysymtab->ntoc,
2710				  sizeof(struct dylib_table_of_contents),
2711				  (int (*)(const void *, const void *))
2712				    dylib_bsearch);
2713		    if(toc == NULL && twolevel_namespace == TRUE){
2714			q->twolevel_searched = TRUE;
2715			for(i = 0; toc == NULL && i < p->nsub_images; i++){
2716			    q = p->sub_images[i];
2717			    q->twolevel_searched = TRUE;
2718			    if(q->dl->cmd == LC_LOAD_DYLIB ||
2719			       q->dl->cmd == LC_LOAD_WEAK_DYLIB ||
2720			       q->dl->cmd == LC_REEXPORT_DYLIB)
2721				break;
2722			    /*
2723			     * Don't search images that cannot be two level
2724			     * encoded.
2725			     *
2726			     * This logic seems questionable that this is not
2727			     * conditional on building a two-level namespace
2728			     * image.
2729			     */
2730			    if(q->definition_obj->library_ordinal == 0)
2731				continue;
2732			    bsearch_strings = q->strings;
2733			    bsearch_symbols = q->symbols;
2734			    toc = bsearch(undefined->merged_symbol->
2735				      nlist.n_un.n_name, q->tocs,
2736				      q->definition_obj->dysymtab->ntoc,
2737				      sizeof(struct dylib_table_of_contents),
2738				      (int (*)(const void *, const void *))
2739					dylib_bsearch);
2740			}
2741		    }
2742		    if(toc != NULL){
2743			/*
2744			 * There is a module that defineds this symbol so
2745			 * load it.
2746			 */
2747			cur_obj = new_object_file();
2748			*cur_obj = *(q->definition_obj);
2749			cur_obj->dylib_module = q->mods + toc->module_index;
2750			if(q->linked_modules != NULL)
2751			    q->linked_modules[toc->module_index / 8] |=
2752				1 << toc->module_index % 8;
2753			if(whyload){
2754			    print_obj_name(cur_obj);
2755			    print("loaded to resolve symbol: %s\n",
2756			       undefined->merged_symbol->nlist.n_un.n_name);
2757			}
2758			merge_dylib_module_symbols(q);
2759			/* make sure this symbol got defined */
2760			if(errors == 0 &&
2761			   undefined->merged_symbol->nlist.n_type ==
2762			    (N_UNDF|N_EXT)
2763			   && undefined->merged_symbol->nlist.n_value == 0){
2764			    error("malformed table of contents in library: "
2765			       "%s (module %s did not define symbol %s)",
2766			       cur_obj->file_name, bsearch_strings +
2767			       cur_obj->dylib_module->module_name,
2768			       undefined->merged_symbol->nlist.n_un.n_name);
2769			}
2770			if(twolevel_namespace == TRUE)
2771			    undefined->merged_symbol->itoc = toc - q->tocs;
2772			undefined = undefined->next;
2773			delete_from_undefined_list(undefined->prev);
2774			found = TRUE;
2775
2776			/*
2777			 * Since something from this dynamic library is being
2778			 * used, if there is a library initialization routine
2779			 * make sure that the module that defines it is loaded.
2780			 */
2781			load_init_dylib_module(q);
2782		    }
2783		    break;
2784
2785		case SORTED_ARCHIVE:
2786		    bsearch_strings = p->ranlib_strings;
2787		    ranlib = bsearch(undefined->merged_symbol->
2788				     nlist.n_un.n_name, p->ranlibs, p->nranlibs,
2789				     sizeof(struct ranlib),
2790				     (int (*)(const void *, const void *))
2791					ranlib_bsearch);
2792		    if(ranlib != NULL){
2793			if(ld_trace_archives == TRUE &&
2794			   p->ld_trace_archive_printed == FALSE){
2795			    char resolvedname[MAXPATHLEN];
2796			    if(realpath(p->file_name, resolvedname) != NULL)
2797				ld_trace("[Logging for XBS] Used "
2798					 "static archive: %s\n", resolvedname);
2799			    else
2800				ld_trace("[Logging for XBS] Used "
2801					 "static archive: %s\n", p->file_name);
2802			    p->ld_trace_archive_printed = TRUE;
2803			}
2804			/*
2805			 * There is a member that defineds this symbol so
2806			 * load it.
2807			 */
2808			cur_obj = new_object_file();
2809			cur_obj->file_name = p->file_name;
2810			cur_obj->ar_hdr = (struct ar_hdr *)(p->file_addr +
2811							    ranlib->ran_off);
2812			if(strncmp(cur_obj->ar_hdr->ar_name, AR_EFMT1,
2813				   sizeof(AR_EFMT1)-1) == 0){
2814			    ar_name = p->file_addr + ranlib->ran_off +
2815				      sizeof(struct ar_hdr);
2816			    ar_name_size =
2817				    strtoul(cur_obj->ar_hdr->ar_name +
2818					    sizeof(AR_EFMT1) - 1, NULL, 10);
2819			    j = ar_name_size;
2820			}
2821			else{
2822			    ar_name = cur_obj->ar_hdr->ar_name;
2823			    ar_name_size = 0;
2824			    j = size_ar_name(cur_obj->ar_hdr);
2825			}
2826			cur_obj->ar_name = ar_name;
2827			cur_obj->ar_name_size = j;
2828			cur_obj->obj_addr = p->file_addr +
2829					    ranlib->ran_off +
2830					    sizeof(struct ar_hdr) +
2831					    ar_name_size;
2832			cur_obj->obj_size = strtol(cur_obj->ar_hdr->ar_size,
2833						   NULL, 10) - ar_name_size;
2834			if(ranlib->ran_off + sizeof(struct ar_hdr) +
2835			   ar_name_size + cur_obj->obj_size > p->file_size){
2836			    error("malformed library: %s (member %.*s extends "
2837				  "past the end of the file, can't load from "
2838				  "it)",p->file_name, (int)j, ar_name);
2839			    return;
2840			}
2841			if(whyload){
2842			    print_obj_name(cur_obj);
2843			    print("loaded to resolve symbol: %s\n",
2844				   undefined->merged_symbol->nlist.n_un.n_name);
2845			}
2846
2847			merge(FALSE, FALSE, FALSE);
2848
2849			/* make sure this symbol got defined */
2850			if(errors == 0 &&
2851			   undefined->merged_symbol->nlist.n_type ==
2852			   (N_UNDF|N_EXT)
2853			   && undefined->merged_symbol->nlist.n_value == 0){
2854			    error("malformed table of contents in library: %s "
2855				  "(member %.*s did not define symbol %s)",
2856				  p->file_name, (int)j, ar_name,
2857				  undefined->merged_symbol->nlist.n_un.n_name);
2858			}
2859			undefined = undefined->next;
2860			delete_from_undefined_list(undefined->prev);
2861			found = TRUE;
2862		    }
2863		    break;
2864
2865		case UNSORTED_ARCHIVE:
2866		    for(i = 0; found == FALSE && i < p->nranlibs; i++){
2867			if(strcmp(undefined->merged_symbol->nlist.n_un.n_name,
2868				  p->ranlib_strings +
2869				  p->ranlibs[i].ran_un.ran_strx) == 0){
2870			    if(ld_trace_archives == TRUE &&
2871			       p->ld_trace_archive_printed == FALSE){
2872				char resolvedname[MAXPATHLEN];
2873				if(realpath(p->file_name, resolvedname) != NULL)
2874				    ld_trace("[Logging for XBS] "
2875					     "Used static archive: %s\n",
2876					     resolvedname);
2877				else
2878				    ld_trace("[Logging for XBS] "
2879					     "Used static archive: %s\n",
2880					     p->file_name);
2881				p->ld_trace_archive_printed = TRUE;
2882			    }
2883			    /*
2884			     * There is a member that defineds this symbol so
2885			     * load it.
2886			     */
2887			    cur_obj = new_object_file();
2888			    cur_obj->file_name = p->file_name;
2889			    cur_obj->ar_hdr = (struct ar_hdr *)(p->file_addr +
2890							p->ranlibs[i].ran_off);
2891			    if(strncmp(cur_obj->ar_hdr->ar_name, AR_EFMT1,
2892				       sizeof(AR_EFMT1)-1) == 0){
2893				ar_name = p->file_addr + p->ranlibs[i].ran_off +
2894					  sizeof(struct ar_hdr);
2895				ar_name_size =
2896					strtoul(cur_obj->ar_hdr->ar_name +
2897					        sizeof(AR_EFMT1) - 1, NULL, 10);
2898				j = ar_name_size;
2899			    }
2900			    else{
2901				ar_name = cur_obj->ar_hdr->ar_name;
2902				ar_name_size = 0;
2903				j = size_ar_name(cur_obj->ar_hdr);
2904			    }
2905			    cur_obj->ar_name = ar_name;
2906			    cur_obj->ar_name_size = j;
2907			    cur_obj->obj_addr = p->file_addr +
2908						p->ranlibs[i].ran_off +
2909						sizeof(struct ar_hdr) +
2910						ar_name_size;
2911			    cur_obj->obj_size = strtol(cur_obj->ar_hdr->ar_size,
2912						       NULL, 10) - ar_name_size;
2913			    if(p->ranlibs[i].ran_off + sizeof(struct ar_hdr) +
2914			       ar_name_size + cur_obj->obj_size > p->file_size){
2915				error("malformed library: %s (member %.*s "
2916				      "extends past the end of the file, can't "
2917				      "load from it)", p->file_name, (int)j,
2918				      ar_name);
2919				return;
2920			    }
2921			    if(whyload){
2922				print_obj_name(cur_obj);
2923				print("loaded to resolve symbol: %s\n",
2924				   undefined->merged_symbol->nlist.n_un.n_name);
2925			    }
2926
2927			    merge(FALSE, FALSE, FALSE);
2928
2929			    /* make sure this symbol got defined */
2930			    if(errors == 0 &&
2931			       undefined->merged_symbol->nlist.n_type ==
2932			       (N_UNDF|N_EXT)
2933			       && undefined->merged_symbol->nlist.n_value == 0){
2934				error("malformed table of contents in library: "
2935				   "%s (member %.*s did not define symbol %s)",
2936				   p->file_name, (int)j, ar_name,
2937				   undefined->merged_symbol->nlist.n_un.n_name);
2938			    }
2939			    undefined = undefined->next;
2940			    delete_from_undefined_list(undefined->prev);
2941			    found = TRUE;
2942			}
2943		    }
2944		    break;
2945
2946		case BUNDLE_LOADER:
2947		    bsearch_strings = p->definition_obj->obj_addr +
2948			      p->definition_obj->symtab->stroff;
2949		    extdef_symbols = (struct nlist *)(
2950				  p->definition_obj->obj_addr +
2951				  p->definition_obj->symtab->symoff) +
2952				  p->definition_obj->dysymtab->iextdefsym;
2953		    extdef =bsearch(undefined->merged_symbol->nlist.n_un.n_name,
2954				  extdef_symbols,
2955				  p->definition_obj->dysymtab->nextdefsym,
2956				  sizeof(struct nlist),
2957				  (int (*)(const void *, const void *))
2958				    nlist_bsearch);
2959		    if(extdef != NULL){
2960			/*
2961			 * There is a external symbol in the bundle loader that
2962			 * defineds this symbol so load it.
2963			 */
2964			cur_obj = p->definition_obj;
2965			if(whyload){
2966			    print_obj_name(cur_obj);
2967			    print("loaded to resolve symbol: %s\n",
2968			       undefined->merged_symbol->nlist.n_un.n_name);
2969			}
2970
2971			merge_bundle_loader_symbols(p);
2972
2973			/* make sure this symbol got defined */
2974			if(errors == 0 &&
2975			   undefined->merged_symbol->nlist.n_type ==
2976			    (N_UNDF|N_EXT)
2977			   && undefined->merged_symbol->nlist.n_value == 0){
2978			    error("malformed external defined symbols of "
2979			       "-bundle_loader: %s (it did not define symbol "
2980			       "%s)", cur_obj->file_name,
2981			       undefined->merged_symbol->nlist.n_un.n_name);
2982			}
2983			undefined = undefined->next;
2984			delete_from_undefined_list(undefined->prev);
2985			found = TRUE;
2986		    }
2987		    break;
2988		}
2989	    }
2990	    if(found == FALSE)
2991		undefined = undefined->next;
2992	}
2993
2994	/*
2995	 * Check to see all merged symbols coming from dynamic libraries
2996	 * came from the first one defining the symbol.  If not issue a warning
2997	 * suggesting -bind_at_launch be used.
2998	 */
2999	if(filetype == MH_EXECUTE && bind_at_load == FALSE){
3000	    bind_at_load_warning = FALSE;
3001	    for(merged_symbol_list = merged_symbol_root == NULL ? NULL :
3002				     merged_symbol_root->list;
3003		merged_symbol_list != NULL;
3004		merged_symbol_list = merged_symbol_list->next){
3005		for(i = 0; i < merged_symbol_list->used; i++){
3006		    merged_symbol = merged_symbol_list->symbols[i];
3007		    if(merged_symbol->defined_in_dylib != TRUE)
3008			continue;
3009		    if(merged_symbol->coalesced_defined_in_dylib == TRUE)
3010			continue;
3011		    if(twolevel_namespace == TRUE){
3012			for(p = dynamic_libs; p != NULL; p = p->next)
3013			    p->twolevel_searched = FALSE;
3014		    }
3015		    for(p = dynamic_libs; p != NULL; p = p->next){
3016			if(p->type == DYLIB){
3017			    if(twolevel_namespace == TRUE &&
3018			       p->twolevel_searched == TRUE)
3019				break;
3020			    q = p;
3021			    if(q->dl->cmd == LC_LOAD_DYLIB ||
3022			       q->dl->cmd == LC_LOAD_WEAK_DYLIB ||
3023			       q->dl->cmd == LC_REEXPORT_DYLIB)
3024				break;
3025			    bsearch_strings = q->strings;
3026			    bsearch_symbols = q->symbols;
3027			    toc = bsearch(merged_symbol->nlist.n_un.n_name,
3028				      q->tocs,q->definition_obj->dysymtab->ntoc,
3029				      sizeof(struct dylib_table_of_contents),
3030				      (int (*)(const void *, const void *))
3031					dylib_bsearch);
3032			    if(toc == NULL && twolevel_namespace == TRUE){
3033				q->twolevel_searched = TRUE;
3034				for(j = 0;
3035				    toc == NULL && j < p->nsub_images;
3036				    j++){
3037				    q = p->sub_images[j];
3038				    q->twolevel_searched = TRUE;
3039				    if(q->dl->cmd == LC_LOAD_DYLIB ||
3040				       q->dl->cmd == LC_LOAD_WEAK_DYLIB ||
3041				       q->dl->cmd == LC_REEXPORT_DYLIB)
3042					break;
3043				    bsearch_strings = q->strings;
3044				    bsearch_symbols = q->symbols;
3045				    toc = bsearch(merged_symbol->
3046				      nlist.n_un.n_name, q->tocs,
3047				      q->definition_obj->dysymtab->ntoc,
3048				      sizeof(struct dylib_table_of_contents),
3049				      (int (*)(const void *, const void *))
3050					dylib_bsearch);
3051				}
3052			    }
3053			    if(toc != NULL){
3054				if(merged_symbol->definition_object->obj_addr
3055				   == q->definition_obj->obj_addr)
3056				    break;
3057				if(merged_symbol->definition_object->obj_addr
3058				   != q->definition_obj->obj_addr){
3059				    if(bind_at_load_warning == FALSE){
3060					warning("suggest use of -bind_at_load, "
3061						"as lazy binding may result in "
3062						"errors or different symbols "
3063						"being used");
3064					bind_at_load_warning = TRUE;
3065				    }
3066				    printf("symbol %s used from dynamic "
3067					"library %s(%s) not from earlier "
3068					"dynamic library %s(%s)\n",
3069					merged_symbol->nlist.n_un.n_name,
3070					merged_symbol->definition_object->
3071					    file_name,
3072					(merged_symbol->definition_object->
3073					    obj_addr + merged_symbol->
3074					    definition_object->symtab->stroff) +
3075					merged_symbol->definition_object->
3076					    dylib_module->module_name,
3077					q->dylib_name,
3078					bsearch_strings + (q->mods +
3079					    toc->module_index)->module_name);
3080				}
3081			    }
3082			}
3083		    }
3084		}
3085	    }
3086	}
3087
3088	/*
3089	 * If the -prebind_all_twolevel_modules is specified and prebinding is
3090	 * is still enabled and the output is an executable and we are not
3091	 * building with -force_flat_namespace then change the bit vectors in
3092	 * the two-level dynamic libraries to mark all modules as used.
3093	 */
3094	if(prebind_all_twolevel_modules == TRUE && prebinding == TRUE &&
3095	   filetype == MH_EXECUTE && force_flat_namespace == FALSE){
3096	    for(p = dynamic_libs; p != NULL; p = p->next){
3097		if(p->type == DYLIB &&
3098		   p->dl->cmd == LC_ID_DYLIB &&
3099		   p->linked_modules != NULL){
3100		    mh = (struct mach_header *)(p->definition_obj->obj_addr);
3101		    if((mh->flags & MH_TWOLEVEL) == MH_TWOLEVEL){
3102			nmodules = p->definition_obj->dysymtab->nmodtab;
3103			for(i = 0; i < nmodules; i++){
3104			    p->linked_modules[i / 8] |= 1 << i % 8;
3105			}
3106		    }
3107		}
3108	    }
3109	}
3110}
3111
3112/*
3113 * load_init_dylib_module() is passed a pointer to a dynamic library that just
3114 * had a module loaded.  Since something from this dynamic library is being used
3115 * if there is a library initialization routine make sure that the module that
3116 * defines it is loaded.
3117 */
3118static
3119void
3120load_init_dylib_module(
3121struct dynamic_library *q)
3122{
3123	if(q->definition_obj->rc != NULL &&
3124	   q->definition_obj->init_module_loaded == FALSE){
3125	    if(is_dylib_module_loaded(q->mods +
3126		  q->definition_obj->rc->init_module) == FALSE){
3127		cur_obj = new_object_file();
3128		*cur_obj = *(q->definition_obj);
3129		cur_obj->dylib_module = q->mods +
3130		    q->definition_obj->rc->init_module;
3131		if(q->linked_modules != NULL)
3132		    q->linked_modules[q->definition_obj->rc->
3133				  init_module / 8] |= 1 <<
3134			q->definition_obj->rc->init_module % 8;
3135		if(whyload){
3136		    print_obj_name(cur_obj);
3137		    print("loaded for library initialization "
3138			  "routine\n");
3139		}
3140		merge_dylib_module_symbols(q);
3141	    }
3142	    q->definition_obj->init_module_loaded = TRUE;
3143	}
3144}
3145
3146/*
3147 * setup_sub_images() is called to set up the sub images that make up the
3148 * specified "primary" dynamic library.  If not all of its sub_umbrella's and
3149 * sub_librarys are set up then it will return FALSE and not set up the sub
3150 * images.  The caller will loop through all the libraries until all libraries
3151 * are setup.  This routine will return TRUE when it sets up the sub_images and
3152 * will also set the sub_images_setup field to TRUE in the specified library.
3153 */
3154static
3155enum bool
3156setup_sub_images(
3157struct dynamic_library *p)
3158{
3159    unsigned long i, j, k, l, n, max_libraries;
3160    struct mach_header *mh;
3161    struct load_command *lc, *load_commands;
3162    struct sub_umbrella_command *usub;
3163    struct sub_library_command *lsub;
3164    struct sub_framework_command *sub;
3165    struct dynamic_library **deps;
3166    char *sub_umbrella_name, *sub_library_name, *sub_framework_name;
3167    enum bool found;
3168
3169	max_libraries = 0;
3170	deps = p->dependent_images;
3171
3172	/*
3173	 * First see if this library has any sub-umbrellas or sub-librarys and
3174	 * that they have had their sub-images set up.  If not return FALSE and
3175	 * wait for this to be set up.  If so add the count of sub-images to
3176	 * max_libraries value which will be used for allocating the array for
3177	 * the sub-images of this library.
3178	 */
3179	mh = (struct mach_header *)(p->definition_obj->obj_addr);
3180	load_commands = (struct load_command *)((char *)mh +
3181						sizeof(struct mach_header));
3182	lc = load_commands;
3183	for(i = 0; i < mh->ncmds; i++){
3184	    switch(lc->cmd){
3185	    case LC_SUB_UMBRELLA:
3186		usub = (struct sub_umbrella_command *)lc;
3187		sub_umbrella_name = (char *)usub + usub->sub_umbrella.offset;
3188		for(j = 0; j < p->ndependent_images; j++){
3189		    if(deps[j]->umbrella_name != NULL &&
3190		       strcmp(sub_umbrella_name, deps[j]->umbrella_name) == 0){
3191			/*
3192			 * TODO: can't this logic (here and in our caller) hang
3193		         * if there is a circular loop?  And is that even
3194			 * possible to create?  See comments in our caller.
3195			 */
3196			if(deps[j]->sub_images_setup == FALSE)
3197			    return(FALSE);
3198			max_libraries += 1 + deps[j]->nsub_images;
3199		    }
3200		}
3201		break;
3202	    case LC_SUB_LIBRARY:
3203		lsub = (struct sub_library_command *)lc;
3204		sub_library_name = (char *)lsub + lsub->sub_library.offset;
3205		for(j = 0; j < p->ndependent_images; j++){
3206		    if(deps[j]->library_name != NULL &&
3207		       strcmp(sub_library_name, deps[j]->library_name) == 0){
3208			/*
3209			 * TODO: can't this logic (here and in our caller) hang
3210		         * if there is a circular loop?  And is that even
3211			 * possible to create?  See comments in our caller.
3212			 */
3213			if(deps[j]->sub_images_setup == FALSE)
3214			    return(FALSE);
3215			max_libraries += 1 + deps[j]->nsub_images;
3216		    }
3217		}
3218		break;
3219	    }
3220	    lc = (struct load_command *)((char *)lc + lc->cmdsize);
3221	}
3222
3223	/*
3224	 * Allocate the sub-images array of pointers to dynamic libraries that
3225	 * make up this "primary" library.  Allocate enough to handle the max.
3226	 */
3227	max_libraries += p->ndependent_images;
3228	p->sub_images = allocate(max_libraries *
3229				 sizeof(struct dynamic_library *));
3230	n = 0;
3231
3232	/*
3233	 * First add the dependent images which are sub-frameworks of this
3234	 * image to the sub images list.
3235	 */
3236	if(p->umbrella_name != NULL){
3237	    for(i = 0; i < p->ndependent_images; i++){
3238		mh = (struct mach_header *)(deps[i]->definition_obj->obj_addr);
3239		load_commands = (struct load_command *)((char *)mh +
3240						    sizeof(struct mach_header));
3241		lc = load_commands;
3242		for(j = 0; j < mh->ncmds; j++){
3243		    if(lc->cmd == LC_SUB_FRAMEWORK){
3244			sub = (struct sub_framework_command *)lc;
3245			sub_framework_name = (char *)sub + sub->umbrella.offset;
3246			if(p->umbrella_name != NULL &&
3247			   strcmp(sub_framework_name, p->umbrella_name) == 0){
3248			    p->sub_images[n++] = deps[i];
3249			    if(p->force_weak_dylib == TRUE)
3250				deps[i]->force_weak_dylib = TRUE;
3251			    goto next_dep;
3252			}
3253		    }
3254		    lc = (struct load_command *)((char *)lc + lc->cmdsize);
3255		}
3256next_dep:	;
3257	    }
3258	}
3259
3260	/*
3261	 * Second add the sub-umbrella's and sub-library's sub-images to the
3262	 * sub images list.
3263	 */
3264	mh = (struct mach_header *)p->definition_obj->obj_addr;
3265	load_commands = (struct load_command *)((char *)mh +
3266						sizeof(struct mach_header));
3267	lc = load_commands;
3268	for(i = 0; i < mh->ncmds; i++){
3269	    switch(lc->cmd){
3270	    case LC_SUB_UMBRELLA:
3271		usub = (struct sub_umbrella_command *)lc;
3272		sub_umbrella_name = (char *)usub + usub->sub_umbrella.offset;
3273		for(j = 0; j < p->ndependent_images; j++){
3274		    if(deps[j]->umbrella_name != NULL &&
3275		       strcmp(sub_umbrella_name, deps[j]->umbrella_name) == 0){
3276
3277			/* make sure this image is not already on the list */
3278			found = FALSE;
3279			for(l = 0; l < n; l++){
3280			    if(p->sub_images[l] == deps[j]){
3281				found = TRUE;
3282				break;
3283			    }
3284			}
3285			if(found == FALSE){
3286			    p->sub_images[n++] = deps[j];
3287			    if(p->force_weak_dylib == TRUE)
3288				deps[j]->force_weak_dylib = TRUE;
3289			}
3290
3291			for(k = 0; k < deps[j]->nsub_images; k++){
3292			    /* make sure this image is not already on the list*/
3293			    found = FALSE;
3294			    for(l = 0; l < n; l++){
3295				if(p->sub_images[l] == deps[j]->sub_images[k]){
3296				    found = TRUE;
3297				    break;
3298				}
3299			    }
3300			    if(found == FALSE)
3301				p->sub_images[n++] = deps[j]->sub_images[k];
3302			}
3303		    }
3304		}
3305		break;
3306	    case LC_SUB_LIBRARY:
3307		lsub = (struct sub_library_command *)lc;
3308		sub_library_name = (char *)lsub + lsub->sub_library.offset;
3309		for(j = 0; j < p->ndependent_images; j++){
3310		    if(deps[j]->library_name != NULL &&
3311		       strcmp(sub_library_name, deps[j]->library_name) == 0){
3312
3313			/* make sure this image is not already on the list */
3314			found = FALSE;
3315			for(l = 0; l < n; l++){
3316			    if(p->sub_images[l] == deps[j]){
3317				found = TRUE;
3318				break;
3319			    }
3320			}
3321			if(found == FALSE)
3322			    p->sub_images[n++] = deps[j];
3323
3324			for(k = 0; k < deps[j]->nsub_images; k++){
3325			    /* make sure this image is not already on the list*/
3326			    found = FALSE;
3327			    for(l = 0; l < n; l++){
3328				if(p->sub_images[l] == deps[j]->sub_images[k]){
3329				    found = TRUE;
3330				    break;
3331				}
3332			    }
3333			    if(found == FALSE)
3334				p->sub_images[n++] = deps[j]->sub_images[k];
3335			}
3336		    }
3337		}
3338		break;
3339	    }
3340	    lc = (struct load_command *)((char *)lc + lc->cmdsize);
3341	}
3342	p->nsub_images = n;
3343	p->sub_images_setup = TRUE;
3344	return(TRUE);
3345}
3346
3347/*
3348 * prebinding_check_for_dylib_override_symbols() checks to make sure that no
3349 * symbols are being overridden in a dependent library if prebinding is to
3350 * be done.  If a symbol is overridden prebinding is disabled and a warning
3351 * is printed.
3352 */
3353__private_extern__
3354void
3355prebinding_check_for_dylib_override_symbols(
3356void)
3357{
3358    unsigned long i;
3359    struct merged_symbol_list *merged_symbol_list;
3360    struct merged_symbol *merged_symbol;
3361
3362	if(prebinding == TRUE){
3363	    for(merged_symbol_list = merged_symbol_root == NULL ? NULL :
3364				     merged_symbol_root->list;
3365		merged_symbol_list != NULL;
3366		merged_symbol_list = merged_symbol_list->next){
3367		for(i = 0; i < merged_symbol_list->used; i++){
3368		    merged_symbol = merged_symbol_list->symbols[i];
3369		    if((merged_symbol->nlist.n_type & N_PEXT) == N_PEXT)
3370			continue;
3371		    check_dylibs_for_definition(merged_symbol, TRUE, FALSE);
3372		}
3373	    }
3374	}
3375}
3376
3377/*
3378 * twolevel_namespace_check_for_unused_dylib_symbols() checks dylibs to make
3379 * sure the user sees a warning about unused symbols defined in a dylib that
3380 * where another symbol of the same name is being used from some other object
3381 * or dynamic library.
3382 */
3383__private_extern__
3384void
3385twolevel_namespace_check_for_unused_dylib_symbols(
3386void)
3387{
3388    unsigned long i;
3389    struct merged_symbol_list *merged_symbol_list;
3390    struct merged_symbol *merged_symbol;
3391
3392	for(merged_symbol_list = merged_symbol_root == NULL ? NULL :
3393				 merged_symbol_root->list;
3394	    merged_symbol_list != NULL;
3395	    merged_symbol_list = merged_symbol_list->next){
3396	    for(i = 0; i < merged_symbol_list->used; i++){
3397		merged_symbol = merged_symbol_list->symbols[i];
3398		if((merged_symbol->nlist.n_type & N_PEXT) == N_PEXT)
3399		    continue;
3400		check_dylibs_for_definition(merged_symbol, FALSE, TRUE);
3401	    }
3402	}
3403}
3404
3405/*
3406 * check_dylibs_for_definition() checks to see if the merged symbol is defined
3407 * in any of the dependent dynamic shared libraries.
3408 *
3409 * If prebind_check is TRUE and the symbol is defined in a dylib and also
3410 * refernced a warning is printed, prebinding is disabled and the symbols are
3411 * traced.
3412 *
3413 * If twolevel_namespace_check is TRUE and the symbol is defined in a dylib the
3414 * a warning about an unused defintion is printed and the symbols are traced.
3415 */
3416static
3417void
3418check_dylibs_for_definition(
3419struct merged_symbol *merged_symbol,
3420enum bool prebind_check,
3421enum bool twolevel_namespace_check)
3422{
3423    struct dynamic_library *p;
3424    struct dylib_table_of_contents *toc;
3425    static enum bool printed_override, printed_unused, merged_symbol_printed;
3426
3427    printed_override = FALSE;
3428    printed_unused = FALSE;
3429    merged_symbol_printed = FALSE;
3430
3431	for(p = dynamic_libs; p != NULL; p = p->next){
3432	    if(p->type == DYLIB){
3433		/*
3434		 * If this symbol is defined in the this dylib it is not an
3435		 * overridden symbol.
3436		 */
3437		if(merged_symbol->defined_in_dylib == TRUE &&
3438		   p->definition_obj->file_name ==
3439		   merged_symbol->definition_object->file_name)
3440		    continue;
3441
3442		bsearch_strings = p->strings;
3443		bsearch_symbols = p->symbols;
3444
3445		toc = bsearch(merged_symbol->nlist.n_un.n_name,
3446			      p->tocs, p->definition_obj->dysymtab->ntoc,
3447			      sizeof(struct dylib_table_of_contents),
3448			      (int (*)(const void *, const void *))
3449				dylib_bsearch);
3450		if(toc != NULL){
3451		    if(prebind_check == TRUE){
3452			/*
3453			 * There is a module that defineds this symbol.  If this
3454			 * symbol is also referenced by the libraries then we
3455			 * can't prebind.
3456			 */
3457			if(check_dylibs_for_reference(merged_symbol) == TRUE){
3458			    if(printed_override == FALSE){
3459				if(ld_trace_prebinding_disabled == TRUE)
3460				    ld_trace("[Logging for XBS] "
3461					     "prebinding disabled for %s because "
3462					     "of symbols overridden in dependent "
3463					     "dynamic shared libraries\n",
3464					     final_output != NULL ? final_output :
3465					     outputfile);
3466				warning("prebinding disabled because of symbols"
3467				   " overridden in dependent dynamic shared "
3468				   "libraries:");
3469				printed_override = TRUE;
3470			    }
3471			    trace_merged_symbol(merged_symbol);
3472			    printf("%s(%s) definition of %s\n",
3473				   p->definition_obj->file_name,
3474				   p->strings +
3475					p->mods[toc->module_index].module_name,
3476				   merged_symbol->nlist.n_un.n_name);
3477			    prebinding = FALSE;
3478			}
3479		    }
3480		    if(twolevel_namespace_check == TRUE){
3481			/*
3482			 * If this module was loaded then warnings about
3483			 * multiply defined symbols in it have previously been
3484			 * flagged.
3485			 */
3486			if(is_dylib_module_loaded(p->mods + toc->module_index)
3487			   == TRUE)
3488			    continue;
3489			if(printed_unused == FALSE){
3490			    if(multiply_defined_unused_flag ==
3491			       MULTIPLY_DEFINED_ERROR)
3492				error("unused multiple definitions of symbol "
3493				      "%s", merged_symbol->nlist.n_un.n_name);
3494			    else
3495				warning("unused multiple definitions of symbol "
3496					"%s", merged_symbol->nlist.n_un.n_name);
3497			    printed_unused = TRUE;
3498			}
3499			/*
3500			 * First print the symbol that is being used if not
3501			 * already printed.
3502			 */
3503			if(merged_symbol_printed == FALSE){
3504			    trace_merged_symbol(merged_symbol);
3505			    merged_symbol_printed = TRUE;
3506			}
3507			printf("%s(%s) unused definition of %s\n",
3508			       p->definition_obj->file_name,
3509			       p->strings +
3510				    p->mods[toc->module_index].module_name,
3511			       merged_symbol->nlist.n_un.n_name);
3512		    }
3513		}
3514	    }
3515	}
3516}
3517
3518/*
3519 * check_dylibs_for_reference() checks the dependent dynamic shared libraries
3520 * to see if the specified merged symbol is referenced in a flat namespace
3521 * library.  If it is TRUE is returned else FALSE is returned.
3522 */
3523static
3524enum bool
3525check_dylibs_for_reference(
3526struct merged_symbol *merged_symbol)
3527{
3528    struct dynamic_library *p;
3529    struct dylib_table_of_contents *toc;
3530    struct nlist *symbol;
3531    struct dylib_reference *dylib_references;
3532    unsigned long i, symbol_index;
3533    struct mach_header *mh;
3534
3535	for(p = dynamic_libs; p != NULL; p = p->next){
3536	    if(p->type == DYLIB){
3537		/*
3538		 * If we are not building an output file that forces flat name
3539		 * space and this library is a two-level namespace library then
3540		 * all references to undefined symbols are to specific
3541		 * libraries and can't be overridden.
3542		 */
3543		mh = (struct mach_header *)(p->definition_obj->obj_addr);
3544		if(force_flat_namespace == FALSE &&
3545		   (mh->flags & MH_TWOLEVEL) == MH_TWOLEVEL)
3546		    continue;
3547		/*
3548		 * See if this symbol appears at all (defined or undefined)
3549		 * in this library.
3550		 */
3551		bsearch_strings = p->strings;
3552		bsearch_symbols = p->symbols;
3553		toc = bsearch(merged_symbol->nlist.n_un.n_name,
3554			      p->tocs, p->definition_obj->dysymtab->ntoc,
3555			      sizeof(struct dylib_table_of_contents),
3556			      (int (*)(const void *, const void *))
3557				dylib_bsearch);
3558		if(toc != NULL){
3559		    symbol_index = toc->symbol_index;
3560		}
3561		else{
3562		    symbol = bsearch(merged_symbol->nlist.n_un.n_name,
3563			     bsearch_symbols +
3564				p->definition_obj->dysymtab->iundefsym,
3565			     p->definition_obj->dysymtab->nundefsym,
3566			     sizeof(struct nlist),
3567			     (int (*)(const void *,const void *))nlist_bsearch);
3568		    if(symbol == NULL)
3569			continue;
3570		    symbol_index = symbol - bsearch_symbols;
3571		}
3572		/*
3573		 * The symbol appears in this library.  Now see if it is
3574		 * referenced by a module in the library.
3575		 */
3576		dylib_references = (struct dylib_reference *)
3577		    (p->definition_obj->obj_addr +
3578		     p->definition_obj->dysymtab->extrefsymoff);
3579		for(i = 0; i < p->definition_obj->dysymtab->nextrefsyms; i++){
3580		    if(dylib_references[i].isym == symbol_index &&
3581		       (dylib_references[i].flags ==
3582			    REFERENCE_FLAG_UNDEFINED_NON_LAZY ||
3583		        dylib_references[i].flags ==
3584			    REFERENCE_FLAG_UNDEFINED_LAZY))
3585		    return(TRUE);
3586		}
3587	    }
3588	}
3589	return(FALSE);
3590}
3591
3592/*
3593 * open_dylib() attempts to open the dynamic library specified by the pointer
3594 * to the dynamic_library structure.  This is only called for dependent
3595 * libraries found in the object loaded or in other dynamic libraries.  Since
3596 * this is only used for undefined checking and prebinding it is not fatal if
3597 * the library can't be opened.  But if it can't be opened and undefined
3598 * checking or prebinding is to be done a warning is issued.
3599 */
3600static
3601enum bool
3602open_dylib(
3603struct dynamic_library *p)
3604{
3605    unsigned long i, file_size;
3606    char *colon, *file_name, *dylib_name, *file_addr;
3607    int fd;
3608    struct stat stat_buf;
3609    kern_return_t r;
3610    struct fat_header *fat_header;
3611    struct mach_header *mh;
3612    struct load_command *lc;
3613    struct dylib_command *dl;
3614
3615	/*
3616	 * First see if there is a -dylib_file option for this dylib and if so
3617	 * use that as the file name to open for the dylib.
3618	 */
3619	for(i = 0; i < ndylib_files; i++){
3620	    colon = strchr(dylib_files[i], ':');
3621	    *colon = '\0';
3622	    if(strcmp(p->dylib_name, dylib_files[i]) == 0){
3623		p->dylib_file = dylib_files[i];
3624		p->file_name = colon + 1;
3625		*colon = ':';
3626		break;
3627	    }
3628	    *colon = ':';
3629	}
3630#if 0
3631	/*
3632	 * It has been determined that this warning is distracting.  Even though
3633	 * the user may want to be alerted that this library is being included
3634	 * indirectly.  It has been determined this rarely a problem.  So when
3635	 * it is a problem we will just hope the user is smart enought to figure
3636	 * it out without any clue.
3637	 */
3638	if(p->dylib_file == NULL &&
3639	   (undefined_flag != UNDEFINED_SUPPRESS ||
3640	    prebinding == TRUE)){
3641	    if(p->definition_obj->ar_hdr != NULL)
3642		warning("using file: %s for reference to dynamic shared library"
3643			" from: %s(%.*s) because no -dylib_file specified",
3644			p->dylib_name, p->definition_obj->file_name,
3645			(int)p->definition_obj->ar_name_size,
3646			p->definition_obj->ar_name);
3647
3648	    else
3649		warning("using file: %s for reference to dynamic shared library"
3650			" from: %s because no -dylib_file specified",
3651			p->dylib_name, p->definition_obj->file_name);
3652	}
3653#endif
3654
3655	/*
3656	 * Try to open the dynamic library.  If it can't be opened it is only
3657	 * a warning if undefined checking or prebinding is to be done.  Once
3658	 * the file is opened sucessfully then any futher problems are treated
3659	 * as errors.
3660	 */
3661	if(p->dylib_file != NULL)
3662	    file_name = p->file_name;
3663	else{
3664	    if(executable_path != NULL &&
3665	       strncmp(p->dylib_name, "@executable_path",
3666                       sizeof("@executable_path") - 1) == 0){
3667		file_name = mkstr(executable_path,
3668				  p->dylib_name + sizeof("@executable_path") -1,
3669				  NULL);
3670	    }
3671	    else{
3672		file_name = p->dylib_name;
3673	    }
3674	}
3675	if((fd = open(file_name, O_RDONLY, 0)) == -1){
3676	    if(undefined_flag != UNDEFINED_SUPPRESS){
3677		system_warning("can't open dynamic library: %s referenced "
3678		    "from: %s (checking for undefined symbols may be affected)",
3679		    file_name, p->definition_obj->file_name);
3680	    }
3681	    return(FALSE);
3682	}
3683
3684	/*
3685	 * Now that the file_name has been determined and opened get it into
3686	 * memory by mapping it.
3687	 */
3688	if(fstat(fd, &stat_buf) == -1){
3689	    system_error("can't stat dynamic library file: %s", file_name);
3690	    close(fd);
3691	    return(FALSE);
3692	}
3693	file_size = stat_buf.st_size;
3694	/*
3695	 * For some reason mapping files with zero size fails so it has to
3696	 * be handled specially.
3697	 */
3698	if(file_size == 0){
3699	    error("file: %s is empty (not a dynamic library)", file_name);
3700	    close(fd);
3701	    return(FALSE);
3702	}
3703	if((r = map_fd((int)fd, (vm_offset_t)0, (vm_offset_t *)&file_addr,
3704	    (boolean_t)TRUE, (vm_size_t)file_size)) != KERN_SUCCESS){
3705	    close(fd);
3706	    mach_fatal(r, "can't map dynamic library file: %s", file_name);
3707	}
3708	close(fd);
3709
3710	/*
3711	 * This file must be a dynamic library (it can be fat too).
3712	 */
3713	cur_obj = NULL;
3714	if(sizeof(struct fat_header) > file_size){
3715	    error("truncated or malformed dynamic library file: %s (file size "
3716		  "too small to be a dynamic library)", file_name);
3717	    return(FALSE);
3718	}
3719	fat_header = (struct fat_header *)file_addr;
3720#ifdef __BIG_ENDIAN__
3721	if(fat_header->magic == FAT_MAGIC)
3722#endif /* __BIG_ENDIAN__ */
3723#ifdef __LITTLE_ENDIAN__
3724	if(fat_header->magic == SWAP_LONG(FAT_MAGIC))
3725#endif /* __LITTLE_ENDIAN__ */
3726	{
3727	    pass1_fat(file_name, file_addr, file_size, FALSE, TRUE, FALSE,
3728		      FALSE);
3729	}
3730	else{
3731	    pass1_object(file_name, file_addr, file_size, FALSE, FALSE, TRUE,
3732			 FALSE, FALSE);
3733	}
3734	if(errors)
3735	    return(FALSE);
3736	if(cur_obj == NULL || cur_obj->dylib == FALSE)
3737	    return(FALSE);
3738
3739	dylib_name = NULL;
3740	mh = (struct mach_header *)cur_obj->obj_addr;
3741	lc = (struct load_command *)((char *)cur_obj->obj_addr +
3742				     sizeof(struct mach_header));
3743	for(i = 0; i < mh->ncmds; i++){
3744	    if(lc->cmd == LC_ID_DYLIB){
3745		dl = (struct dylib_command *)lc;
3746		dylib_name = (char *)dl + dl->dylib.name.offset;
3747#ifdef notdef
3748		if(strcmp(p->dylib_name, dylib_name) != 0){
3749		    error("wrong dynamic library: %s (the name in the "
3750			  "LC_ID_DYLIB command (%s) is not %s)", file_name,
3751			  dylib_name, p->dylib_name);
3752		}
3753#endif
3754		p->dl = dl;
3755		p->definition_obj = cur_obj;
3756		break;
3757	    }
3758	    lc = (struct load_command *)((char *)lc + lc->cmdsize);
3759	}
3760	return(TRUE);
3761}
3762
3763/*
3764 * set_sub_frameworks_ordinals() sets the library ordinal for other libraries
3765 * that are sub-frameworks of the specified dynamic library.  If any ordinals
3766 * are set then TRUE is returned else FALSE is returned.
3767 */
3768static
3769enum bool
3770set_sub_frameworks_ordinals(
3771struct dynamic_library *umbrella)
3772{
3773    enum bool set_some_ordinals;
3774    struct dynamic_library *p;
3775    unsigned long i;
3776    struct mach_header *mh;
3777    struct load_command *lc;
3778    struct sub_framework_command *sub;
3779
3780	set_some_ordinals = FALSE;
3781	for(p = dynamic_libs; p != NULL; p = p->next){
3782	    if(p->type != DYLIB)
3783		continue;
3784	    /*
3785	     * If this library's ordinal is not set the see if it has an
3786	     * LC_SUB_FRAMEWORK command with the same name as the umbrella
3787	     * library.
3788	     */
3789	    if(p->definition_obj->library_ordinal == 0){
3790		mh = (struct mach_header *)p->definition_obj->obj_addr;
3791		lc = (struct load_command *)
3792			((char *)p->definition_obj->obj_addr +
3793				sizeof(struct mach_header));
3794		for(i = 0; i < mh->ncmds; i++){
3795		    if(lc->cmd == LC_SUB_FRAMEWORK){
3796			sub = (struct sub_framework_command *)lc;
3797			if(strcmp((char *)sub + sub->umbrella.offset,
3798				  umbrella->umbrella_name) == 0){
3799			    p->definition_obj->library_ordinal =
3800				umbrella->definition_obj->library_ordinal;
3801			    set_isub_image(p, p);
3802			    set_some_ordinals = TRUE;
3803			    break;
3804			}
3805		    }
3806		    lc = (struct load_command *)((char *)lc + lc->cmdsize);
3807		}
3808	    }
3809	}
3810	return(set_some_ordinals);
3811}
3812
3813/*
3814 * set_sub_umbrella_sub_library_ordinal() sets the library ordinal for the
3815 * specified dynamic library if it is a sub-umbrella or a sub-library of another
3816 * dynamic library who's library ordinal is set.  If the ordinal is set then
3817 * TRUE is returned else FALSE is returned.
3818 */
3819static
3820enum bool
3821set_sub_umbrella_sub_library_ordinal(
3822struct dynamic_library *sub)
3823{
3824    struct dynamic_library *p;
3825    unsigned long i;
3826    struct mach_header *mh;
3827    struct load_command *lc;
3828    struct sub_umbrella_command *usub;
3829    struct sub_library_command *lsub;
3830
3831	for(p = dynamic_libs; p != NULL; p = p->next){
3832	    if(p->type != DYLIB)
3833		continue;
3834	    /*
3835	     * If this library's ordinal is set the see if it has an
3836	     * LC_SUB_UMBRELLA or LC_SUB_LIBRARY command with the same name as
3837	     * the sub library.
3838	     */
3839	    if(p->definition_obj->library_ordinal != 0){
3840		mh = (struct mach_header *)p->definition_obj->obj_addr;
3841		lc = (struct load_command *)
3842			((char *)p->definition_obj->obj_addr +
3843				sizeof(struct mach_header));
3844		for(i = 0; i < mh->ncmds; i++){
3845		    if(lc->cmd == LC_SUB_UMBRELLA){
3846			usub = (struct sub_umbrella_command *)lc;
3847			if(sub->umbrella_name != NULL &&
3848			   strcmp((char *)usub + usub->sub_umbrella.offset,
3849				  sub->umbrella_name) == 0){
3850			    sub->definition_obj->library_ordinal =
3851				p->definition_obj->library_ordinal;
3852			    set_isub_image(p, sub);
3853			    return(TRUE);
3854			}
3855		    }
3856		    else if(lc->cmd == LC_SUB_LIBRARY){
3857			lsub = (struct sub_library_command *)lc;
3858			if(sub->library_name != NULL &&
3859			   strcmp((char *)lsub + lsub->sub_library.offset,
3860				  sub->library_name) == 0){
3861			    sub->definition_obj->library_ordinal =
3862				p->definition_obj->library_ordinal;
3863			    set_isub_image(p, sub);
3864			    return(TRUE);
3865			}
3866		    }
3867		    lc = (struct load_command *)((char *)lc + lc->cmdsize);
3868		}
3869	    }
3870	}
3871	return(FALSE);
3872}
3873
3874/*
3875 * set_isub_image() sets the isub_image of the specified sub dynamic library to
3876 * the index into the sub_images of the specified dynamic library p.
3877 */
3878static
3879void
3880set_isub_image(
3881struct dynamic_library *p,
3882struct dynamic_library *sub)
3883{
3884    struct dynamic_library *q;
3885    unsigned long j;
3886
3887	/*
3888	 * Find the first library in the list with this
3889	 * ordinal which is the primary library.  Then walk
3890	 * the primary library's sub_images to figure out
3891	 * what the sub_image index is for this library.
3892	 */
3893	for(q = dynamic_libs; q != NULL; q = q->next){
3894	    if(q->type != DYLIB)
3895		continue;
3896	    if(q->definition_obj->library_ordinal ==
3897	       p->definition_obj->library_ordinal){
3898		for(j = 0; j < q->nsub_images; j++){
3899		    if(q->sub_images[j] == sub){
3900			sub->definition_obj->isub_image = j + 1;
3901			return;
3902		    }
3903		}
3904	    }
3905	}
3906}
3907
3908/*
3909 * add_dynamic_lib() adds a library to the list of specified
3910 * libraries.  A specified library is a library that is referenced from the
3911 * object files loaded.  It does not include libraries referenced from dynamic
3912 * libraries.  This returns a pointer to the dynamic_library struct for the
3913 * dylib_name specified in the dylib_command (or a new dynamic_library struct
3914 * for archive types).
3915 */
3916__private_extern__
3917struct dynamic_library *
3918add_dynamic_lib(
3919enum library_type type,
3920struct dylib_command *dl,
3921struct object_file *definition_obj)
3922{
3923    struct dynamic_library *p, *q;
3924    char *dylib_name;
3925
3926	dylib_name = NULL;
3927	/*
3928	 * If this is a dynamic shared library check to see if it is all ready
3929	 * on the list.
3930	 */
3931	if(type == DYLIB){
3932	    dylib_name = (char *)dl + dl->dylib.name.offset;
3933	    /*
3934	     * See if this library is already on the list of specified libraries
3935	     * and if so merge the two.  If only one is an LC_ID_DYLIB then use
3936	     * that one.
3937	     */
3938	    for(p = dynamic_libs; p != NULL; p = p->next){
3939		if(p->type == DYLIB &&
3940		   strcmp(p->dylib_name, dylib_name) == 0){
3941		    if(p->dl->cmd == LC_ID_DYLIB){
3942			/*
3943			 * If the new one is also a LC_ID_DYLIB use the one
3944			 * with the highest compatiblity number.  Else if the
3945			 * new one is just an LC_LOAD_DYLIB, LC_LOAD_WEAK_DYLIB
3946			 * or LC_REEXPORT_DYLIB ignore it and use the one that
3947			 * is on the list which is a LC_ID_DYLIB.
3948			 */
3949			if(dl->cmd == LC_ID_DYLIB){
3950			   if(dl->dylib.compatibility_version >
3951			      p->dl->dylib.compatibility_version){
3952				p->dylib_name = dylib_name;
3953				p->dl = dl;
3954				p->definition_obj = definition_obj;
3955			    }
3956			}
3957		    }
3958		    else{
3959			if(dl->cmd == LC_ID_DYLIB){
3960			    p->dylib_name = dylib_name;
3961			    p->dl = dl;
3962			    p->definition_obj = definition_obj;
3963			}
3964		    }
3965		    return(p);
3966		}
3967	    }
3968	}
3969	/*
3970	 * If this library is not the lists of libraries or is an archive
3971	 * library.  Create a new dynamic_library struct for it.  Add it to the
3972	 * end of the list of specified libraries.  Then return a pointer new
3973	 * dynamic_library struct.
3974	 */
3975	p = allocate(sizeof(struct dynamic_library));
3976	memset(p, '\0', sizeof(struct dynamic_library));
3977	if(dynamic_libs == NULL)
3978	    dynamic_libs = p;
3979	else{
3980	    for(q = dynamic_libs; q->next != NULL; q = q->next)
3981		;
3982	    q->next = p;
3983	}
3984
3985	if(type == DYLIB){
3986	    p->type = DYLIB;
3987	    p->dylib_name = dylib_name;
3988	    p->dl = dl;
3989	    p->definition_obj = definition_obj;
3990	    /*
3991	     * If the environment variable NEXT_ROOT is set then the file_name
3992	     * for this library prepended with NEXT_ROOT.  Basicly faking out
3993	     * as if a -dylib_file argument was seen.
3994	     */
3995	    if(next_root != NULL && *dylib_name == '/'){
3996		p->file_name = allocate(strlen(next_root) +
3997				      strlen(dylib_name) + 1);
3998		strcpy(p->file_name, next_root);
3999		strcat(p->file_name, dylib_name);
4000		p->dylib_file = p->dylib_name;
4001	    }
4002	}
4003
4004	if(type == BUNDLE_LOADER){
4005	    p->type = BUNDLE_LOADER;
4006	    p->dylib_name = NULL;
4007	    p->dl = NULL;
4008	    p->definition_obj = definition_obj;
4009	}
4010	return(p);
4011}
4012
4013/*
4014 * Function for bsearch() for finding a symbol name in a dylib table of
4015 * contents.
4016 */
4017__private_extern__
4018int
4019dylib_bsearch(
4020const char *symbol_name,
4021const struct dylib_table_of_contents *toc)
4022{
4023	return(strcmp(symbol_name,
4024		      bsearch_strings +
4025		      bsearch_symbols[toc->symbol_index].n_un.n_strx));
4026}
4027
4028/*
4029 * Function for bsearch() for finding a symbol name in the sorted list of
4030 * undefined symbols.
4031 */
4032static
4033int
4034nlist_bsearch(
4035const char *symbol_name,
4036const struct nlist *symbol)
4037{
4038	return(strcmp(symbol_name, bsearch_strings + symbol->n_un.n_strx));
4039}
4040#endif /* !defined(RLD) */
4041
4042/*
4043 * Function for bsearch() for finding a symbol name in a ranlib table of
4044 * contents.
4045 */
4046static
4047int
4048ranlib_bsearch(
4049const char *symbol_name,
4050const struct ranlib *ran)
4051{
4052	return(strcmp(symbol_name, bsearch_strings + ran->ran_un.ran_strx));
4053}
4054#endif /* !defined(SA_RLD) && !(defined(KLD) && defined(__STATIC__)) */
4055
4056/*
4057 * merge() merges all the global information from the cur_obj into the merged
4058 * data structures for the output object file to be built from.
4059 */
4060__private_extern__
4061void
4062merge(
4063enum bool dylib_only,
4064enum bool bundle_loader,
4065enum bool force_weak)
4066{
4067    unsigned long previous_errors;
4068
4069	/*
4070	 * save the previous errors and only return out of here if something
4071	 * we do in here gets an error.
4072	 */
4073	previous_errors = errors;
4074	errors = 0;
4075
4076	/* print the object file name if tracing */
4077	if(trace){
4078	    print_obj_name(cur_obj);
4079	    print("\n");
4080	}
4081
4082	/* check the header and load commands of the object file */
4083	check_cur_obj(dylib_only, bundle_loader);
4084	if(errors)
4085	    goto merge_return;
4086
4087	/* if this was called to via an open_dylib() we are done */
4088	if(dylib_only == TRUE)
4089	    goto merge_return;
4090
4091#ifndef RLD
4092	/*
4093	 * if this is the -bundle_loader argument then put it on the list
4094	 * of dynamic libraries where it will be searched.
4095	 */
4096	if(bundle_loader){
4097	    /* If this object file has no symbols then don't add it */
4098	    if(cur_obj->symtab != NULL)
4099		(void)add_dynamic_lib(BUNDLE_LOADER, NULL, cur_obj);
4100	    goto merge_return;
4101	}
4102#endif /* !defined(RLD) */
4103
4104	/* if this object has any fixed VM shared library stuff merge it */
4105	if(cur_obj->fvmlib_stuff){
4106#ifndef RLD
4107	    merge_fvmlibs();
4108	    if(errors)
4109		goto merge_return;
4110#else /* defined(RLD) */
4111	    if(cur_obj != base_obj){
4112		error_with_cur_obj("can't dynamicly load fixed VM shared "
4113				   "library");
4114		goto merge_return;
4115	    }
4116#endif /* defined(RLD) */
4117	}
4118
4119	/* if this object has any dynamic shared library stuff merge it */
4120	if(cur_obj->dylib_stuff){
4121#ifndef RLD
4122	    merge_dylibs(force_weak);
4123	    if(errors)
4124		goto merge_return;
4125	    if(cur_obj->dylib)
4126		goto merge_return;
4127	    if(cur_obj->dylinker)
4128		goto merge_return;
4129#else /* defined(RLD) */
4130	    if(cur_obj != base_obj){
4131		error_with_cur_obj("can't used dynamic libraries or dynamic "
4132		    "linker with rld based interfaces");
4133		goto merge_return;
4134	    }
4135#endif /* defined(RLD) */
4136	}
4137
4138#ifndef KLD
4139	/* read the DWARF information if any */
4140	if(strip_level < STRIP_DEBUG)
4141	  read_dwarf_info();
4142#endif
4143
4144	/* merged it's sections */
4145	merge_sections();
4146	if(errors)
4147	    goto merge_return;
4148
4149	/* merged it's symbols */
4150	merge_symbols();
4151	if(errors)
4152	    goto merge_return;
4153
4154merge_return:
4155	errors += previous_errors;
4156}
4157
4158/*
4159 * check_cur_obj() checks to see if the cur_obj object file is really an object
4160 * file and that all the offset and sizes in the headers are within the memory
4161 * the object file is mapped in.  This allows the rest of the code in the link
4162 * editor to use the offsets and sizes in the headers without bounds checking.
4163 *
4164 * Since this is making a pass through the headers a number of things are filled
4165 * in in the object structrure for this object file including: the symtab field,
4166 * the dysymtab field, the section_maps and nsection_maps fields (this routine
4167 * allocates the section_map structures and fills them in too), the fvmlib_
4168 * stuff field is set if any SG_FVMLIB segments or LC_LOADFVMLIB commands are
4169 * seen and the dylib_stuff field is set if the file is a MH_DYLIB or
4170 * MH_DYLIB_STUB type and has a LC_ID_DYLIB command or a LC_LOAD_DYLIB,
4171 * LC_LOAD_WEAK_DLIB or LC_REEXPORT_DYLIB command is seen.
4172 */
4173static
4174void
4175check_cur_obj(
4176enum bool dylib_only,
4177enum bool bundle_loader)
4178{
4179    unsigned long i, j, section_type;
4180    uint32_t magic;
4181    struct mach_header *mh;
4182    struct mach_header_64 *mh64;
4183    struct load_command l, *lc, *load_commands;
4184    struct segment_command *sg;
4185    struct section *s;
4186    struct symtab_command *st;
4187    struct dysymtab_command *dyst;
4188    struct routines_command *rc;
4189    struct symseg_command *ss;
4190    struct fvmlib_command *fl;
4191    struct dylib_command *dl, *dlid;
4192    struct dylinker_command *dyld, *dyldid;
4193    struct sub_framework_command *sub;
4194    struct sub_umbrella_command *usub;
4195    struct sub_library_command *lsub;
4196    struct sub_client_command *csub;
4197    struct twolevel_hints_command *hints;
4198    struct prebind_cksum_command *cs;
4199    struct uuid_command *uuid;
4200    char *fvmlib_name, *dylib_name, *dylib_id_name, *dylinker_name,
4201	 *umbrella_name, *sub_umbrella_name, *sub_library_name,*sub_client_name;
4202    cpu_subtype_t new_cpusubtype;
4203    const char *new_arch, *prev_arch;
4204    const struct arch_flag *family_arch_flag;
4205    uint32_t *indirect_symtab;
4206    struct dylib_table_of_contents *tocs;
4207    struct dylib_module *mods;
4208    struct dylib_reference *refs;
4209#ifndef RLD
4210    enum bool is_framework, allowable_client;
4211    char *short_name, *has_suffix, *this_client_name;
4212#endif
4213
4214    static const struct symtab_command empty_symtab = { 0 };
4215    static const struct dysymtab_command empty_dysymtab = { 0 };
4216
4217#ifdef KLD
4218	memset(&output_uuid_info, '\0', sizeof(struct uuid_info));
4219#endif
4220	/* check to see the mach_header is valid */
4221	if(sizeof(struct mach_header) > cur_obj->obj_size){
4222	    error_with_cur_obj("truncated or malformed object (mach header "
4223			       "extends past the end of the file)");
4224	    return;
4225	}
4226
4227	magic = *((uint32_t *)cur_obj->obj_addr);
4228
4229	if(magic ==  MH_MAGIC ||
4230	   magic == SWAP_LONG(MH_MAGIC)){
4231	  mh = (struct mach_header *)cur_obj->obj_addr;
4232	  if(magic == MH_MAGIC){
4233	    cur_obj->swapped = FALSE;
4234	  }
4235	  else{
4236	    cur_obj->swapped = TRUE;
4237	    swap_mach_header(mh, host_byte_sex);
4238	  }
4239	}
4240	else if(cur_obj->obj_size >= sizeof(struct mach_header_64) &&
4241		(magic == MH_MAGIC_64 ||
4242		 magic == SWAP_LONG(MH_MAGIC_64))){
4243
4244	  mh64 = (struct mach_header_64 *)cur_obj->obj_addr;
4245	  if(magic == MH_MAGIC_64){
4246	    cur_obj->swapped = FALSE;
4247	  }
4248	  else{
4249	    cur_obj->swapped = TRUE;
4250        swap_mach_header_64(mh64, host_byte_sex);
4251	  }
4252
4253	  /* If no architecture has been explicitly given, and
4254	   *  this is the first object seen, set up arch_flag
4255	   *  without interrogating the object file further
4256	   */
4257	  if(!arch_flag.cputype) {
4258		family_arch_flag = get_arch_family_from_cputype(mh64->cputype);
4259		if(family_arch_flag == NULL){
4260		    error_with_cur_obj("cputype (%d) unknown (file not loaded)",
4261			 mh64->cputype);
4262		    return;
4263		}
4264		arch_flag.cputype = mh64->cputype;
4265		if(force_cpusubtype_ALL == TRUE)
4266		    arch_flag.cpusubtype = family_arch_flag->cpusubtype;
4267		else
4268		    arch_flag.cpusubtype = mh64->cpusubtype;
4269	  }
4270
4271	  return;
4272	}
4273	else{
4274	  if(no_arch_warnings != TRUE)
4275	    error_with_cur_obj("bad magic number (not a Mach-O file)");
4276	  return;
4277	}
4278	if(mh->cputype != 0){
4279	    if(target_byte_sex == UNKNOWN_BYTE_SEX){
4280		if(cur_obj->swapped == TRUE)
4281		    target_byte_sex = host_byte_sex == BIG_ENDIAN_BYTE_SEX ?
4282    			LITTLE_ENDIAN_BYTE_SEX : BIG_ENDIAN_BYTE_SEX;
4283		else
4284		    target_byte_sex = host_byte_sex;
4285	    }
4286	    /*
4287	     * If for this cputype we are to always output the ALL cpusubtype
4288	     * then set force_cpusubtype_ALL.
4289	     */
4290	    if(force_cpusubtype_ALL_for_cputype(mh->cputype) == TRUE)
4291		force_cpusubtype_ALL = TRUE;
4292	    /*
4293	     * If we have previous loaded something or an -arch flag was
4294	     * specified something so make sure the cputype of this object
4295	     * matches (the case the architecture has been previous selected).
4296	     */
4297	    if(arch_flag.cputype){
4298		if(arch_flag.cputype != mh->cputype){
4299		    new_arch = get_arch_name_from_types(mh->cputype,
4300						        mh->cpusubtype);
4301		    prev_arch = get_arch_name_from_types(arch_flag.cputype,
4302						         arch_flag.cpusubtype);
4303		    if(no_arch_warnings == TRUE)
4304			return;
4305		    if(arch_flag.name != NULL){
4306			if(arch_errors_fatal == TRUE){
4307			    error_with_cur_obj("cputype (%d, architecture %s) "
4308				"does not match cputype (%d) for specified "
4309				"-arch flag: %s", mh->cputype, new_arch,
4310				arch_flag.cputype, arch_flag.name);
4311			}
4312			else
4313			    warning_with_cur_obj("cputype (%d, architecture %s)"
4314				" does not match cputype (%d) for specified "
4315				"-arch flag: %s (file not loaded)", mh->cputype,
4316				 new_arch, arch_flag.cputype, arch_flag.name);
4317		    }
4318		    else{
4319			if(arch_errors_fatal == TRUE){
4320			    error_with_cur_obj("cputype (%d, architecture %s) "
4321				"does not match cputype (%d architecture %s) "
4322				"of objects files previously loaded",
4323				mh->cputype, new_arch, arch_flag.cputype,
4324				prev_arch);
4325			}
4326			else
4327			    warning_with_cur_obj("cputype (%d, architecture %s)"
4328				" does not match cputype (%d architecture %s) "
4329				"of objects files previously loaded (file not "
4330				"loaded)", mh->cputype, new_arch,
4331				arch_flag.cputype,prev_arch);
4332		    }
4333		    return;
4334		}
4335		/* deal with combining this cpusubtype and what is current */
4336		if(force_cpusubtype_ALL == FALSE){
4337		    new_cpusubtype = cpusubtype_combine(arch_flag.cputype,
4338					  arch_flag.cpusubtype, mh->cpusubtype);
4339		    if(new_cpusubtype == -1){
4340			new_arch = get_arch_name_from_types(mh->cputype,
4341							    mh->cpusubtype);
4342			prev_arch = get_arch_name_from_types(arch_flag.cputype,
4343							 arch_flag.cpusubtype);
4344			if(no_arch_warnings == TRUE)
4345			    return;
4346			if(arch_flag.name != NULL){
4347			    if(arch_errors_fatal == TRUE){
4348				error_with_cur_obj("cpusubtype (%d, "
4349				    "architecture %s) does not combine with "
4350				    "cpusubtype (%d) for specified -arch flag: "
4351				    "%s and -force_cpusubtype_ALL not "
4352				    "specified", mh->cpusubtype, new_arch,
4353				    arch_flag.cpusubtype, arch_flag.name);
4354			    }
4355			    else
4356				warning_with_cur_obj("cpusubtype (%d, "
4357				    "architecture %s) does not combine with "
4358				    "cpusubtype (%d) for specified -arch flag: "
4359				    "%s and -force_cpusubtype_ALL not specified"
4360				    " (file not loaded)", mh->cpusubtype,
4361				    new_arch, arch_flag.cpusubtype,
4362				    arch_flag.name);
4363			}
4364			else{
4365			    if(arch_errors_fatal == TRUE){
4366				error_with_cur_obj("cpusubtype (%d, "
4367				    "architecture %s) does not combine with "
4368				    "cpusubtype (%d, architecture %s) of "
4369				    "objects files previously loaded and "
4370				    "-force_cpusubtype_ALL not specified",
4371				    mh->cpusubtype, new_arch,
4372				    arch_flag.cpusubtype, prev_arch);
4373			    }
4374			    else
4375				warning_with_cur_obj("cpusubtype (%d, "
4376				    "architecture %s) does not combine with "
4377				    "cpusubtype (%d, architecture %s) of "
4378				    "objects files previously loaded and "
4379				    "-force_cpusubtype_ALL not specified (file "
4380				    "not loaded)", mh->cpusubtype, new_arch,
4381				    arch_flag.cpusubtype, prev_arch);
4382			}
4383			return;
4384		    }
4385		    else{
4386			/*
4387			 * No -force_cpusubtype_ALL is specified if an -arch
4388			 * flag for a specific implementation of an architecture
4389			 * was specified then the resulting cpusubtype will be
4390			 * for that specific implementation of that architecture
4391			 * and all cpusubtypes must combine with the cpusubtype
4392			 * for the -arch flag to the cpusubtype for the -arch
4393			 * flag else an error must be flaged.
4394			 */
4395			if(specific_arch_flag == TRUE){
4396			    if(arch_flag.cpusubtype != new_cpusubtype){
4397			      new_arch = get_arch_name_from_types(mh->cputype,
4398								mh->cpusubtype);
4399			      warning_with_cur_obj("cpusubtype (%d, "
4400				"architecture %s) does not combine with "
4401				"cpusubtype (%d) for specified -arch flag: %s "
4402				"and -force_cpusubtype_ALL not specified (file "
4403				"not loaded)", mh->cpusubtype, new_arch,
4404				arch_flag.cpusubtype, arch_flag.name);
4405			    }
4406			}
4407			else if(mh->filetype != MH_DYLIB &&
4408				bundle_loader == FALSE)
4409			    arch_flag.cpusubtype = new_cpusubtype;
4410		    }
4411		}
4412		else{ /* force_cpusubtype_ALL == TRUE */
4413		    family_arch_flag =get_arch_family_from_cputype(mh->cputype);
4414		    if(family_arch_flag != NULL)
4415			arch_flag.cpusubtype = family_arch_flag->cpusubtype;
4416		    else{
4417			warning_with_cur_obj("cputype (%d) unknown (file not "
4418			    "loaded)", mh->cputype);
4419			return;
4420		    }
4421		}
4422	    }
4423	    /*
4424	     * Nothing has been loaded yet and no -arch flag has been specified
4425	     * so use this object to set what is to be loaded (the case the
4426	     * architecture has not been selected).
4427	     */
4428	    else{
4429		family_arch_flag = get_arch_family_from_cputype(mh->cputype);
4430		if(family_arch_flag == NULL){
4431		    error_with_cur_obj("cputype (%d) unknown (file not loaded)",
4432			 mh->cputype);
4433		    return;
4434		}
4435		arch_flag.cputype = mh->cputype;
4436		if(force_cpusubtype_ALL == TRUE)
4437		    arch_flag.cpusubtype = family_arch_flag->cpusubtype;
4438		else
4439		    arch_flag.cpusubtype = mh->cpusubtype;
4440		if(target_byte_sex != get_byte_sex_from_flag(family_arch_flag))
4441		    error_with_cur_obj("wrong bytesex for cputype (%d) for "
4442			"-arch %s (bad object or this program out of sync with "
4443			"get_arch_family_from_cputype() and get_byte_sex_"
4444			"from_flag())", arch_flag.cputype,
4445			family_arch_flag->name);
4446#if !defined(SA_RLD) && !(defined(KLD) && defined(__STATIC__))
4447		/*
4448		 * Pick up the Mac OS X deployment target if not done already.
4449		 */
4450		if(macosx_deployment_target.major == 0)
4451		    get_macosx_deployment_target(&macosx_deployment_target);
4452#endif /* !defined(SA_RLD) && !(defined(KLD) && defined(__STATIC__)) */
4453	    }
4454	}
4455	if(mh->sizeofcmds + sizeof(struct mach_header) > cur_obj->obj_size){
4456	    error_with_cur_obj("truncated or malformed object (load commands "
4457			       "extend past the end of the file)");
4458	    return;
4459	}
4460	if((mh->flags & MH_INCRLINK) != 0){
4461	    error_with_cur_obj("was the output of an incremental link, can't "
4462			       "be link edited again");
4463	    return;
4464	}
4465	if((mh->flags & MH_DYLDLINK) != 0 &&
4466	   (mh->filetype != MH_DYLIB &&
4467	    mh->filetype != MH_DYLIB_STUB &&
4468	    mh->filetype != MH_DYLINKER) &&
4469	   bundle_loader == FALSE){
4470	    error_with_cur_obj("is input for the dynamic link editor, is not "
4471			       "relocatable by the static link editor again");
4472	    return;
4473	}
4474	/*
4475	 * If this is a MH_DYLIB or MH_DYLIB_STUB file then a single LC_ID_DYLIB
4476	 * command must be seen to identify the library.
4477	 */
4478	cur_obj->dylib = (enum bool)(mh->filetype == MH_DYLIB ||
4479				     mh->filetype == MH_DYLIB_STUB);
4480	dlid = NULL;
4481	dylib_id_name = NULL;
4482	if(cur_obj->dylib == TRUE && dynamic == FALSE){
4483	    error_with_cur_obj("incompatible, file is a dynamic shared library "
4484		  "(must specify \"-dynamic\" to be used)");
4485	    return;
4486	}
4487	if(dylib_only == TRUE && cur_obj->dylib == FALSE){
4488	    error_with_cur_obj("file is not a dynamic shared library");
4489	    return;
4490	}
4491	/*
4492	 * If this is a MH_DYLINKER file then a single LC_ID_DYLINKER command
4493	 * must be seen to identify the dynamic linker.
4494	 */
4495	cur_obj->dylinker = (enum bool)(mh->filetype == MH_DYLINKER);
4496	dyldid = NULL;
4497	if(cur_obj->dylinker == TRUE && dynamic == FALSE){
4498	    error_with_cur_obj("incompatible, file is a dynamic link editor "
4499		  "(must specify \"-dynamic\" to be used)");
4500	    return;
4501	}
4502
4503	/* check to see that the load commands are valid */
4504	load_commands = (struct load_command *)((char *)cur_obj->obj_addr +
4505			    sizeof(struct mach_header));
4506	st = NULL;
4507	dyst = NULL;
4508	rc = NULL;
4509	sub = NULL;
4510	umbrella_name = NULL;
4511	lc = load_commands;
4512	for(i = 0; i < mh->ncmds; i++){
4513	    l = *lc;
4514	    if(cur_obj->swapped)
4515		swap_load_command(&l, host_byte_sex);
4516	    if(l.cmdsize % sizeof(long) != 0){
4517		error_with_cur_obj("load command %lu size not a multiple of "
4518				   "sizeof(long)", i);
4519		return;
4520	    }
4521	    if(l.cmdsize <= 0){
4522		error_with_cur_obj("load command %lu size is less than or equal"
4523				   " to zero", i);
4524		return;
4525	    }
4526	    if((char *)lc + l.cmdsize >
4527	       (char *)load_commands + mh->sizeofcmds){
4528		error_with_cur_obj("load command %lu extends past end of all "
4529				   "load commands", i);
4530		return;
4531	    }
4532	    switch(l.cmd){
4533	    case LC_SEGMENT:
4534		sg = (struct segment_command *)lc;
4535		if(cur_obj->swapped)
4536		    swap_segment_command(sg, host_byte_sex);
4537		if(sg->cmdsize != sizeof(struct segment_command) +
4538				     sg->nsects * sizeof(struct section)){
4539		    error_with_cur_obj("cmdsize field of load command %lu is "
4540				       "inconsistant for a segment command "
4541				       "with the number of sections it has", i);
4542		    return;
4543		}
4544		if(sg->flags == SG_FVMLIB){
4545		    if(sg->nsects != 0){
4546			error_with_cur_obj("SG_FVMLIB segment %.16s contains "
4547					   "sections and shouldn't",
4548					   sg->segname);
4549			return;
4550		    }
4551		    cur_obj->fvmlib_stuff = TRUE;
4552		    break;
4553		}
4554		check_size_offset(sg->filesize, sg->fileoff, sizeof(long),
4555				  "filesize", "fileoff", i);
4556		if(errors)
4557		    return;
4558		/*
4559		 * Segments without sections are an error to see on input except
4560		 * for the segments created by the link-editor (which are
4561		 * recreated).
4562		 */
4563		if(sg->nsects == 0){
4564		    if(strcmp(sg->segname, SEG_PAGEZERO) != 0 &&
4565		       strcmp(sg->segname, SEG_LINKEDIT) != 0 &&
4566		       strcmp(sg->segname, SEG_UNIXSTACK) != 0){
4567			error_with_cur_obj("segment %.16s contains no "
4568					   "sections and can't be link-edited",
4569					   sg->segname);
4570			return;
4571		    }
4572		}
4573		else{
4574		    /*
4575		     * Doing a reallocate here is not bad beacuse in the
4576		     * normal case this is an MH_OBJECT file type and has only
4577		     * one segment.  So this only gets done once per object.
4578		     */
4579		    cur_obj->section_maps = reallocate(cur_obj->section_maps,
4580					(cur_obj->nsection_maps + sg->nsects) *
4581					sizeof(struct section_map));
4582		    memset(cur_obj->section_maps + cur_obj->nsection_maps, '\0',
4583			   sg->nsects * sizeof(struct section_map));
4584		}
4585		s = (struct section *)
4586		    ((char *)sg + sizeof(struct segment_command));
4587		if(cur_obj->swapped)
4588		    swap_section(s, sg->nsects, host_byte_sex);
4589		for(j = 0 ; j < sg->nsects ; j++){
4590		    cur_obj->section_maps[cur_obj->nsection_maps++].s = s;
4591		    /* check to see that segment name in the section structure
4592		       matches the one in the segment command if this is not in
4593		       an MH_OBJECT filetype */
4594		    if(mh->filetype != MH_OBJECT &&
4595		       strcmp(sg->segname, s->segname) != 0){
4596			error_with_cur_obj("segment name %.16s of section %lu "
4597				"(%.16s,%.16s) in load command %lu does not "
4598				"match segment name %.16s", s->segname, j,
4599				s->segname, s->sectname, i, sg->segname);
4600			return;
4601		    }
4602		    /* check to see that flags (type) of this section is some
4603		       thing the link-editor understands */
4604		    section_type = s->flags & SECTION_TYPE;
4605		    if(section_type != S_REGULAR &&
4606		       section_type != S_ZEROFILL &&
4607		       section_type != S_CSTRING_LITERALS &&
4608		       section_type != S_4BYTE_LITERALS &&
4609		       section_type != S_8BYTE_LITERALS &&
4610		       section_type != S_LITERAL_POINTERS &&
4611		       section_type != S_NON_LAZY_SYMBOL_POINTERS &&
4612		       section_type != S_LAZY_SYMBOL_POINTERS &&
4613		       section_type != S_SYMBOL_STUBS &&
4614		       section_type != S_COALESCED &&
4615		       section_type != S_MOD_INIT_FUNC_POINTERS &&
4616		       section_type != S_MOD_TERM_FUNC_POINTERS &&
4617		       section_type != S_DTRACE_DOF){
4618			error_with_cur_obj("unknown flags (type) of section %lu"
4619					   " (%.16s,%.16s) in load command %lu",
4620					   j, s->segname, s->sectname, i);
4621			return;
4622		    }
4623		    if((s->flags & S_ATTR_DEBUG) == S_ATTR_DEBUG &&
4624		       section_type != S_REGULAR){
4625			error_with_cur_obj("malformed object, debug section %lu"
4626			    " (%.16s,%.16s) in load command %lu is not of type "
4627			    "S_REGULAR\n", j, s->segname, s->sectname, i);
4628			return;
4629		    }
4630		    if(dynamic == FALSE){
4631			if(section_type == S_NON_LAZY_SYMBOL_POINTERS ||
4632			   section_type == S_LAZY_SYMBOL_POINTERS ||
4633			   section_type == S_SYMBOL_STUBS ||
4634			   section_type == S_MOD_INIT_FUNC_POINTERS ||
4635			   section_type == S_MOD_TERM_FUNC_POINTERS){
4636			    error_with_cur_obj("incompatible, file contains "
4637				"unsupported type of section %lu (%.16s,%.16s) "
4638				"in load command %lu (must specify "
4639				"\"-dynamic\" to be used)", j, s->segname,
4640				s->sectname, i);
4641			    return;
4642			}
4643		    }
4644#if defined(SA_RLD) || (defined(KLD) && defined(__STATIC__))
4645		    if(section_type == S_NON_LAZY_SYMBOL_POINTERS ||
4646		       section_type == S_LAZY_SYMBOL_POINTERS ||
4647		       section_type == S_SYMBOL_STUBS ||
4648		       section_type == S_MOD_INIT_FUNC_POINTERS ||
4649		       section_type == S_MOD_TERM_FUNC_POINTERS){
4650			error_with_cur_obj("unsupported type of section %lu "
4651			   "(%.16s,%.16s) for %s in load command %lu", j,
4652			   s->segname, s->sectname, progname, i);
4653			return;
4654		    }
4655#endif /* defined(SA_RLD) || (defined(KLD) && defined(__STATIC__)) */
4656		    /* check to make sure the alignment is reasonable */
4657		    if(s->align > MAXSECTALIGN){
4658			error_with_cur_obj("align (%u) of section %lu "
4659			    "(%.16s,%.16s) in load command %lu greater "
4660			    "than maximum section alignment (%d)", s->align,
4661			     j, s->segname, s->sectname, i, MAXSECTALIGN);
4662			return;
4663		    }
4664		    /* check the size and offset of the contents if it has any*/
4665		    if(mh->filetype != MH_DYLIB_STUB &&
4666		       section_type != S_ZEROFILL){
4667			check_size_offset_sect(s->size, s->offset, sizeof(char),
4668			    "size", "offset", i, j, s->segname, s->sectname);
4669			if(errors)
4670			    return;
4671		    }
4672		    /* check the relocation entries if it can have them */
4673		    if(section_type == S_ZEROFILL ||
4674		       section_type == S_CSTRING_LITERALS ||
4675		       section_type == S_4BYTE_LITERALS ||
4676		       section_type == S_8BYTE_LITERALS ||
4677		       section_type == S_NON_LAZY_SYMBOL_POINTERS){
4678			if(s->nreloc != 0){
4679			    error_with_cur_obj("section %lu (%.16s,%.16s) in "
4680				"load command %lu has relocation entries which "
4681				"it shouldn't for its type (flags)", j,
4682				 s->segname, s->sectname, i);
4683			    return;
4684			}
4685		    }
4686		    else{
4687			if(s->nreloc != 0){
4688			    if(mh->cputype == 0 && mh->cpusubtype == 0){
4689				error_with_cur_obj("section %lu (%.16s,%.16s)"
4690				    "in load command %lu has relocation entries"
4691				    " but the cputype and cpusubtype for the "
4692				    "object are not set", j, s->segname,
4693				    s->sectname, i);
4694				return;
4695			    }
4696			}
4697			else{
4698			    check_size_offset_sect(s->nreloc * sizeof(struct
4699				 relocation_info), s->reloff, sizeof(long),
4700				 "nreloc * sizeof(struct relocation_info)",
4701				 "reloff", i, j, s->segname, s->sectname);
4702			    if(errors)
4703				return;
4704			}
4705		    }
4706		    if(section_type == S_SYMBOL_STUBS && s->reserved2 == 0){
4707			error_with_cur_obj("symbol stub section %lu "
4708			    "(%.16s,%.16s) in load command %lu, sizeof stub in "
4709			    "reserved2 field is zero", j, s->segname,
4710			    s->sectname, i);
4711			return;
4712		    }
4713		    s++;
4714		}
4715		break;
4716
4717	    case LC_SYMTAB:
4718		if(st != NULL){
4719		    error_with_cur_obj("contains more than one LC_SYMTAB load "
4720				       "command");
4721		    return;
4722		}
4723		st = (struct symtab_command *)lc;
4724		if(cur_obj->swapped)
4725		    swap_symtab_command(st, host_byte_sex);
4726		if(st->cmdsize != sizeof(struct symtab_command)){
4727		    error_with_cur_obj("cmdsize of load command %lu incorrect "
4728				       "for LC_SYMTAB", i);
4729		    return;
4730		}
4731		check_size_offset(st->nsyms * sizeof(struct nlist), st->symoff,
4732				  sizeof(long), "nsyms * sizeof(struct nlist)",
4733				  "symoff", i);
4734		if(errors)
4735		    return;
4736		check_size_offset(st->strsize, st->stroff, sizeof(long),
4737				  "strsize", "stroff", i);
4738		if(errors)
4739		    return;
4740		cur_obj->symtab = st;
4741		break;
4742
4743	    case LC_DYSYMTAB:
4744		if(dyst != NULL){
4745		    error_with_cur_obj("contains more than one LC_DYSYMTAB "
4746				       "load command");
4747		    return;
4748		}
4749		dyst = (struct dysymtab_command *)lc;
4750		if(cur_obj->swapped)
4751		    swap_dysymtab_command(dyst, host_byte_sex);
4752		if(dyst->cmdsize != sizeof(struct dysymtab_command)){
4753		    error_with_cur_obj("cmdsize of load command %lu incorrect "
4754				       "for LC_DYSYMTAB", i);
4755		    return;
4756		}
4757		check_size_offset(dyst->ntoc *
4758				  sizeof(struct dylib_table_of_contents),
4759				  dyst->tocoff, sizeof(long),
4760				"ntoc * sizeof(struct dylib_table_of_contents)",
4761				"tocoff", i);
4762		if(dyst->ntoc == 0 && cur_obj->dylib == TRUE &&
4763		   dyst->nextdefsym != 0)
4764		    warning_with_cur_obj("shared library has no table of "
4765					 "contents entries (can't resolve "
4766				         "symbols from it)");
4767		if(errors)
4768		    return;
4769		check_size_offset(dyst->nmodtab * sizeof(struct dylib_module),
4770				  dyst->modtaboff, sizeof(long),
4771				  "nmodtab * sizeof(struct dylib_module)",
4772				  "modtaboff", i);
4773		if(errors)
4774		    return;
4775		check_size_offset(dyst->nextrefsyms *
4776				  sizeof(struct dylib_reference),
4777				  dyst->extrefsymoff, sizeof(long),
4778				 "nextrefsyms * sizeof(struct dylib_reference)",
4779				 "extrefsymoff", i);
4780		if(errors)
4781		    return;
4782		check_size_offset(dyst->nindirectsyms * sizeof(long),
4783				  dyst->indirectsymoff, sizeof(long),
4784				  "nindirectsyms * sizeof(long)",
4785				  "indirectsymoff", i);
4786		if(errors)
4787		    return;
4788		check_size_offset(dyst->nextrel *sizeof(struct relocation_info),
4789				  dyst->extreloff, sizeof(long),
4790				  "nextrel * sizeof(struct relocation_info)",
4791				  "extreloff", i);
4792		if(errors)
4793		    return;
4794		check_size_offset(dyst->nlocrel *sizeof(struct relocation_info),
4795				  dyst->locreloff, sizeof(long),
4796				  "nlocrel * sizeof(struct relocation_info)",
4797				  "locreloff", i);
4798		if(errors)
4799		    return;
4800		cur_obj->dysymtab = dyst;
4801		break;
4802
4803	    case LC_ROUTINES:
4804		if(rc != NULL){
4805		    error_with_cur_obj("contains more than one LC_ROUTINES "
4806				       "load command");
4807		    return;
4808		}
4809		rc = (struct routines_command *)lc;
4810		if(cur_obj->swapped)
4811		    swap_routines_command(rc, host_byte_sex);
4812		if(rc->cmdsize != sizeof(struct routines_command)){
4813		    error_with_cur_obj("cmdsize of load command %lu incorrect "
4814				       "for LC_ROUTINES", i);
4815		    return;
4816		}
4817		if(errors)
4818		    return;
4819		cur_obj->rc = rc;
4820		break;
4821
4822	    case LC_SYMSEG:
4823		ss = (struct symseg_command *)lc;
4824		if(cur_obj->swapped)
4825		    swap_symseg_command(ss, host_byte_sex);
4826		if(ss->size != 0){
4827		    warning_with_cur_obj("contains obsolete LC_SYMSEG load "
4828			"command with non-zero size (produced with a pre-1.0 "
4829			"version of the compiler, please recompile)");
4830		}
4831		break;
4832
4833	    case LC_IDFVMLIB:
4834		if(filetype != MH_FVMLIB){
4835		    error_with_cur_obj("LC_IDFVMLIB load command in object "
4836			"file (should not be in an input file to the link "
4837			"editor for output filetypes other than MH_FVMLIB)");
4838		    return;
4839		}
4840		cur_obj->fvmlib_stuff = TRUE;
4841		fl = (struct fvmlib_command *)lc;
4842		if(cur_obj->swapped)
4843		    swap_fvmlib_command(fl, host_byte_sex);
4844		break;
4845
4846	    case LC_LOADFVMLIB:
4847		if(filetype == MH_FVMLIB ||
4848		   filetype == MH_DYLIB ||
4849		   filetype == MH_DYLINKER){
4850		    error_with_cur_obj("LC_LOADFVMLIB load command in object "
4851			"file (should not be in an input file to the link "
4852			"editor for the output file type %s)",
4853			filetype == MH_FVMLIB ? "MH_FVMLIB" :
4854			(filetype == MH_DYLIB ? "MH_DYLIB" : "MH_DYLINKER"));
4855		    return;
4856		}
4857		fl = (struct fvmlib_command *)lc;
4858		if(cur_obj->swapped)
4859		    swap_fvmlib_command(fl, host_byte_sex);
4860		if(fl->cmdsize < sizeof(struct fvmlib_command)){
4861		    error_with_cur_obj("cmdsize of load command %lu incorrect "
4862				       "for LC_LOADFVMLIB", i);
4863		    return;
4864		}
4865		if(fl->fvmlib.name.offset >= fl->cmdsize){
4866		    error_with_cur_obj("name.offset of load command %lu extends"
4867				       " past the end of the load command", i);
4868		    return;
4869		}
4870		fvmlib_name = (char *)fl + fl->fvmlib.name.offset;
4871		for(j = 0 ; j < fl->cmdsize - fl->fvmlib.name.offset; j++){
4872		    if(fvmlib_name[j] == '\0')
4873			break;
4874		}
4875		if(j >= fl->cmdsize - fl->fvmlib.name.offset){
4876		    error_with_cur_obj("library name of load command %lu "
4877				       "not null terminated", i);
4878		    return;
4879		}
4880		cur_obj->fvmlib_stuff = TRUE;
4881		break;
4882
4883	    case LC_ID_DYLIB:
4884		if(filetype == MH_FVMLIB ||
4885		   filetype == MH_DYLINKER){
4886		    error_with_cur_obj("LC_ID_DYLIB load command in object "
4887			"file (should not be in an input file to the link "
4888			"editor for the output file type %s)",
4889			filetype == MH_FVMLIB ? "MH_FVMLIB" : "MH_DYLINKER");
4890		    return;
4891		}
4892		if(mh->filetype != MH_DYLIB && mh->filetype != MH_DYLIB_STUB){
4893		    error_with_cur_obj("LC_ID_DYLIB load command in non-"
4894			"%s filetype", mh->filetype == MH_DYLIB ? "MH_DYLIB" :
4895			"MH_DYLIB_STUB");
4896		    return;
4897		}
4898		if(dlid != NULL){
4899		    error_with_cur_obj("malformed object (more than one "
4900			"LC_ID_DYLIB load command in %s file)", mh->filetype ==
4901			MH_DYLIB ? "MH_DYLIB" : "MH_DYLIB_STUB");
4902		    return;
4903		}
4904		dl = (struct dylib_command *)lc;
4905		dlid = dl;
4906		if(cur_obj->swapped)
4907		    swap_dylib_command(dl, host_byte_sex);
4908		if(dl->cmdsize < sizeof(struct dylib_command)){
4909		    error_with_cur_obj("cmdsize of load command %lu incorrect "
4910				       "for LC_ID_DYLIB", i);
4911		    return;
4912		}
4913		if(dl->dylib.name.offset >= dl->cmdsize){
4914		    error_with_cur_obj("name.offset of load command %lu extends"
4915				       " past the end of the load command", i);
4916		    return;
4917		}
4918		dylib_id_name = (char *)dl + dl->dylib.name.offset;
4919		for(j = 0 ; j < dl->cmdsize - dl->dylib.name.offset; j++){
4920		    if(dylib_id_name[j] == '\0')
4921			break;
4922		}
4923		if(j >= dl->cmdsize - dl->dylib.name.offset){
4924		    error_with_cur_obj("library name of load command %lu "
4925				       "not null terminated", i);
4926		    return;
4927		}
4928		cur_obj->dylib_stuff = TRUE;
4929		break;
4930
4931	    case LC_LOAD_DYLIB:
4932	    case LC_LOAD_WEAK_DYLIB:
4933	    case LC_REEXPORT_DYLIB:
4934		if(filetype == MH_FVMLIB ||
4935		   filetype == MH_DYLINKER){
4936		    error_with_cur_obj("%s load command in object "
4937			"file (should not be in an input file to the link "
4938			"editor for the output file type %s)",
4939			l.cmd == LC_LOAD_DYLIB ? "LC_LOAD_DYLIB" :
4940			"LC_LOAD_WEAK_DYLIB",
4941			filetype == MH_FVMLIB ? "MH_FVMLIB" : "MH_DYLINKER");
4942		    return;
4943		}
4944		dl = (struct dylib_command *)lc;
4945		if(cur_obj->swapped)
4946		    swap_dylib_command(dl, host_byte_sex);
4947		if(dl->cmdsize < sizeof(struct dylib_command)){
4948		    error_with_cur_obj("cmdsize of load command %lu incorrect "
4949			"for %s", i, l.cmd == LC_LOAD_DYLIB ?  "LC_LOAD_DYLIB" :
4950			"LC_LOAD_WEAK_DYLIB");
4951		    return;
4952		}
4953		if(dl->dylib.name.offset >= dl->cmdsize){
4954		    error_with_cur_obj("name.offset of load command %lu extends"
4955				       " past the end of the load command", i);
4956		    return;
4957		}
4958		dylib_name = (char *)dl + dl->dylib.name.offset;
4959		for(j = 0 ; j < dl->cmdsize - dl->dylib.name.offset; j++){
4960		    if(dylib_name[j] == '\0')
4961			break;
4962		}
4963		if(j >= dl->cmdsize - dl->dylib.name.offset){
4964		    error_with_cur_obj("library name of load command %lu "
4965				       "not null terminated", i);
4966		    return;
4967		}
4968		cur_obj->dylib_stuff = TRUE;
4969		cur_obj->nload_dylibs++;
4970		break;
4971
4972	    case LC_SUB_FRAMEWORK:
4973		if(filetype == MH_FVMLIB ||
4974		   filetype == MH_DYLINKER){
4975		    error_with_cur_obj("LC_SUB_FRAMEWORK load command in "
4976			"object file (should not be in an input file to the "
4977			"link editor for the output file type %s)",
4978			filetype == MH_FVMLIB ? "MH_FVMLIB" : "MH_DYLINKER");
4979		    return;
4980		}
4981		if(mh->filetype != MH_DYLIB && mh->filetype != MH_DYLIB_STUB){
4982		    error_with_cur_obj("LC_SUB_FRAMEWORK load command in non-"
4983			"%s filetype", mh->filetype == MH_DYLIB ? "MH_DYLIB" :
4984			"MH_DYLIB_STUB");
4985		    return;
4986		}
4987		if(sub != NULL){
4988		    error_with_cur_obj("malformed object (more than one "
4989			"LC_SUB_FRAMEWORK load command in %s file)",
4990			mh->filetype == MH_DYLIB ? "MH_DYLIB" :
4991			"MH_DYLIB_STUB");
4992		    return;
4993		}
4994		sub = (struct sub_framework_command *)lc;
4995		if(cur_obj->swapped)
4996		    swap_sub_framework_command(sub, host_byte_sex);
4997		if(sub->cmdsize < sizeof(struct sub_framework_command)){
4998		    error_with_cur_obj("cmdsize of load command %lu incorrect "
4999				       "for LC_SUB_FRAMEWORK", i);
5000		    return;
5001		}
5002		if(sub->umbrella.offset >= sub->cmdsize){
5003		    error_with_cur_obj("umbrella.offset of load command %lu "
5004				"extends past the end of the load command", i);
5005		    return;
5006		}
5007		umbrella_name = (char *)sub + sub->umbrella.offset;
5008		for(j = 0 ; j < sub->cmdsize - sub->umbrella.offset; j++){
5009		    if(umbrella_name[j] == '\0')
5010			break;
5011		}
5012		if(j >= sub->cmdsize - sub->umbrella.offset){
5013		    error_with_cur_obj("umbrella name of load command %lu "
5014				       "not null terminated", i);
5015		    return;
5016		}
5017		break;
5018
5019	    case LC_SUB_UMBRELLA:
5020		if(filetype == MH_FVMLIB ||
5021		   filetype == MH_DYLINKER){
5022		    error_with_cur_obj("LC_SUB_UMBRELLA load command in "
5023			"object file (should not be in an input file to the "
5024			"link editor for the output file type %s)",
5025			filetype == MH_FVMLIB ? "MH_FVMLIB" : "MH_DYLINKER");
5026		    return;
5027		}
5028		if(mh->filetype != MH_DYLIB && mh->filetype != MH_DYLIB_STUB){
5029		    error_with_cur_obj("LC_SUB_UMBRELLA load command in non-"
5030			"%s filetype", mh->filetype == MH_DYLIB ? "MH_DYLIB" :
5031			"MH_DYLIB_STUB");
5032		    return;
5033		}
5034		usub = (struct sub_umbrella_command *)lc;
5035		if(cur_obj->swapped)
5036		    swap_sub_umbrella_command(usub, host_byte_sex);
5037		if(usub->cmdsize < sizeof(struct sub_umbrella_command)){
5038		    error_with_cur_obj("cmdsize of load command %lu incorrect "
5039				       "for LC_SUB_UMBRELLA", i);
5040		    return;
5041		}
5042		if(usub->sub_umbrella.offset >= usub->cmdsize){
5043		    error_with_cur_obj("sub_umbrella.offset of load command "
5044			"%lu extends past the end of the load command", i);
5045		    return;
5046		}
5047		sub_umbrella_name = (char *)usub + usub->sub_umbrella.offset;
5048		for(j = 0 ; j < usub->cmdsize - usub->sub_umbrella.offset; j++){
5049		    if(sub_umbrella_name[j] == '\0')
5050			break;
5051		}
5052		if(j >= usub->cmdsize - usub->sub_umbrella.offset){
5053		    error_with_cur_obj("sub_umbrella name of load command %lu "
5054				       "not null terminated", i);
5055		    return;
5056		}
5057		break;
5058
5059	    case LC_SUB_LIBRARY:
5060		if(filetype == MH_FVMLIB ||
5061		   filetype == MH_DYLINKER){
5062		    error_with_cur_obj("LC_SUB_LIBRARY load command in "
5063			"object file (should not be in an input file to the "
5064			"link editor for the output file type %s)",
5065			filetype == MH_FVMLIB ? "MH_FVMLIB" : "MH_DYLINKER");
5066		    return;
5067		}
5068		if(mh->filetype != MH_DYLIB && mh->filetype != MH_DYLIB_STUB){
5069		    error_with_cur_obj("LC_SUB_LIBRARY load command in non-"
5070			"%s filetype", mh->filetype == MH_DYLIB ? "MH_DYLIB" :
5071			"MH_DYLIB_STUB");
5072		    return;
5073		}
5074		lsub = (struct sub_library_command *)lc;
5075		if(cur_obj->swapped)
5076		    swap_sub_library_command(lsub, host_byte_sex);
5077		if(lsub->cmdsize < sizeof(struct sub_library_command)){
5078		    error_with_cur_obj("cmdsize of load command %lu incorrect "
5079				       "for LC_SUB_LIBRARY", i);
5080		    return;
5081		}
5082		if(lsub->sub_library.offset >= lsub->cmdsize){
5083		    error_with_cur_obj("sub_library.offset of load command "
5084			"%lu extends past the end of the load command", i);
5085		    return;
5086		}
5087		sub_library_name = (char *)lsub + lsub->sub_library.offset;
5088		for(j = 0 ; j < lsub->cmdsize - lsub->sub_library.offset; j++){
5089		    if(sub_library_name[j] == '\0')
5090			break;
5091		}
5092		if(j >= lsub->cmdsize - lsub->sub_library.offset){
5093		    error_with_cur_obj("sub_library name of load command %lu "
5094				       "not null terminated", i);
5095		    return;
5096		}
5097		break;
5098
5099	    case LC_SUB_CLIENT:
5100		if(filetype == MH_FVMLIB ||
5101		   filetype == MH_DYLINKER){
5102		    error_with_cur_obj("LC_SUB_CLIENT load command in "
5103			"object file (should not be in an input file to the "
5104			"link editor for the output file type %s)",
5105			filetype == MH_FVMLIB ? "MH_FVMLIB" : "MH_DYLINKER");
5106		    return;
5107		}
5108		if(mh->filetype != MH_DYLIB && mh->filetype != MH_DYLIB_STUB){
5109		    error_with_cur_obj("LC_SUB_CLIENT load command in non-"
5110			"%s filetype", mh->filetype == MH_DYLIB ? "MH_DYLIB" :
5111			"MH_DYLIB_STUB");
5112		    return;
5113		}
5114		csub = (struct sub_client_command *)lc;
5115		if(cur_obj->swapped)
5116		    swap_sub_client_command(csub, host_byte_sex);
5117		if(csub->cmdsize < sizeof(struct sub_client_command)){
5118		    error_with_cur_obj("cmdsize of load command %lu incorrect "
5119				       "for LC_SUB_CLIENT", i);
5120		    return;
5121		}
5122		if(csub->client.offset >= csub->cmdsize){
5123		    error_with_cur_obj("client.offset of load command %lu "
5124				"extends past the end of the load command", i);
5125		    return;
5126		}
5127		sub_client_name = (char *)csub + csub->client.offset;
5128		for(j = 0 ; j < csub->cmdsize - csub->client.offset; j++){
5129		    if(sub_client_name[j] == '\0')
5130			break;
5131		}
5132		if(j >= csub->cmdsize - csub->client.offset){
5133		    error_with_cur_obj("sub_client name of load command %lu "
5134				       "not null terminated", i);
5135		    return;
5136		}
5137		break;
5138
5139	    case LC_ID_DYLINKER:
5140		if(filetype == MH_FVMLIB ||
5141		   filetype == MH_DYLIB ||
5142		   filetype == MH_DYLINKER){
5143		    error_with_cur_obj("LC_ID_DYLINKER load command in object "
5144			"file (should not be in an input file to the link "
5145			"editor for the output file type %s)",
5146			filetype == MH_FVMLIB ? "MH_FVMLIB" :
5147			(filetype == MH_DYLIB ? "MH_DYLIB" : "MH_DYLINKER"));
5148		    return;
5149		}
5150		if(mh->filetype != MH_DYLINKER){
5151		    error_with_cur_obj("LC_ID_DYLINKER load command in non-"
5152			"MH_DYLINKER filetype");
5153		    return;
5154		}
5155		if(dyldid != NULL){
5156		    error_with_cur_obj("malformed object (more than one "
5157			"LC_ID_DYLINKER load command in MH_DYLINKER file)");
5158		    return;
5159		}
5160		dyld = (struct dylinker_command *)lc;
5161		dyldid = dyld;
5162		if(cur_obj->swapped)
5163		    swap_dylinker_command(dyld, host_byte_sex);
5164		if(dyld->cmdsize < sizeof(struct dylinker_command)){
5165		    error_with_cur_obj("cmdsize of load command %lu incorrect "
5166				       "for LC_ID_DYLINKER", i);
5167		    return;
5168		}
5169		if(dyld->name.offset >= dyld->cmdsize){
5170		    error_with_cur_obj("name.offset of load command %lu extends"
5171				       " past the end of the load command", i);
5172		    return;
5173		}
5174		dylinker_name = (char *)dyld + dyld->name.offset;
5175		for(j = 0 ; j < dyld->cmdsize - dyld->name.offset; j++){
5176		    if(dylinker_name[j] == '\0')
5177			break;
5178		}
5179		if(j >= dyld->cmdsize - dyld->name.offset){
5180		    error_with_cur_obj("dynamic linker name of load command "
5181			"%lu not null terminated", i);
5182		    return;
5183		}
5184		cur_obj->dylib_stuff = TRUE;
5185		break;
5186
5187	    case LC_LOAD_DYLINKER:
5188		if(filetype == MH_FVMLIB ||
5189		   filetype == MH_DYLIB ||
5190		   filetype == MH_DYLINKER){
5191		    error_with_cur_obj("LC_LOAD_DYLINKER load command in object"
5192			" file (should not be in an input file to the link "
5193			"editor for the output file type %s)",
5194			filetype == MH_FVMLIB ? "MH_FVMLIB" :
5195			(filetype == MH_DYLIB ? "MH_DYLIB" : "MH_DYLINKER"));
5196		    return;
5197		}
5198		dyld = (struct dylinker_command *)lc;
5199		if(cur_obj->swapped)
5200		    swap_dylinker_command(dyld, host_byte_sex);
5201		if(dyld->cmdsize < sizeof(struct dylinker_command)){
5202		    error_with_cur_obj("cmdsize of load command %lu incorrect "
5203				       "for LC_LOAD_DYLINKER", i);
5204		    return;
5205		}
5206		if(dyld->name.offset >= dyld->cmdsize){
5207		    error_with_cur_obj("name.offset of load command %lu extends"
5208				       " past the end of the load command", i);
5209		    return;
5210		}
5211		dylinker_name = (char *)dyld + dyld->name.offset;
5212		for(j = 0 ; j < dyld->cmdsize - dyld->name.offset; j++){
5213		    if(dylinker_name[j] == '\0')
5214			break;
5215		}
5216		if(j >= dyld->cmdsize - dyld->name.offset){
5217		    error_with_cur_obj("dynamic linker name of load command "
5218			"%lu not null terminated", i);
5219		    return;
5220		}
5221		cur_obj->dylib_stuff = TRUE;
5222		break;
5223
5224	    case LC_TWOLEVEL_HINTS:
5225		hints = (struct twolevel_hints_command *)lc;
5226		if(cur_obj->swapped)
5227		    swap_twolevel_hints_command(hints, host_byte_sex);
5228		if(hints->cmdsize != sizeof(struct twolevel_hints_command)){
5229		    error_with_cur_obj("cmdsize of load command %lu incorrect "
5230				       "for LC_TWOLEVEL_HINTS", i);
5231		    return;
5232		}
5233		check_size_offset(hints->nhints * sizeof(struct twolevel_hint),
5234				  hints->offset, sizeof(long),
5235				  "nhints * sizeof(struct twolevel_hint)",
5236				  "offset", i);
5237		if(errors)
5238		    return;
5239		break;
5240
5241	    case LC_PREBIND_CKSUM:
5242		cs = (struct prebind_cksum_command *)lc;
5243		if(cur_obj->swapped)
5244		    swap_prebind_cksum_command(cs, host_byte_sex);
5245		if(cs->cmdsize != sizeof(struct prebind_cksum_command)){
5246		    error_with_cur_obj("cmdsize of load command %lu incorrect "
5247				       "for LC_PREBIND_CKSUM", i);
5248		    return;
5249		}
5250		if(errors)
5251		    return;
5252		break;
5253
5254	    case LC_UUID:
5255		uuid = (struct uuid_command *)lc;
5256		if(cur_obj->swapped)
5257		    swap_uuid_command(uuid, host_byte_sex);
5258		if(uuid->cmdsize != sizeof(struct uuid_command)){
5259		    error_with_cur_obj("cmdsize of load command %lu incorrect "
5260				       "for LC_UUID", i);
5261		    return;
5262		}
5263		if(errors)
5264		    return;
5265#ifndef KLD
5266		/*
5267		 * If we see an input file with an LC_UUID load command then
5268		 * set up to emit one in the output.
5269		 */
5270		output_uuid_info.emit = TRUE;
5271#else
5272		/*
5273		 * For kernel extensions preserve the existing UUID in the
5274		 * output.
5275		 */
5276		output_uuid_info.uuid_command.cmd = LC_UUID;
5277		output_uuid_info.uuid_command.cmdsize =
5278						sizeof(struct uuid_command);
5279		memcpy(&(output_uuid_info.uuid_command.uuid[0]), uuid->uuid,
5280		       sizeof(uuid->uuid));
5281#endif
5282
5283		break;
5284
5285	    /*
5286	     * All of these are not looked at so the whole command is not
5287	     * swapped.  But we need to swap just the first part in memory in
5288	     * case they are in a dylib so other code can step over them.
5289	     */
5290	    case LC_UNIXTHREAD:
5291	    case LC_THREAD:
5292	    case LC_IDENT:
5293	    case LC_FVMFILE:
5294	    case LC_PREPAGE:
5295	    case LC_PREBOUND_DYLIB:
5296	    case LC_CODE_SIGNATURE:
5297	    case LC_SEGMENT_SPLIT_INFO:
5298		if(cur_obj->swapped)
5299		    swap_load_command(lc, host_byte_sex);
5300		break;
5301
5302	    default:
5303		error_with_cur_obj("load command %lu unknown cmd field", i);
5304		return;
5305	    }
5306	    lc = (struct load_command *)((char *)lc + l.cmdsize);
5307	}
5308	/*
5309	 * The -bundle_loader argument must be an object file with a dynamic
5310	 * symbol table command.
5311	 */
5312	if(bundle_loader){
5313	    if(cur_obj->dysymtab == NULL){
5314		error_with_cur_obj("bundle loader does not have an LC_DYSYMTAB "
5315				   "command");
5316		return;
5317	    }
5318	    cur_obj->bundle_loader = TRUE;
5319	}
5320	/*
5321	 * If this object does not have a symbol table command then set it's
5322	 * symtab pointer to the empty symtab.  This makes symbol number range
5323	 * checks in relocation cleaner.
5324	 */
5325	if(cur_obj->symtab == NULL){
5326	    if(cur_obj->dysymtab != NULL)
5327		error_with_cur_obj("contains LC_DYSYMTAB load command without "
5328				   "a LC_SYMTAB load command");
5329	    cur_obj->symtab = (struct symtab_command *)&empty_symtab;
5330	    cur_obj->dysymtab = (struct dysymtab_command *)&empty_dysymtab;
5331	}
5332	else{
5333	    if(cur_obj->dysymtab == NULL){
5334		cur_obj->dysymtab = (struct dysymtab_command *)&empty_dysymtab;
5335		if(cur_obj->rc != NULL)
5336		    error_with_cur_obj("contains LC_ROUTINES load command "
5337				       "without a LC_DYSYMTAB load command");
5338	    }
5339	    else{
5340		if(dyst->nlocalsym != 0 &&
5341		   dyst->ilocalsym > st->nsyms)
5342		    error_with_cur_obj("ilocalsym in LC_DYSYMTAB load "
5343			"command extends past the end of the symbol table");
5344		if(dyst->nlocalsym != 0 &&
5345		   dyst->ilocalsym + dyst->nlocalsym > st->nsyms)
5346		    error_with_cur_obj("ilocalsym plus nlocalsym in "
5347			"LC_DYSYMTAB load command extends past the "
5348			"end of the symbol table");
5349
5350		if(dyst->nextdefsym != 0 &&
5351		   dyst->iextdefsym > st->nsyms)
5352		    error_with_cur_obj("iextdefsym in LC_DYSYMTAB load "
5353			"command extends past the end of the symbol table");
5354		if(dyst->nextdefsym != 0 &&
5355		   dyst->iextdefsym + dyst->nextdefsym > st->nsyms)
5356		    error_with_cur_obj("iextdefsym plus nextdefsym in "
5357			"LC_DYSYMTAB load command extends past the "
5358			"end of the symbol table");
5359
5360		if(dyst->nundefsym != 0 &&
5361		   dyst->iundefsym > st->nsyms)
5362		    error_with_cur_obj("iundefsym in LC_DYSYMTAB load "
5363			"command extends past the end of the symbol table");
5364		if(dyst->nundefsym != 0 &&
5365		   dyst->iundefsym + dyst->nundefsym > st->nsyms)
5366		    error_with_cur_obj("iundefsym plus nundefsym in "
5367			"LC_DYSYMTAB load command extends past the "
5368			"end of the symbol table");
5369
5370		if(dyst->ntoc != 0){
5371		    tocs =(struct dylib_table_of_contents *)(cur_obj->obj_addr +
5372							     dyst->tocoff);
5373		    if(cur_obj->swapped)
5374			swap_dylib_table_of_contents(tocs, dyst->ntoc,
5375						     host_byte_sex);
5376		    for(i = 0; i < dyst->ntoc; i++){
5377			if(tocs[i].symbol_index > st->nsyms)
5378			    error_with_cur_obj("symbol_index field of table of "
5379				"contents entry %lu past the end of the symbol "
5380				"table", i);
5381			if(tocs[i].module_index > dyst->nmodtab)
5382			    error_with_cur_obj("module_index field of table of "
5383				"contents entry %lu past the end of the module "
5384				"table", i);
5385		    }
5386		}
5387
5388		if(dyst->nmodtab != 0){
5389		    mods = (struct dylib_module *)(cur_obj->obj_addr +
5390						   dyst->modtaboff);
5391		    if(cur_obj->swapped)
5392			swap_dylib_module(mods, dyst->nmodtab, host_byte_sex);
5393		    for(i = 0; i < dyst->nmodtab; i++){
5394			if(mods[i].module_name > st->strsize)
5395			    error_with_cur_obj("module_name field of module "
5396				"table entry %lu past the end of the string "
5397				"table", i);
5398			if(mods[i].iextdefsym > st->nsyms)
5399			    error_with_cur_obj("iextdefsym field of module "
5400				"table entry %lu past the end of the symbol "
5401				"table", i);
5402			if(mods[i].iextdefsym +
5403			   mods[i].nextdefsym > st->nsyms)
5404			    error_with_cur_obj("iextdefsym field plus "
5405				"nextdefsym field of module table entry %lu "
5406				"past the end of the symbol table", i);
5407			if(mods[i].irefsym > dyst->nextrefsyms)
5408			    error_with_cur_obj("irefsym field of module table "
5409				"entry %lu past the end of the reference table",
5410				i);
5411			if(mods[i].irefsym +
5412			   mods[i].nrefsym > dyst->nextrefsyms)
5413			    error_with_cur_obj("irefsym field plus "
5414				"nrefsym field of module table entry %lu past "
5415				"the end of the reference table", i);
5416			if(mods[i].ilocalsym > st->nsyms)
5417			    error_with_cur_obj("ilocalsym field of module "
5418				"table entry %lu past the end of the symbol "
5419				"table", i);
5420			if(mods[i].ilocalsym +
5421			   mods[i].nlocalsym > st->nsyms)
5422			    error_with_cur_obj("ilocalsym field plus "
5423				"nlocalsym field of module table entry %lu "
5424				"past the end of the symbol table", i);
5425		    }
5426		}
5427
5428		if(dyst->nextrefsyms != 0){
5429		    refs = (struct dylib_reference *)(cur_obj->obj_addr +
5430						      dyst->extrefsymoff);
5431		    if(cur_obj->swapped)
5432			swap_dylib_reference(refs, dyst->nextrefsyms,
5433					     host_byte_sex);
5434		    for(i = 0; i < dyst->nextrefsyms; i++){
5435			if(refs[i].isym > st->nsyms)
5436			    error_with_cur_obj("isym field of reference table "
5437				"entry %lu past the end of the symbol table",i);
5438		    }
5439		}
5440
5441		if(dyst->nindirectsyms != 0){
5442		    indirect_symtab = (uint32_t *)(cur_obj->obj_addr +
5443					    dyst->indirectsymoff);
5444		    if(cur_obj->swapped)
5445			swap_indirect_symbols(indirect_symtab,
5446			    dyst->nindirectsyms, host_byte_sex);
5447		    for(i = 0; i < dyst->nindirectsyms; i++){
5448			if(indirect_symtab[i] != INDIRECT_SYMBOL_LOCAL &&
5449			   indirect_symtab[i] != INDIRECT_SYMBOL_ABS){
5450			    if(indirect_symtab[i] > st->nsyms)
5451				error_with_cur_obj("indirect symbol table entry"
5452				    " %lu past the end of the symbol table", i);
5453			}
5454		    }
5455		}
5456
5457		if(rc != NULL && rc->init_module > dyst->nmodtab)
5458		    error_with_cur_obj("init_module field of LC_ROUTINES load "
5459			"command past the end of the module table");
5460	    }
5461	}
5462	/*
5463	 * If this is a MH_DYLIB or MH_DYLIB_STUB file then a single
5464	 * LC_ID_DYLIB command must be seen to identify the library.
5465	 */
5466	if((mh->filetype == MH_DYLIB || mh->filetype == MH_DYLIB_STUB) &&
5467	   dlid == NULL){
5468	    error_with_cur_obj("malformed object (no LC_ID_DYLIB load command "
5469			       "in %s file)", mh->filetype == MH_DYLIB ?
5470			       "MH_DYLIB" : "MH_DYLIB_STUB");
5471	    return;
5472	}
5473	/*
5474	 * If this is a MH_DYLINKER file then a single LC_ID_DYLINKER command
5475	 * must be seen to identify the library.
5476	 */
5477	if(mh->filetype == MH_DYLINKER && dyldid == NULL){
5478	    error_with_cur_obj("malformed object (no LC_ID_DYLINKER load "
5479		"command in MH_DYLINKER file)");
5480	    return;
5481	}
5482#ifndef RLD
5483	/*
5484	 * If we find a sub_framework_command for a dynamic library that was
5485	 * directly linked against then we must generate a link error
5486	 * if what we are building is not the umbrella framework for this
5487	 * subframework or it is not a another subframework of the same
5488	 * umbrella framework.
5489	 *
5490	 * The following error is a non-standard form but it is exactly what is
5491	 * specified when this feature was added.
5492	 */
5493	if(indirect_dylib == FALSE && sub != NULL &&
5494	   (umbrella_framework_name == NULL ||
5495	    strcmp(umbrella_name, umbrella_framework_name) != 0)){
5496
5497	    short_name = guess_short_name(dylib_id_name, &is_framework,
5498					  &has_suffix);
5499	    /*
5500	     * This may still be an allowable of this sub framework.  Check the
5501	     * LC_SUB_CLIENT commands to see if this client name is listed.
5502	     */
5503	    if(umbrella_framework_name != NULL)
5504		this_client_name = umbrella_framework_name;
5505	    else
5506		this_client_name = client_name;
5507	    allowable_client = FALSE;
5508	    if(this_client_name != NULL){
5509		lc = load_commands;
5510		for(i = 0; i < mh->ncmds; i++){
5511		    if(lc->cmd == LC_SUB_CLIENT){
5512			csub = (struct sub_client_command *)lc;
5513			sub_client_name = (char *)csub + csub->client.offset;
5514			if(strcmp(sub_client_name, this_client_name) == 0){
5515			    allowable_client = TRUE;
5516			    break;
5517			}
5518		    }
5519		    lc = (struct load_command *)((char *)lc + lc->cmdsize);
5520		}
5521	    }
5522	    if(allowable_client == FALSE){
5523		if(short_name != NULL && is_framework == TRUE)
5524		    error_with_cur_obj("'%s.framework' is a subframework.  "
5525			"Link against the umbrella framework '%s.framework' "
5526			"instead.", short_name, umbrella_name);
5527		else
5528		    error_with_cur_obj("is a subframework.  Link against the "
5529			"umbrella framework '%s.framework' instead.",
5530			umbrella_name);
5531	    }
5532	}
5533#endif /* RLD */
5534}
5535
5536#ifdef RLD
5537/*
5538 * merge_base_program() does the pass1 functions for the base program that
5539 * called rld_load() using it's SEG_LINKEDIT.  It does the same things as the
5540 * routines pass1(),check_obj() and merge() except that the offset are assumed
5541 * to be correct in most cases (if they weren't the program would not be
5542 * executing).  If seg_linkedit is NULL it then the symbol and string table
5543 * passed in is used instead of seg_linkedit.
5544 *
5545 * A hand crafted object structure is created so to work with the rest of the
5546 * code.  Like check_obj() a number of things are filled in in the object
5547 * structrure including: the symtab field, the section_maps and nsection_maps
5548 * fields (this routine allocates the section_map structures and fills them in
5549 * too), all fvmlib stuff is ignored since the output is loaded as well as
5550 * linked.  The file offsets in symtab are faked since this is not a file mapped
5551 * into memory but rather a running process.  This involves setting where the
5552 * object starts to the address of the _mh_execute_header and calcating the
5553 * file offset of the symbol and string table as the differences of the
5554 * addresses from the _mh_execute_header.  This makes using the rest of the
5555 * code easy.
5556 */
5557__private_extern__
5558void
5559merge_base_program(
5560char *basefile_name,
5561struct mach_header *basefile_addr,
5562struct segment_command *seg_linkedit,
5563struct nlist *symtab,
5564unsigned long nsyms,
5565char *strtab,
5566unsigned long strsize)
5567{
5568    unsigned long i, j, section_type;
5569    struct mach_header *mh;
5570    struct load_command *lc, *load_commands;
5571    struct segment_command *sg;
5572    struct section *s;
5573    struct symtab_command *st;
5574    struct dysymtab_command *dyst;
5575
5576    static const struct symtab_command empty_symtab = { 0 };
5577    static struct symtab_command base_program_symtab = { 0 };
5578
5579	/*
5580	 * Hand craft the object structure as in pass1().  Note the obj_size
5581	 * feild should never be tested against since this is not a file mapped
5582	 * into memory but rather a running program.
5583	 */
5584	cur_obj = new_object_file();
5585	cur_obj->file_name = basefile_name;
5586	cur_obj->obj_addr = (char *)basefile_addr;
5587	cur_obj->obj_size = 0;
5588	cur_obj->from_fat_file = FALSE;
5589	base_obj = cur_obj;
5590	/* Set the output cpu types from the base program's header */
5591	mh = basefile_addr;
5592	arch_flag.cputype = mh->cputype;
5593	arch_flag.cpusubtype = mh->cpusubtype;
5594
5595	/*
5596	 * Go through the load commands and do what would be done in check_obj()
5597	 * but not checking for offsets.
5598	 */
5599	load_commands = (struct load_command *)((char *)cur_obj->obj_addr +
5600			    sizeof(struct mach_header));
5601	st = NULL;
5602	dyst = NULL;
5603	lc = load_commands;
5604	for(i = 0; i < mh->ncmds; i++){
5605	    if(lc->cmdsize % sizeof(long) != 0){
5606		error_with_cur_obj("load command %lu size not a multiple of "
5607				   "sizeof(long)", i);
5608		return;
5609	    }
5610	    if(lc->cmdsize <= 0){
5611		error_with_cur_obj("load command %lu size is less than or equal"
5612				   " to zero", i);
5613		return;
5614	    }
5615	    if((char *)lc + lc->cmdsize >
5616	       (char *)load_commands + mh->sizeofcmds){
5617		error_with_cur_obj("load command %lu extends past end of all "
5618				   "load commands", i);
5619		return;
5620	    }
5621	    switch(lc->cmd){
5622	    case LC_SEGMENT:
5623		sg = (struct segment_command *)lc;
5624		if(sg->cmdsize != sizeof(struct segment_command) +
5625				     sg->nsects * sizeof(struct section)){
5626		    error_with_cur_obj("cmdsize field of load command %lu is "
5627				       "inconsistant for a segment command "
5628				       "with the number of sections it has", i);
5629		    return;
5630		}
5631		if(sg->flags == SG_FVMLIB){
5632		    if(sg->nsects != 0){
5633			error_with_cur_obj("SG_FVMLIB segment %.16s contains "
5634					   "sections and shouldn't",
5635					   sg->segname);
5636			return;
5637		    }
5638		    break;
5639		}
5640		/*
5641		 * Segments without sections are an error to see on input except
5642		 * for the segments created by the link-editor (which are
5643		 * recreated).
5644		 */
5645		if(sg->nsects == 0){
5646		    if(strcmp(sg->segname, SEG_PAGEZERO) != 0 &&
5647		       strcmp(sg->segname, SEG_LINKEDIT) != 0){
5648			error_with_cur_obj("segment %.16s contains no "
5649					   "sections and can't be link-edited",
5650					   sg->segname);
5651			return;
5652		    }
5653		}
5654		else{
5655		    /*
5656		     * Doing a reallocate here is not bad beacuse in the
5657		     * normal case this is an MH_OBJECT file type and has only
5658		     * one section.  So this only gets done once per object.
5659		     */
5660		    cur_obj->section_maps = reallocate(cur_obj->section_maps,
5661					(cur_obj->nsection_maps + sg->nsects) *
5662					sizeof(struct section_map));
5663		    memset(cur_obj->section_maps + cur_obj->nsection_maps, '\0',
5664			   sg->nsects * sizeof(struct section_map));
5665		}
5666		s = (struct section *)
5667		    ((char *)sg + sizeof(struct segment_command));
5668		for(j = 0 ; j < sg->nsects ; j++){
5669		    cur_obj->section_maps[cur_obj->nsection_maps++].s = s;
5670		    /* check to see that segment name in the section structure
5671		       matches the one in the segment command if this is not in
5672		       an MH_OBJECT filetype */
5673		    if(mh->filetype != MH_OBJECT &&
5674		       strcmp(sg->segname, s->segname) != 0){
5675			error_with_cur_obj("segment name %.16s of section %lu "
5676				"(%.16s,%.16s) in load command %lu does not "
5677				"match segment name %.16s", s->segname, j,
5678				s->segname, s->sectname, i, sg->segname);
5679			return;
5680		    }
5681		    /* check to see that flags (type) of this section is some
5682		       thing the link-editor understands */
5683		    section_type = s->flags & SECTION_TYPE;
5684		    if(section_type != S_REGULAR &&
5685		       section_type != S_ZEROFILL &&
5686		       section_type != S_CSTRING_LITERALS &&
5687		       section_type != S_4BYTE_LITERALS &&
5688		       section_type != S_8BYTE_LITERALS &&
5689		       section_type != S_LITERAL_POINTERS &&
5690		       section_type != S_NON_LAZY_SYMBOL_POINTERS &&
5691		       section_type != S_LAZY_SYMBOL_POINTERS &&
5692		       section_type != S_SYMBOL_STUBS &&
5693		       section_type != S_COALESCED &&
5694		       section_type != S_MOD_INIT_FUNC_POINTERS &&
5695		       section_type != S_MOD_TERM_FUNC_POINTERS &&
5696		       section_type != S_DTRACE_DOF){
5697			error_with_cur_obj("unknown flags (type) of section %lu"
5698					   " (%.16s,%.16s) in load command %lu",
5699					   j, s->segname, s->sectname, i);
5700			return;
5701		    }
5702		    /* check to make sure the alignment is reasonable */
5703		    if(s->align > MAXSECTALIGN){
5704			error_with_cur_obj("align (%u) of section %lu "
5705			    "(%.16s,%.16s) in load command %lu greater "
5706			    "than maximum section alignment (%d)", s->align,
5707			     j, s->segname, s->sectname, i, MAXSECTALIGN);
5708			return;
5709		    }
5710		    s++;
5711		}
5712		break;
5713
5714	    case LC_SYMTAB:
5715		if(st != NULL){
5716		    error_with_cur_obj("contains more than one LC_SYMTAB load "
5717				       "command");
5718		    return;
5719		}
5720		st = (struct symtab_command *)lc;
5721		if(st->cmdsize != sizeof(struct symtab_command)){
5722		    error_with_cur_obj("cmdsize of load command %lu incorrect "
5723				       "for LC_SYMTAB", i);
5724		    return;
5725		}
5726		break;
5727
5728	    case LC_DYSYMTAB:
5729		if(dyst != NULL){
5730		    error_with_cur_obj("contains more than one LC_DYSYMTAB "
5731				       "load command");
5732		    return;
5733		}
5734		dyst = (struct dysymtab_command *)lc;
5735		if(dyst->cmdsize != sizeof(struct dysymtab_command)){
5736		    error_with_cur_obj("cmdsize of load command %lu incorrect "
5737				       "for LC_DYSYMTAB", i);
5738		    return;
5739		}
5740		break;
5741
5742	    case LC_SYMSEG:
5743	    case LC_IDFVMLIB:
5744	    case LC_LOADFVMLIB:
5745	    case LC_ID_DYLIB:
5746	    case LC_LOAD_DYLIB:
5747	    case LC_LOAD_WEAK_DYLIB:
5748	    case LC_REEXPORT_DYLIB:
5749	    case LC_ID_DYLINKER:
5750	    case LC_LOAD_DYLINKER:
5751	    case LC_UNIXTHREAD:
5752	    case LC_THREAD:
5753	    case LC_IDENT:
5754	    case LC_FVMFILE:
5755	    case LC_PREPAGE:
5756		break;
5757
5758	    default:
5759		error_with_cur_obj("load command %lu unknown cmd", i);
5760		return;
5761	    }
5762	    lc = (struct load_command *)((char *)lc + lc->cmdsize);
5763	}
5764	/*
5765	 * Now the slightly tricky part of faking up a symtab command that
5766	 * appears to have offsets to the symbol and string table when added
5767	 * to the cur_obj->obj_addr get the correct addresses.
5768	 */
5769	if(seg_linkedit == NULL){
5770	    base_program_symtab.cmd = LC_SYMTAB;
5771	    base_program_symtab.cmdsize = sizeof(struct symtab_command);
5772	    base_program_symtab.symoff = (long)symtab - (long)cur_obj->obj_addr;
5773	    base_program_symtab.nsyms = nsyms;
5774	    base_program_symtab.stroff = (long)strtab - (long)cur_obj->obj_addr;
5775	    base_program_symtab.strsize = strsize;
5776	    cur_obj->symtab = &base_program_symtab;
5777	}
5778	else if(st != NULL && st->nsyms != 0){
5779	    if(st->symoff < seg_linkedit->fileoff ||
5780	       st->symoff + st->nsyms * sizeof(struct nlist) >
5781				seg_linkedit->fileoff + seg_linkedit->filesize){
5782		error_with_cur_obj("symbol table is not contained in "
5783				   SEG_LINKEDIT " segment");
5784		return;
5785	    }
5786	    if(st->stroff < seg_linkedit->fileoff ||
5787	       st->stroff + st->strsize >
5788				seg_linkedit->fileoff + seg_linkedit->filesize){
5789		error_with_cur_obj("string table is not contained in "
5790				   SEG_LINKEDIT " segment");
5791		return;
5792	    }
5793	    base_program_symtab = *st;
5794	    base_program_symtab.symoff = (seg_linkedit->vmaddr + (st->symoff -
5795					  seg_linkedit->fileoff)) -
5796					  (long)cur_obj->obj_addr;
5797	    base_program_symtab.stroff = (seg_linkedit->vmaddr + (st->stroff -
5798					  seg_linkedit->fileoff)) -
5799					  (long)cur_obj->obj_addr;
5800	    cur_obj->symtab = &base_program_symtab;
5801	}
5802	/*
5803	 * If this object does not have a symbol table command then set it's
5804	 * symtab pointer to the empty symtab.  This makes symbol number range
5805	 * checks in relocation cleaner.
5806	 */
5807	else{
5808	    cur_obj->symtab = (struct symtab_command *)&empty_symtab;
5809	}
5810
5811	/*
5812	 * Now finish with the base program by doing what would be done in
5813	 * merge() by merging the base program's sections and symbols.
5814	 */
5815	/* merged the base program's sections */
5816	merge_sections();
5817
5818	/* merged the base program's symbols */
5819	merge_symbols();
5820}
5821#endif /* RLD */
5822
5823/*
5824 * check_size_offset() is used by check_cur_obj() to check a pair of sizes,
5825 * and offsets from the object file to see it they are aligned correctly and
5826 * containded with in the file.
5827 */
5828static
5829void
5830check_size_offset(
5831unsigned long size,
5832unsigned long offset,
5833unsigned long align,
5834char *size_str,
5835char *offset_str,
5836unsigned long cmd)
5837{
5838	if(size != 0){
5839	    if(offset % align != 0){
5840#ifdef mc68000
5841		/*
5842		 * For the mc68000 the alignment is only a warning because it
5843		 * can deal with all accesses on bad alignment.
5844		 */
5845		warning_with_cur_obj("%s in load command %lu not aligned on %lu"
5846				     " byte boundary", offset_str, cmd, align);
5847#else /* !defined(mc68000) */
5848		error_with_cur_obj("%s in load command %lu not aligned on %lu "
5849				   "byte boundary", offset_str, cmd, align);
5850#endif /* mc68000 */
5851		return;
5852	    }
5853	    if(offset > cur_obj->obj_size){
5854		error_with_cur_obj("%s in load command %lu extends past the "
5855				   "end of the file", offset_str, cmd);
5856		return;
5857	    }
5858	    if(offset + size > cur_obj->obj_size){
5859		error_with_cur_obj("%s plus %s in load command %lu extends past"
5860				   " the end of the file", offset_str, size_str,
5861				   cmd);
5862		return;
5863	    }
5864	}
5865}
5866
5867/*
5868 * check_size_offset_sect() is used by check_cur_obj() to check a pair of sizes,
5869 * and offsets from a section in the object file to see it they are aligned
5870 * correctly and containded with in the file.
5871 */
5872static
5873void
5874check_size_offset_sect(
5875unsigned long size,
5876unsigned long offset,
5877unsigned long align,
5878char *size_str,
5879char *offset_str,
5880unsigned long cmd,
5881unsigned long sect,
5882char *segname,
5883char *sectname)
5884{
5885	if(size != 0){
5886	    if(offset % align != 0){
5887#ifdef mc68000
5888		/*
5889		 * For the mc68000 the alignment is only a warning because it
5890		 * can deal with all accesses on bad alignment.
5891		 */
5892		warning_with_cur_obj("%s of section %lu (%.16s,%.16s) in load "
5893		    "command %lu not aligned on %lu byte boundary", offset_str,
5894		    sect, segname, sectname, cmd, align);
5895#else /* !defined(mc68000) */
5896		error_with_cur_obj("%s of section %lu (%.16s,%.16s) in load "
5897		    "command %lu not aligned on %lu byte boundary", offset_str,
5898		    sect, segname, sectname, cmd, align);
5899#endif /* mc68000 */
5900		return;
5901	    }
5902	    if(offset > cur_obj->obj_size){
5903		error_with_cur_obj("%s of section %lu (%.16s,%.16s) in load "
5904		    "command %lu extends past the end of the file", offset_str,
5905		    sect, segname, sectname, cmd);
5906		return;
5907	    }
5908	    if(offset + size > cur_obj->obj_size){
5909		error_with_cur_obj("%s plus %s of section %lu (%.16s,%.16s) "
5910		    "in load command %lu extends past the end of the file",
5911		    offset_str, size_str, sect, segname, sectname, cmd);
5912		return;
5913	    }
5914	}
5915}
5916
5917#ifndef RLD
5918/*
5919 * collect_base_obj_segments() collects the segments from the base file on a
5920 * merged segment list used for overlap checking in
5921 * check_for_overlapping_segments().
5922 */
5923static
5924void
5925collect_base_obj_segments(void)
5926{
5927    unsigned long i;
5928    struct mach_header *mh;
5929    struct load_command *lc, *load_commands;
5930    struct segment_command *sg;
5931
5932	mh = (struct mach_header *)base_obj->obj_addr;
5933	load_commands = (struct load_command *)((char *)base_obj->obj_addr +
5934			    sizeof(struct mach_header));
5935	lc = load_commands;
5936	for(i = 0; i < mh->ncmds; i++){
5937	    switch(lc->cmd){
5938	    case LC_SEGMENT:
5939		sg = (struct segment_command *)lc;
5940		add_base_obj_segment(sg, base_obj->file_name);
5941		break;
5942
5943	    default:
5944		break;
5945	    }
5946	    lc = (struct load_command *)((char *)lc + lc->cmdsize);
5947	}
5948}
5949
5950/*
5951 * add_base_obj_segment() adds the specified segment to the list of
5952 * base_obj_segments as comming from the specified base filename.
5953 */
5954static
5955void
5956add_base_obj_segment(
5957struct segment_command *sg,
5958char *filename)
5959{
5960    struct merged_segment **p, *msg;
5961
5962	p = &base_obj_segments;
5963	while(*p){
5964	    msg = *p;
5965	    p = &(msg->next);
5966	}
5967	*p = allocate(sizeof(struct merged_segment));
5968	msg = *p;
5969	memset(msg, '\0', sizeof(struct merged_segment));
5970	msg->sg = *sg;
5971	msg->filename = filename;
5972}
5973
5974#ifndef KLD
5975/*
5976 * symbol_address_compare takes two pointers to pointers to symbol entries,
5977 * and returns an ordering on them by address.  It also looks for STABS
5978 * symbols and if found sets *(int *)fail_p.
5979 */
5980static int
5981symbol_address_compare (void *fail_p, const void *a_p, const void *b_p)
5982{
5983  const struct nlist * const * aa = a_p;
5984  const struct nlist * a = *aa;
5985  const struct nlist * const * bb = b_p;
5986  const struct nlist * b = *bb;
5987
5988  if (a->n_type & N_STAB)
5989    *(int *)fail_p = 1;
5990  if ((a->n_type & N_TYPE) != (b->n_type & N_TYPE))
5991    return (a->n_type & N_TYPE) < (b->n_type & N_TYPE) ? -1 : 1;
5992  if (a->n_value != b->n_value)
5993    {
5994      /* This is before the symbols are swapped, so this routine must
5995	 swap what it needs.  */
5996      if (cur_obj->swapped)
5997	return SWAP_LONG (a->n_value) < SWAP_LONG (b->n_value) ? -1 : 1;
5998      else
5999	return a->n_value < b->n_value ? -1 : 1;
6000    }
6001
6002  else
6003    return 0;
6004}
6005
6006/*
6007 * read_dwarf_info looks for DWARF sections in cur_obj and if found,
6008 * fills in the dwarf_name and dwarf_comp_dir fields in cur_obj.
6009 *
6010 * Once this routine has completed, no section marked with
6011 * S_ATTR_DEBUG will be needed in the link, and so if the object file
6012 * layout is appropriate those sections can be unmapped.
6013 */
6014static void
6015read_dwarf_info(void)
6016{
6017  enum { chunksize = 256 };
6018
6019  struct ld_chunk {
6020    struct ld_chunk * next;
6021    size_t filedata[chunksize];
6022  };
6023
6024  int little_endian;
6025  struct section * debug_info = NULL;
6026  struct section * debug_line = NULL;
6027  struct section * debug_abbrev = NULL;
6028
6029  const char * name;
6030  const char * comp_dir;
6031  uint64_t stmt_list;
6032  int has_stabs = FALSE;
6033
6034  struct line_reader_data * lrd;
6035  /* 'st' is the symbol table, 'sst' is pointers into that table
6036     sorted by the symbol's address.  */
6037  struct nlist *st;
6038  struct nlist **sst;
6039
6040  struct ld_chunk * chunks;
6041  struct ld_chunk * lastchunk;
6042  size_t * symdata;
6043  size_t lastused;
6044  size_t num_line_syms = 0;
6045  size_t dwarf_source_i;
6046  size_t max_files = 0;
6047
6048  struct line_info li_start, li_end;
6049
6050  size_t i;
6051
6052#if __LITTLE_ENDIAN__
6053  little_endian = !cur_obj->swapped;
6054#else
6055  little_endian = cur_obj->swapped;
6056#endif
6057
6058  /* Find the sections containing the DWARF information we need.  */
6059  for (i = 0; i < cur_obj->nsection_maps; i++)
6060    {
6061      struct section * s = cur_obj->section_maps[i].s;
6062
6063      if (strncmp (s->segname, "__DWARF", 16) != 0)
6064	continue;
6065      if (strncmp (s->sectname, "__debug_info", 16) == 0)
6066	debug_info = s;
6067      else if (strncmp (s->sectname, "__debug_line", 16) == 0)
6068	debug_line = s;
6069      else if (strncmp (s->sectname, "__debug_abbrev", 16) == 0)
6070	debug_abbrev = s;
6071    }
6072
6073  /* No DWARF means nothing to do.
6074     However, no line table may just mean that there's no code in this
6075     file, in which case processing continues.  */
6076  if (! debug_info || ! debug_abbrev || ! cur_obj->symtab
6077      || debug_info->size == 0)
6078    return;
6079
6080  /* Read the debug_info (and debug_abbrev) sections, and determine
6081     the name and working directory to put in the SO stabs, and also
6082     the offset into the line number section.  */
6083  if (read_comp_unit ((const uint8_t *) cur_obj->obj_addr + debug_info->offset,
6084		      debug_info->size,
6085		      ((const uint8_t *)cur_obj->obj_addr
6086		       + debug_abbrev->offset),
6087		      debug_abbrev->size, little_endian,
6088		      &name, &comp_dir, &stmt_list)
6089      && name) {
6090    cur_obj->dwarf_name = strdup (name);
6091    if (comp_dir)
6092      cur_obj->dwarf_comp_dir = strdup (comp_dir);
6093    else
6094      cur_obj->dwarf_comp_dir = NULL;
6095  } else {
6096    warning_with_cur_obj("could not understand DWARF debug information");
6097    return;
6098  }
6099
6100  /* If there is no line table, don't do any more processing.  No N_FUN
6101     or N_SOL stabs will be output.  */
6102  if (! debug_line || stmt_list == (uint64_t) -1)
6103    return;
6104
6105  /* At this point check_symbol has not been called, so all the code below
6106     that processes symbols must not assume that the symbol's contents
6107     make any sense.  */
6108
6109  /* Generate the line number information into
6110     cur_obj->dwarf_source_data.  The format of dwarf_source_data is a
6111     sequence of size_t-sized words made up of subsequences.  Each
6112     subsequence describes the source files which the debug_line information
6113     says contributed to the code of the entity starting at a particular
6114     symbol.
6115
6116     The subsequences are sorted by the index of the symbol to which they
6117     refer.  The format of a subsequence is a word containing the index
6118     of the symbol, a word giving the end of the entity starting with
6119     that symbol, and then one or more words which are file numbers
6120     with their high bit set.
6121
6122     A file number is simply an index into cur_obj->dwarf_paths; each
6123     dwarf_paths entry is either NULL (if not used) or the path of the
6124     source file.  */
6125
6126  st = (struct nlist *)(cur_obj->obj_addr + cur_obj->symtab->symoff);
6127  /* The processing is easier if we have a list of symbols sorted by
6128     address.  */
6129  sst = allocate (sizeof (struct nlist *) * cur_obj->symtab->nsyms);
6130  for (i = 0; i < cur_obj->symtab->nsyms; i++)
6131    sst[i] = st + i;
6132  qsort_r (sst, cur_obj->symtab->nsyms, sizeof (struct nlist *), &has_stabs,
6133	   symbol_address_compare);
6134  if (has_stabs) {
6135    error_with_cur_obj("has both STABS and DWARF debugging info");
6136    free (sst);
6137    return;
6138  }
6139
6140  if (stmt_list >= debug_line->size){
6141    warning_with_cur_obj("offset in DWARF debug_info for line number data is too large");
6142    free (sst);
6143    return;
6144  }
6145
6146  lrd = line_open ((const uint8_t *) cur_obj->obj_addr + debug_line->offset
6147		   + stmt_list,
6148		   debug_line->size - stmt_list, little_endian);
6149  if (! lrd) {
6150    warning_with_cur_obj("could not understand DWARF line number information");
6151    free (sst);
6152    return;
6153  }
6154
6155  /* In this first pass, we process the symbols in address order and
6156     put them into a linked list of chunks to avoid having to call
6157     reallocate().  */
6158  chunks = allocate (sizeof (*chunks));
6159  chunks->next = NULL;
6160  lastchunk = chunks;
6161  lastused = 0;
6162  /* There's also an index by symbol number so we can easily sort them
6163     later.  */
6164  symdata = allocate (sizeof (size_t) * cur_obj->symtab->nsyms);
6165  memset (symdata, 0, sizeof (size_t) * cur_obj->symtab->nsyms);
6166
6167  li_start.end_of_sequence = TRUE;
6168  for (i = 0; i < cur_obj->symtab->nsyms; i++){
6169    struct nlist * s = sst[i];
6170    size_t idx = s - st;
6171    struct ld_chunk * symchunk;
6172    size_t n_value = s->n_value;
6173
6174    size_t limit, max_limit;
6175
6176    if ((s->n_type & N_TYPE) != N_SECT
6177	|| s->n_sect == NO_SECT)
6178      continue;
6179    /* Looking for line number information that isn't there is
6180       expensive, so we only look for line numbers for symbols in
6181       sections that might contain instructions.  */
6182    if (! (cur_obj->section_maps[s->n_sect - 1].s->flags
6183	   & (S_ATTR_SOME_INSTRUCTIONS | S_ATTR_PURE_INSTRUCTIONS)))
6184      continue;
6185
6186    if (i + 1 < cur_obj->symtab->nsyms
6187	&& (sst[i + 1]->n_type & N_TYPE) == N_SECT)
6188      limit = sst[i + 1]->n_value;
6189    else
6190      limit = (uint32_t) -1;
6191
6192    if (cur_obj->swapped){
6193      n_value = SWAP_LONG (n_value);
6194      limit = SWAP_LONG (limit);
6195    }
6196
6197    if (li_start.pc > n_value || li_end.pc <= n_value
6198	|| li_start.end_of_sequence)
6199      {
6200	if (! line_find_addr (lrd, &li_start, &li_end, n_value)) {
6201	  if (li_start.end_of_sequence)
6202	    continue;
6203	  else
6204	    goto line_err;
6205	}
6206
6207	/* Make the start...end range as large as possible.  */
6208	if (li_start.file == li_end.file && ! li_end.end_of_sequence)
6209	  if (! line_next (lrd, &li_end, line_stop_file))
6210	    goto line_err;
6211      }
6212
6213    symdata[idx] = lastused + 1;
6214
6215    symchunk = lastchunk;
6216    num_line_syms++;
6217
6218    max_limit = 0;
6219    for (;;)
6220      {
6221	size_t j;
6222	struct ld_chunk * curchunk = symchunk;
6223
6224	/* File numbers this large are probably an error, and if not
6225	   they're certainly too large for this linker to handle.  */
6226	if (li_start.file >= 0x10000000)
6227	  goto line_err;
6228
6229	if (li_end.pc > max_limit)
6230	  max_limit = li_end.pc;
6231
6232	for (j = symdata[idx]; j < lastused; j++)
6233	  {
6234	    if (j % chunksize == 0)
6235	      curchunk = curchunk->next;
6236	    if (curchunk->filedata[j % chunksize] == li_start.file)
6237	      goto skipfile;
6238	  }
6239	lastchunk->filedata[lastused % chunksize] = li_start.file;
6240	lastused++;
6241	if (li_start.file >= max_files)
6242	  max_files = li_start.file + 1;
6243	if (lastused % chunksize == 0)
6244	  {
6245	    lastchunk->next = allocate (sizeof (*chunks));
6246	    lastchunk = lastchunk->next;
6247	    lastchunk->next = NULL;
6248	  }
6249
6250      skipfile:
6251	if (li_end.pc >= limit || li_end.end_of_sequence)
6252	  break;
6253	li_start = li_end;
6254	if (! line_next (lrd, &li_end, line_stop_file))
6255	  goto line_err;
6256      }
6257
6258    /* The function ends at either the next symbol, or after the last
6259       byte which has a line number.  */
6260    if (limit > max_limit)
6261      limit = max_limit;
6262
6263    lastchunk->filedata[lastused % chunksize] = (size_t) -1;
6264    lastused++;
6265    if (lastused % chunksize == 0)
6266      {
6267	lastchunk->next = allocate (sizeof (*chunks));
6268	lastchunk = lastchunk->next;
6269	lastchunk->next = NULL;
6270      }
6271    lastchunk->filedata[lastused % chunksize] = limit - n_value;
6272    lastused++;
6273    if (lastused % chunksize == 0)
6274      {
6275	lastchunk->next = allocate (sizeof (*chunks));
6276	lastchunk = lastchunk->next;
6277	lastchunk->next = NULL;
6278      }
6279  }
6280
6281  free (sst);
6282
6283  /* Now take the data in the chunks out ordered by symbol index, so
6284     the final result can be iterated through easily.  */
6285
6286  cur_obj->dwarf_paths = allocate (max_files * sizeof (const char *));
6287  memset (cur_obj->dwarf_paths, 0, max_files * sizeof (const char *));
6288  cur_obj->dwarf_num_paths = max_files;
6289
6290  cur_obj->dwarf_source_data = allocate ((lastused + num_line_syms*2 + 1)
6291					 * sizeof (size_t));
6292  dwarf_source_i = 0;
6293  for (i = 0; i < cur_obj->symtab->nsyms; i++)
6294    if (symdata[i]) {
6295      struct ld_chunk * symchunk = chunks;
6296      size_t j;
6297      size_t * limit_space;
6298
6299      cur_obj->dwarf_source_data[dwarf_source_i++] = i;
6300      limit_space = cur_obj->dwarf_source_data + dwarf_source_i++;
6301      for (j = 0; j < (symdata[i] - 1) / chunksize; j++)
6302	symchunk = symchunk->next;
6303      for (j = symdata[i] - 1;
6304	   symchunk->filedata[j % chunksize] != (size_t) -1;
6305	   j++) {
6306	size_t filenum = symchunk->filedata[j % chunksize];
6307	cur_obj->dwarf_source_data[dwarf_source_i++] = filenum | 0x80000000;
6308	if (! cur_obj->dwarf_paths[filenum])
6309	  cur_obj->dwarf_paths[filenum] = line_file (lrd, filenum);
6310	if (j % chunksize == chunksize - 1)
6311	  symchunk = symchunk->next;
6312      }
6313      j++;
6314      if (j % chunksize == 0)
6315	symchunk = symchunk->next;
6316      *limit_space = symchunk->filedata[j % chunksize];
6317    }
6318  /* Terminate with 0x7fffffff, which is larger than any valid symbol
6319     index.  */
6320  cur_obj->dwarf_source_data[dwarf_source_i++] = 0x7fffffff;
6321
6322  /* Finish up by freeing everything.  */
6323  line_free (lrd);
6324  free (symdata);
6325  lastchunk = chunks;
6326  while (lastchunk) {
6327    struct ld_chunk * tmp = lastchunk->next;
6328    free (lastchunk);
6329    lastchunk = tmp;
6330  };
6331
6332  return;
6333
6334 line_err:
6335  line_free (lrd);
6336  free (sst);
6337  free (symdata);
6338  lastchunk = chunks;
6339  while (lastchunk) {
6340    struct ld_chunk * tmp = lastchunk->next;
6341    free (lastchunk);
6342    lastchunk = tmp;
6343  };
6344
6345  warning_with_cur_obj("invalid DWARF line number information");
6346  return;
6347}
6348#endif
6349
6350/*
6351 * Mkstr() creates a string that is the concatenation of a variable number of
6352 * strings.  It is pass a variable number of pointers to strings and the last
6353 * pointer is NULL.  It returns the pointer to the string it created.  The
6354 * storage for the string is malloc()'ed can be free()'ed when nolonger needed.
6355 */
6356static
6357char *
6358mkstr(
6359const char *args,
6360...)
6361{
6362    va_list ap;
6363    char *s, *p;
6364    unsigned long size;
6365
6366	size = 0;
6367	if(args != NULL){
6368	    size += strlen(args);
6369	    va_start(ap, args);
6370	    p = (char *)va_arg(ap, char *);
6371	    while(p != NULL){
6372		size += strlen(p);
6373		p = (char *)va_arg(ap, char *);
6374	    }
6375	}
6376	s = allocate(size + 1);
6377	*s = '\0';
6378
6379	if(args != NULL){
6380	    (void)strcat(s, args);
6381	    va_start(ap, args);
6382	    p = (char *)va_arg(ap, char *);
6383	    while(p != NULL){
6384		(void)strcat(s, p);
6385		p = (char *)va_arg(ap, char *);
6386	    }
6387	    va_end(ap);
6388	}
6389	return(s);
6390}
6391#endif /* !defined(RLD) */
6392