diff options
| author | svn2git <svn2git@FreeBSD.org> | 1994-05-01 08:00:00 +0000 |
|---|---|---|
| committer | svn2git <svn2git@FreeBSD.org> | 1994-05-01 08:00:00 +0000 |
| commit | a16f65c7d117419bd266c28a1901ef129a337569 (patch) | |
| tree | 2626602f66dc3551e7a7c7bc9ad763c3bc7ab40a /gnu/usr.bin/ld | |
| parent | 8503f4f13f77abf7adc8f7e329c6f9c1d52b6a20 (diff) | |
Release FreeBSD 1.1upstream/1.1.0_cvsrelease/1.1.0_cvs
This commit was manufactured to restore the state of the 1.1-RELEASE image.
Releases prior to 5.3-RELEASE are omitting the secure/ and crypto/ subdirs.
Diffstat (limited to 'gnu/usr.bin/ld')
33 files changed, 13279 insertions, 0 deletions
diff --git a/gnu/usr.bin/ld/Makefile b/gnu/usr.bin/ld/Makefile new file mode 100644 index 000000000000..26c71c2e45c0 --- /dev/null +++ b/gnu/usr.bin/ld/Makefile @@ -0,0 +1,19 @@ +# $Id: Makefile,v 1.14 1994/02/14 10:02:13 rgrimes Exp $ +# + +PROG= ld +SRCS= ld.c symbol.c lib.c shlib.c warnings.c etc.c rrs.c xbits.c md.c +CFLAGS += -D__FreeBSD__ -I$(.CURDIR) -I$(.CURDIR)/$(MACHINE) + +LDADD+= -lgnumalloc +DPADD+= /usr/lib/libgnumalloc.a +LDFLAGS+= -Xlinker -Bstatic + +SUBDIR= ldconfig ldd +.if !defined(NOPIC) +SUBDIR+= rtld +.endif + +.PATH: $(.CURDIR)/$(MACHINE) + +.include <bsd.prog.mk> diff --git a/gnu/usr.bin/ld/TODO b/gnu/usr.bin/ld/TODO new file mode 100644 index 000000000000..d37a245b40d6 --- /dev/null +++ b/gnu/usr.bin/ld/TODO @@ -0,0 +1,4 @@ +- Make C++ shared libs work (properly resolve ctor and dtor lists) +- Make -r and -X work together for PIC .o files. + +- Avoid duplicatating shared library specifications in link_objects diff --git a/gnu/usr.bin/ld/cplus-dem.c b/gnu/usr.bin/ld/cplus-dem.c new file mode 100644 index 000000000000..3a41c2f6c8e9 --- /dev/null +++ b/gnu/usr.bin/ld/cplus-dem.c @@ -0,0 +1,975 @@ +/*- + * This code is derived from software copyrighted by the Free Software + * Foundation. + */ + +#ifndef lint +/*static char sccsid[] = "from: @(#)cplus-dem.c 5.4 (Berkeley) 4/30/91";*/ +static char rcsid[] = "$Id: cplus-dem.c,v 1.3 1993/11/09 04:18:51 paul Exp $"; +#endif /* not lint */ + +/* Demangler for GNU C++ + Copyright (C) 1989 Free Software Foundation, Inc. + written by James Clark (jjc@jclark.uucp) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 1, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ + +/* This is for g++ 1.36.1 (November 6 version). It will probably + require changes for any other version. + + Modified for g++ 1.36.2 (November 18 version). */ + +/* This file exports one function + + char *cplus_demangle (const char *name) + + If `name' is a mangled function name produced by g++, then + a pointer to a malloced string giving a C++ representation + of the name will be returned; otherwise NULL will be returned. + It is the caller's responsibility to free the string which + is returned. + + For example, + + cplus_demangle ("_foo__1Ai") + + returns + + "A::foo(int)" + + This file imports xmalloc and xrealloc, which are like malloc and + realloc except that they generate a fatal error if there is no + available memory. */ + +/* #define nounderscore 1 /* define this is names don't start with _ */ + +#include <stdio.h> +#include <ctype.h> + +#ifdef USG +#include <memory.h> +#include <string.h> +#else +#include <strings.h> +#define memcpy(s1, s2, n) bcopy ((s2), (s1), (n)) +#define memcmp(s1, s2, n) bcmp ((s2), (s1), (n)) +#define strchr index +#define strrchr rindex +#endif + +#ifndef __STDC__ +#define const +#endif + +#ifdef __STDC__ +extern char *cplus_demangle (const char *type); +#else +extern char *cplus_demangle (); +#endif + +#ifdef __STDC__ +extern char *xmalloc (int); +extern char *xrealloc (char *, int); +#else +extern char *xmalloc (); +extern char *xrealloc (); +#endif + +static char **typevec = 0; +static int ntypes = 0; +static int typevec_size = 0; + +static struct { + const char *in; + const char *out; +} optable[] = { + "new", " new", + "delete", " delete", + "ne", "!=", + "eq", "==", + "ge", ">=", + "gt", ">", + "le", "<=", + "lt", "<", + "plus", "+", + "minus", "-", + "mult", "*", + "convert", "+", /* unary + */ + "negate", "-", /* unary - */ + "trunc_mod", "%", + "trunc_div", "/", + "truth_andif", "&&", + "truth_orif", "||", + "truth_not", "!", + "postincrement", "++", + "postdecrement", "--", + "bit_ior", "|", + "bit_xor", "^", + "bit_and", "&", + "bit_not", "~", + "call", "()", + "cond", "?:", + "alshift", "<<", + "arshift", ">>", + "component", "->", + "indirect", "*", + "method_call", "->()", + "addr", "&", /* unary & */ + "array", "[]", + "nop", "", /* for operator= */ +}; + +/* Beware: these aren't '\0' terminated. */ + +typedef struct { + char *b; /* pointer to start of string */ + char *p; /* pointer after last character */ + char *e; /* pointer after end of allocated space */ +} string; + +#ifdef __STDC__ +static void string_need (string *s, int n); +static void string_delete (string *s); +static void string_init (string *s); +static void string_clear (string *s); +static int string_empty (string *s); +static void string_append (string *p, const char *s); +static void string_appends (string *p, string *s); +static void string_appendn (string *p, const char *s, int n); +static void string_prepend (string *p, const char *s); +#if 0 +static void string_prepends (string *p, string *s); +#endif +static void string_prependn (string *p, const char *s, int n); +static int get_count (const char **type, int *count); +static int do_args (const char **type, string *decl); +static int do_type (const char **type, string *result); +static int do_arg (const char **type, string *result); +static int do_args (const char **type, string *decl); +static void munge_function_name (string *name); +static void remember_type (const char *type, int len); +#else +static void string_need (); +static void string_delete (); +static void string_init (); +static void string_clear (); +static int string_empty (); +static void string_append (); +static void string_appends (); +static void string_appendn (); +static void string_prepend (); +static void string_prepends (); +static void string_prependn (); +static int get_count (); +static int do_args (); +static int do_type (); +static int do_arg (); +static int do_args (); +static void munge_function_name (); +static void remember_type (); +#endif + +char * +cplus_demangle (type) + const char *type; +{ + string decl; + int n; + int success = 0; + int constructor = 0; + int const_flag = 0; + int i; + const char *p; +#ifndef LONGERNAMES + const char *premangle; +#endif + + if (type == NULL || *type == '\0') + return NULL; +#ifndef nounderscore + if (*type++ != '_') + return NULL; +#endif + p = type; + while (*p != '\0' && !(*p == '_' && p[1] == '_')) + p++; + if (*p == '\0') + { + /* destructor */ + if (type[0] == '_' && type[1] == '$' && type[2] == '_') + { + int n = (strlen (type) - 3)*2 + 3 + 2 + 1; + char *tem = (char *) xmalloc (n); + strcpy (tem, type + 3); + strcat (tem, "::~"); + strcat (tem, type + 3); + strcat (tem, "()"); + return tem; + } + /* static data member */ + if (*type != '_' && (p = strchr (type, '$')) != NULL) + { + int n = strlen (type) + 2; + char *tem = (char *) xmalloc (n); + memcpy (tem, type, p - type); + strcpy (tem + (p - type), "::"); + strcpy (tem + (p - type) + 2, p + 1); + return tem; + } + /* virtual table */ + if (type[0] == '_' && type[1] == 'v' && type[2] == 't' && type[3] == '$') + { + int n = strlen (type + 4) + 14 + 1; + char *tem = (char *) xmalloc (n); + strcpy (tem, type + 4); + strcat (tem, " virtual table"); + return tem; + } + return NULL; + } + + string_init (&decl); + + if (p == type) + { + if (!isdigit (p[2])) + { + string_delete (&decl); + return NULL; + } + constructor = 1; + } + else + { + string_appendn (&decl, type, p - type); + munge_function_name (&decl); + } + p += 2; + +#ifndef LONGERNAMES + premangle = p; +#endif + switch (*p) + { + case 'C': + /* a const member function */ + if (!isdigit (p[1])) + { + string_delete (&decl); + return NULL; + } + p += 1; + const_flag = 1; + /* fall through */ + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + n = 0; + do + { + n *= 10; + n += *p - '0'; + p += 1; + } + while (isdigit (*p)); + if (strlen (p) < n) + { + string_delete (&decl); + return NULL; + } + if (constructor) + { + string_appendn (&decl, p, n); + string_append (&decl, "::"); + string_appendn (&decl, p, n); + } + else + { + string_prepend (&decl, "::"); + string_prependn (&decl, p, n); + } + p += n; +#ifndef LONGERNAMES + remember_type (premangle, p - premangle); +#endif + success = do_args (&p, &decl); + if (const_flag) + string_append (&decl, " const"); + break; + case 'F': + p += 1; + success = do_args (&p, &decl); + break; + } + + for (i = 0; i < ntypes; i++) + if (typevec[i] != NULL) + free (typevec[i]); + ntypes = 0; + if (typevec != NULL) + { + free ((char *)typevec); + typevec = NULL; + typevec_size = 0; + } + + if (success) + { + string_appendn (&decl, "", 1); + return decl.b; + } + else + { + string_delete (&decl); + return NULL; + } +} + +static int +get_count (type, count) + const char **type; + int *count; +{ + if (!isdigit (**type)) + return 0; + *count = **type - '0'; + *type += 1; + /* see flush_repeats in cplus-method.c */ + if (isdigit (**type)) + { + const char *p = *type; + int n = *count; + do + { + n *= 10; + n += *p - '0'; + p += 1; + } + while (isdigit (*p)); + if (*p == '_') + { + *type = p + 1; + *count = n; + } + } + return 1; +} + +/* result will be initialised here; it will be freed on failure */ + +static int +do_type (type, result) + const char **type; + string *result; +{ + int n; + int done; + int non_empty = 0; + int success; + string decl; + const char *remembered_type; + + string_init (&decl); + string_init (result); + + done = 0; + success = 1; + while (success && !done) + { + int member; + switch (**type) + { + case 'P': + *type += 1; + string_prepend (&decl, "*"); + break; + + case 'R': + *type += 1; + string_prepend (&decl, "&"); + break; + + case 'T': + *type += 1; + if (!get_count (type, &n) || n >= ntypes) + success = 0; + else + { + remembered_type = typevec[n]; + type = &remembered_type; + } + break; + + case 'F': + *type += 1; + if (!string_empty (&decl) && decl.b[0] == '*') + { + string_prepend (&decl, "("); + string_append (&decl, ")"); + } + if (!do_args (type, &decl) || **type != '_') + success = 0; + else + *type += 1; + break; + + case 'M': + case 'O': + { + int constp = 0; + int volatilep = 0; + + member = **type == 'M'; + *type += 1; + if (!isdigit (**type)) + { + success = 0; + break; + } + n = 0; + do + { + n *= 10; + n += **type - '0'; + *type += 1; + } + while (isdigit (**type)); + if (strlen (*type) < n) + { + success = 0; + break; + } + string_append (&decl, ")"); + string_prepend (&decl, "::"); + string_prependn (&decl, *type, n); + string_prepend (&decl, "("); + *type += n; + if (member) + { + if (**type == 'C') + { + *type += 1; + constp = 1; + } + if (**type == 'V') + { + *type += 1; + volatilep = 1; + } + if (*(*type)++ != 'F') + { + success = 0; + break; + } + } + if ((member && !do_args (type, &decl)) || **type != '_') + { + success = 0; + break; + } + *type += 1; + if (constp) + { + if (non_empty) + string_append (&decl, " "); + else + non_empty = 1; + string_append (&decl, "const"); + } + if (volatilep) + { + if (non_empty) + string_append (&decl, " "); + else + non_empty = 1; + string_append (&decl, "volatilep"); + } + break; + } + + case 'C': + if ((*type)[1] == 'P') + { + *type += 1; + if (!string_empty (&decl)) + string_prepend (&decl, " "); + string_prepend (&decl, "const"); + break; + } + + /* fall through */ + default: + done = 1; + break; + } + } + + done = 0; + non_empty = 0; + while (success && !done) + { + switch (**type) + { + case 'C': + *type += 1; + if (non_empty) + string_append (result, " "); + else + non_empty = 1; + string_append (result, "const"); + break; + case 'U': + *type += 1; + if (non_empty) + string_append (result, " "); + else + non_empty = 1; + string_append (result, "unsigned"); + break; + case 'V': + *type += 1; + if (non_empty) + string_append (result, " "); + else + non_empty = 1; + string_append (result, "volatile"); + break; + default: + done = 1; + break; + } + } + + if (success) + switch (**type) + { + case '\0': + case '_': + break; + case 'v': + *type += 1; + if (non_empty) + string_append (result, " "); + string_append (result, "void"); + break; + case 'x': + *type += 1; + if (non_empty) + string_append (result, " "); + string_append (result, "long long"); + break; + case 'l': + *type += 1; + if (non_empty) + string_append (result, " "); + string_append (result, "long"); + break; + case 'i': + *type += 1; + if (non_empty) + string_append (result, " "); + string_append (result, "int"); + break; + case 's': + *type += 1; + if (non_empty) + string_append (result, " "); + string_append (result, "short"); + break; + case 'c': + *type += 1; + if (non_empty) + string_append (result, " "); + string_append (result, "char"); + break; + case 'r': + *type += 1; + if (non_empty) + string_append (result, " "); + string_append (result, "long double"); + break; + case 'd': + *type += 1; + if (non_empty) + string_append (result, " "); + string_append (result, "double"); + break; + case 'f': + *type += 1; + if (non_empty) + string_append (result, " "); + string_append (result, "float"); + break; + case 'G': + *type += 1; + if (!isdigit (**type)) + { + success = 0; + break; + } + /* fall through */ + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + n = 0; + do + { + n *= 10; + n += **type - '0'; + *type += 1; + } + while (isdigit (**type)); + if (strlen (*type) < n) + { + success = 0; + break; + } + if (non_empty) + string_append (result, " "); + string_appendn (result, *type, n); + *type += n; + break; + default: + success = 0; + break; + } + + if (success) + { + if (!string_empty (&decl)) + { + string_append (result, " "); + string_appends (result, &decl); + } + string_delete (&decl); + return 1; + } + else + { + string_delete (&decl); + string_delete (result); + return 0; + } +} + +/* `result' will be initialised in do_type; it will be freed on failure */ + +static int +do_arg (type, result) + const char **type; + string *result; +{ + const char *start = *type; + + if (!do_type (type, result)) + return 0; + remember_type (start, *type - start); + return 1; +} + +static void +remember_type (start, len) + const char *start; + int len; +{ + char *tem; + + if (ntypes >= typevec_size) + { + if (typevec_size == 0) + { + typevec_size = 3; + typevec = (char **) xmalloc (sizeof (char*)*typevec_size); + } + else + { + typevec_size *= 2; + typevec = (char **) xrealloc ((char *)typevec, sizeof (char*)*typevec_size); + } + } + tem = (char *) xmalloc (len + 1); + memcpy (tem, start, len); + tem[len] = '\0'; + typevec[ntypes++] = tem; +} + +/* `decl' must be already initialised, usually non-empty; + it won't be freed on failure */ + +static int +do_args (type, decl) + const char **type; + string *decl; +{ + string arg; + int need_comma = 0; + + string_append (decl, "("); + + while (**type != '_' && **type != '\0' && **type != 'e' && **type != 'v') + { + if (**type == 'N') + { + int r; + int t; + *type += 1; + if (!get_count (type, &r) || !get_count (type, &t) || t >= ntypes) + return 0; + while (--r >= 0) + { + const char *tem = typevec[t]; + if (need_comma) + string_append (decl, ", "); + if (!do_arg (&tem, &arg)) + return 0; + string_appends (decl, &arg); + string_delete (&arg); + need_comma = 1; + } + } + else + { + if (need_comma) + string_append (decl, ", "); + if (!do_arg (type, &arg)) + return 0; + string_appends (decl, &arg); + string_delete (&arg); + need_comma = 1; + } + } + + if (**type == 'v') + *type += 1; + else if (**type == 'e') + { + *type += 1; + if (need_comma) + string_append (decl, ","); + string_append (decl, "..."); + } + + string_append (decl, ")"); + return 1; +} + +static void +munge_function_name (name) + string *name; +{ + if (!string_empty (name) && name->p - name->b >= 3 + && name->b[0] == 'o' && name->b[1] == 'p' && name->b[2] == '$') + { + int i; + /* see if it's an assignment expression */ + if (name->p - name->b >= 10 /* op$assign_ */ + && memcmp (name->b + 3, "assign_", 7) == 0) + { + for (i = 0; i < sizeof (optable)/sizeof (optable[0]); i++) + { + int len = name->p - name->b - 10; + if (strlen (optable[i].in) == len + && memcmp (optable[i].in, name->b + 10, len) == 0) + { + string_clear (name); + string_append (name, "operator"); + string_append (name, optable[i].out); + string_append (name, "="); + return; + } + } + } + else + { + for (i = 0; i < sizeof (optable)/sizeof (optable[0]); i++) + { + int len = name->p - name->b - 3; + if (strlen (optable[i].in) == len + && memcmp (optable[i].in, name->b + 3, len) == 0) + { + string_clear (name); + string_append (name, "operator"); + string_append (name, optable[i].out); + return; + } + } + } + return; + } + else if (!string_empty (name) && name->p - name->b >= 5 + && memcmp (name->b, "type$", 5) == 0) + { + /* type conversion operator */ + string type; + const char *tem = name->b + 5; + if (do_type (&tem, &type)) + { + string_clear (name); + string_append (name, "operator "); + string_appends (name, &type); + string_delete (&type); + return; + } + } +} + +/* a mini string-handling package */ + +static void +string_need (s, n) + string *s; + int n; +{ + if (s->b == NULL) + { + if (n < 32) + n = 32; + s->p = s->b = (char *) xmalloc (n); + s->e = s->b + n; + } + else if (s->e - s->p < n) + { + int tem = s->p - s->b; + n += tem; + n *= 2; + s->b = (char *) xrealloc (s->b, n); + s->p = s->b + tem; + s->e = s->b + n; + } +} + +static void +string_delete (s) + string *s; +{ + if (s->b != NULL) + { + free (s->b); + s->b = s->e = s->p = NULL; + } +} + +static void +string_init (s) + string *s; +{ + s->b = s->p = s->e = NULL; +} + +static void +string_clear (s) + string *s; +{ + s->p = s->b; +} + +static int +string_empty (s) + string *s; +{ + return s->b == s->p; +} + +static void +string_append (p, s) + string *p; + const char *s; +{ + int n; + if (s == NULL || *s == '\0') + return; + n = strlen (s); + string_need (p, n); + memcpy (p->p, s, n); + p->p += n; +} + +static void +string_appends (p, s) + string *p, *s; +{ + int n; + if (s->b == s->p) + return; + n = s->p - s->b; + string_need (p, n); + memcpy (p->p, s->b, n); + p->p += n; +} + +static void +string_appendn (p, s, n) + string *p; + const char *s; + int n; +{ + if (n == 0) + return; + string_need (p, n); + memcpy (p->p, s, n); + p->p += n; +} + +static void +string_prepend (p, s) + string *p; + const char *s; +{ + if (s == NULL || *s == '\0') + return; + string_prependn (p, s, strlen (s)); +} + +#if 0 +static void +string_prepends (p, s) + string *p, *s; +{ + if (s->b == s->p) + return; + string_prependn (p, s->b, s->p - s->b); +} +#endif + +static void +string_prependn (p, s, n) + string *p; + const char *s; + int n; +{ + char *q; + + if (n == 0) + return; + string_need (p, n); + for (q = p->p - 1; q >= p->b; q--) + q[n] = q[0]; + memcpy (p->b, s, n); + p->p += n; +} diff --git a/gnu/usr.bin/ld/etc.c b/gnu/usr.bin/ld/etc.c new file mode 100644 index 000000000000..27e2c5661895 --- /dev/null +++ b/gnu/usr.bin/ld/etc.c @@ -0,0 +1,151 @@ +/* + * $Id: etc.c,v 1.7 1994/02/13 20:41:05 jkh Exp $ + */ + +#include <sys/param.h> +#include <stdio.h> +#include <stdlib.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <sys/file.h> +#include <sys/time.h> +#include <fcntl.h> +#include <ar.h> +#include <ranlib.h> +#include <a.out.h> +#include <stab.h> +#include <string.h> +#if __STDC__ +#include <stdarg.h> +#else +#include <varargs.h> +#endif + +#include "ld.h" + +/* + * Report a nonfatal error. + */ + +void +#if __STDC__ +error(char *fmt, ...) +#else +error(fmt, va_alist) + char *fmt; + va_dcl +#endif +{ + va_list ap; +#if __STDC__ + va_start(ap, fmt); +#else + va_start(ap); +#endif + (void)fprintf(stderr, "%s: ", progname); + (void)vfprintf(stderr, fmt, ap); + (void)fprintf(stderr, "\n"); + va_end(ap); +} + +void (*fatal_cleanup_hook)__P((void)); +/* + * Report a fatal error. + */ + +void +#if __STDC__ +fatal(char *fmt, ...) +#else +fatal(fmt, va_alist) + char *fmt; + va_dcl +#endif +{ + va_list ap; +#if __STDC__ + va_start(ap, fmt); +#else + va_start(ap); +#endif + (void)fprintf(stderr, "%s: ", progname); + (void)vfprintf(stderr, fmt, ap); + (void)fprintf(stderr, "\n"); + va_end(ap); + + if (fatal_cleanup_hook) + (*fatal_cleanup_hook)(); + exit(1); +} + + +/* + * Return a newly-allocated string whose contents concatenate + * the strings S1, S2, S3. + */ + +char * +concat(s1, s2, s3) + const char *s1, *s2, *s3; +{ + register int len1 = strlen (s1), + len2 = strlen (s2), + len3 = strlen (s3); + + register char *result = (char *) xmalloc (len1 + len2 + len3 + 1); + + strcpy (result, s1); + strcpy (result + len1, s2); + strcpy (result + len1 + len2, s3); + result[len1 + len2 + len3] = 0; + + return result; +} + +/* Parse the string ARG using scanf format FORMAT, and return the result. + If it does not parse, report fatal error + generating the error message using format string ERROR and ARG as arg. */ + +int +parse(arg, format, error) + char *arg, *format, *error; +{ + int x; + if (1 != sscanf (arg, format, &x)) + fatal (error, arg); + return x; +} + +/* Like malloc but get fatal error if memory is exhausted. */ + +void * +xmalloc(size) + int size; +{ + register void *result = (void *)malloc (size); + + if (!result) + fatal ("virtual memory exhausted", 0); + + return result; +} + +/* Like realloc but get fatal error if memory is exhausted. */ + +void * +xrealloc(ptr, size) + void *ptr; + int size; +{ + register void *result; + + if (ptr == NULL) + result = (void *)malloc (size); + else + result = (void *)realloc (ptr, size); + + if (!result) + fatal ("virtual memory exhausted", 0); + + return result; +} diff --git a/gnu/usr.bin/ld/i386/md-static-funcs.c b/gnu/usr.bin/ld/i386/md-static-funcs.c new file mode 100644 index 000000000000..f52ce066f19b --- /dev/null +++ b/gnu/usr.bin/ld/i386/md-static-funcs.c @@ -0,0 +1,17 @@ +/* + * $Id: md-static-funcs.c,v 1.2 1994/02/13 20:42:06 jkh Exp $ + * + * Called by ld.so when onanating. + * This *must* be a static function, so it is not called through a jmpslot. + */ + +static void +md_relocate_simple(r, relocation, addr) +struct relocation_info *r; +long relocation; +char *addr; +{ +if (r->r_relative) + *(long *)addr += relocation; +} + diff --git a/gnu/usr.bin/ld/i386/md.c b/gnu/usr.bin/ld/i386/md.c new file mode 100644 index 000000000000..2e206a9eb25d --- /dev/null +++ b/gnu/usr.bin/ld/i386/md.c @@ -0,0 +1,357 @@ +/* + * Copyright (c) 1993 Paul Kranenburg + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Paul Kranenburg. + * 4. The name of the author may not be used to endorse or promote products + * derived from this software withough specific prior written permission + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * $Id: md.c,v 1.9 1994/02/13 20:42:09 jkh Exp $ + */ + +#include <sys/param.h> +#include <stdio.h> +#include <stdlib.h> +#include <sys/types.h> +#include <fcntl.h> +#include <a.out.h> +#include <stab.h> +#include <string.h> + +#include "ld.h" + +/* + * Get relocation addend corresponding to relocation record RP + * from address ADDR + */ +long +md_get_addend(rp, addr) +struct relocation_info *rp; +unsigned char *addr; +{ + switch (RELOC_TARGET_SIZE(rp)) { + case 0: + return get_byte(addr); + break; + case 1: + return get_short(addr); + break; + case 2: + return get_long(addr); + break; + } +} + +/* + * Put RELOCATION at ADDR according to relocation record RP. + */ +void +md_relocate(rp, relocation, addr, relocatable_output) +struct relocation_info *rp; +long relocation; +unsigned char *addr; +{ + switch (RELOC_TARGET_SIZE(rp)) { + case 0: + put_byte(addr, relocation); + break; + case 1: + put_short(addr, relocation); + break; + case 2: + put_long(addr, relocation); + break; + default: + fatal("Unsupported relocation size: %x", RELOC_TARGET_SIZE(rp)); + } +} + +/* + * Machine dependent part of claim_rrs_reloc(). + * Set RRS relocation type. + */ +int +md_make_reloc(rp, r, type) +struct relocation_info *rp, *r; +int type; +{ + /* Relocation size */ + r->r_length = rp->r_length; + + if (RELOC_PCREL_P(rp)) + r->r_pcrel = 1; + + if (type & RELTYPE_RELATIVE) + r->r_relative = 1; + + if (type & RELTYPE_COPY) + r->r_copy = 1; + + return 0; +} + +/* + * Set up a transfer from jmpslot at OFFSET (relative to the PLT table) + * to the binder slot (which is at offset 0 of the PLT). + */ +void +md_make_jmpslot(sp, offset, index) +jmpslot_t *sp; +long offset; +long index; +{ + /* + * i386 PC-relative "fixed point" is located right after the + * instruction it pertains to. + */ + u_long fudge = - (sizeof(sp->opcode) + sizeof(sp->addr) + offset); + + sp->opcode = CALL; +#if 0 + sp->addr = fudge; +#else + sp->addr[0] = fudge & 0xffff; + sp->addr[1] = fudge >> 16; +#endif + sp->reloc_index = index; +} + +/* + * Set up a "direct" transfer (ie. not through the run-time binder) from + * jmpslot at OFFSET to ADDR. Used by `ld' when the SYMBOLIC flag is on, + * and by `ld.so' after resolving the symbol. + * On the i386, we use the JMP instruction which is PC relative, so no + * further RRS relocations will be necessary for such a jmpslot. + */ +void +md_fix_jmpslot(sp, offset, addr) +jmpslot_t *sp; +long offset; +u_long addr; +{ + u_long fudge = addr - (sizeof(sp->opcode) + sizeof(sp->addr) + offset); + + sp->opcode = JUMP; +#if 0 + sp->addr = fudge; +#else + sp->addr[0] = fudge & 0xffff; + sp->addr[1] = fudge >> 16; +#endif + sp->reloc_index = 0; +} + +/* + * Update the relocation record for a RRS jmpslot. + */ +void +md_make_jmpreloc(rp, r, type) +struct relocation_info *rp, *r; +int type; +{ + jmpslot_t *sp; + + /* + * Fix relocation address to point to the correct + * location within this jmpslot. + */ + r->r_address += sizeof(sp->opcode); + + /* Relocation size */ + r->r_length = 2; + + /* Set relocation type */ + r->r_jmptable = 1; + if (type & RELTYPE_RELATIVE) + r->r_relative = 1; + +} + +/* + * Set relocation type for a RRS GOT relocation. + */ +void +md_make_gotreloc(rp, r, type) +struct relocation_info *rp, *r; +int type; +{ + r->r_baserel = 1; + if (type & RELTYPE_RELATIVE) + r->r_relative = 1; + + /* Relocation size */ + r->r_length = 2; +} + +/* + * Set relocation type for a RRS copy operation. + */ +void +md_make_cpyreloc(rp, r) +struct relocation_info *rp, *r; +{ + /* Relocation size */ + r->r_length = 2; + + r->r_copy = 1; +} + +void +md_set_breakpoint(where, savep) +long where; +long *savep; +{ + *savep = *(long *)where; + *(char *)where = TRAP; +} + +#ifndef RTLD + +#ifdef FreeBSD +int netzmagic; +#endif + +/* + * Initialize (output) exec header such that useful values are + * obtained from subsequent N_*() macro evaluations. + */ +void +md_init_header(hp, magic, flags) +struct exec *hp; +int magic, flags; +{ +#ifdef NetBSD + if (oldmagic || magic == QMAGIC) + hp->a_midmag = magic; + else + N_SETMAGIC((*hp), magic, MID_I386, flags); +#endif +#ifdef FreeBSD + if (oldmagic) + hp->a_midmag = magic; + else if (netzmagic) + N_SETMAGIC_NET((*hp), magic, MID_I386, flags); + else + N_SETMAGIC((*hp), magic, MID_I386, flags); +#endif + + /* TEXT_START depends on the value of outheader.a_entry. */ + if (!(link_mode & SHAREABLE)) /*WAS: if (entry_symbol) */ + hp->a_entry = PAGSIZ; +} +#endif /* RTLD */ + + +#ifdef NEED_SWAP +/* + * Byte swap routines for cross-linking. + */ + +void +md_swapin_exec_hdr(h) +struct exec *h; +{ + int skip = 0; + + if (!N_BADMAG(*h)) + skip = 1; + + swap_longs((long *)h + skip, sizeof(*h)/sizeof(long) - skip); +} + +void +md_swapout_exec_hdr(h) +struct exec *h; +{ + /* NetBSD: Always leave magic alone */ + int skip = 1; +#if 0 + if (N_GETMAGIC(*h) == OMAGIC) + skip = 0; +#endif + + swap_longs((long *)h + skip, sizeof(*h)/sizeof(long) - skip); +} + + +void +md_swapin_reloc(r, n) +struct relocation_info *r; +int n; +{ + int bits; + + for (; n; n--, r++) { + r->r_address = md_swap_long(r->r_address); + bits = ((int *)r)[1]; + r->r_symbolnum = md_swap_long(bits & 0xffffff00); + r->r_pcrel = (bits & 1); + r->r_length = ((bits >> 1) & 3); + r->r_extern = ((bits >> 3) & 1); + r->r_baserel = ((bits >> 4) & 1); + r->r_jmptable = ((bits >> 5) & 1); + r->r_relative = ((bits >> 6) & 1); +#ifdef N_SIZE + r->r_copy = ((bits >> 7) & 1); +#endif + } +} + +void +md_swapout_reloc(r, n) +struct relocation_info *r; +int n; +{ + int bits; + + for (; n; n--, r++) { + r->r_address = md_swap_long(r->r_address); + bits = (md_swap_long(r->r_symbolnum) & 0xffffff00); + bits |= (r->r_pcrel & 1); + bits |= ((r->r_length << 1) & 6); + bits |= ((r->r_extern << 3) & 8); + bits |= ((r->r_baserel << 4) & 0x10); + bits |= ((r->r_jmptable << 5) & 0x20); + bits |= ((r->r_relative << 6) & 0x40); +#ifdef N_SIZE + bits |= ((r->r_copy << 7) & 0x80); +#endif + ((int *)r)[1] = bits; + } +} + +void +md_swapout_jmpslot(j, n) +jmpslot_t *j; +int n; +{ + for (; n; n--, j++) { + j->opcode = md_swap_short(j->opcode); + j->addr[0] = md_swap_short(j->addr[0]); + j->addr[1] = md_swap_short(j->addr[1]); + j->reloc_index = md_swap_short(j->reloc_index); + } +} + +#endif /* NEED_SWAP */ diff --git a/gnu/usr.bin/ld/i386/md.h b/gnu/usr.bin/ld/i386/md.h new file mode 100644 index 000000000000..f98bb5eef2a1 --- /dev/null +++ b/gnu/usr.bin/ld/i386/md.h @@ -0,0 +1,257 @@ +/* + * Copyright (c) 1993 Paul Kranenburg + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Paul Kranenburg. + * 4. The name of the author may not be used to endorse or promote products + * derived from this software withough specific prior written permission + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * $Id: md.h,v 1.9 1994/02/13 20:42:11 jkh Exp $ + */ + + +#if defined(CROSS_LINKER) && defined(XHOST) && XHOST==sparc + +#define NEED_SWAP + +#endif + +#define MAX_ALIGNMENT (sizeof (long)) + +#ifdef NetBSD +#define PAGSIZ __LDPGSZ +#else +#define PAGSIZ 4096 +#endif + +#if defined(NetBSD) || defined(CROSS_LINKER) + +#define N_SET_FLAG(ex,f) (oldmagic || N_GETMAGIC(ex)==QMAGIC ? (0) : \ + N_SETMAGIC(ex, \ + N_GETMAGIC(ex), \ + MID_MACHINE, \ + N_GETFLAG(ex)|(f))) + +#define N_IS_DYNAMIC(ex) ((N_GETFLAG(ex) & EX_DYNAMIC)) + +#define N_BADMID(ex) \ + (N_GETMID(ex) != 0 && N_GETMID(ex) != MID_MACHINE) + +#endif + +/* + * FreeBSD does it differently + */ +#ifdef FreeBSD +#define N_SET_FLAG(ex,f) (oldmagic ? (0) : \ + (netzmagic == 0 ? \ + N_SETMAGIC(ex, \ + N_GETMAGIC(ex), \ + MID_MACHINE, \ + N_GETFLAG(ex)|(f)) : \ + N_SETMAGIC_NET(ex, \ + N_GETMAGIC_NET(ex), \ + MID_MACHINE, \ + N_GETFLAG_NET(ex)|(f)) )) + +#define N_IS_DYNAMIC(ex) ((N_GETMAGIC_NET(ex) == ZMAGIC) ? \ + ((N_GETFLAG_NET(ex) & EX_DYNAMIC)) : \ + ((N_GETFLAG(ex) & EX_DYNAMIC) )) +#define N_BADMID(ex) 0 +#endif + +/* + * Should be handled by a.out.h ? + */ +#define N_ADJUST(ex) (((ex).a_entry < PAGSIZ) ? -PAGSIZ : 0) +#define TEXT_START(ex) (N_TXTADDR(ex) + N_ADJUST(ex)) +#define DATA_START(ex) (N_DATADDR(ex) + N_ADJUST(ex)) + +#define RELOC_STATICS_THROUGH_GOT_P(r) (0) +#define JMPSLOT_NEEDS_RELOC (0) + +#define md_got_reloc(r) (0) + +#define md_get_rt_segment_addend(r,a) md_get_addend(r,a) + +/* Width of a Global Offset Table entry */ +#define GOT_ENTRY_SIZE 4 +typedef long got_t; + +typedef struct jmpslot { + u_short opcode; + u_short addr[2]; + u_short reloc_index; +#define JMPSLOT_RELOC_MASK 0xffff +} jmpslot_t; + +#define NOP 0x90 +#define CALL 0xe890 /* NOP + CALL opcode */ +#define JUMP 0xe990 /* NOP + JMP opcode */ +#define TRAP 0xcc /* INT 3 */ + +/* + * Byte swap defs for cross linking + */ + +#if !defined(NEED_SWAP) + +#define md_swapin_exec_hdr(h) +#define md_swapout_exec_hdr(h) +#define md_swapin_symbols(s,n) +#define md_swapout_symbols(s,n) +#define md_swapin_zsymbols(s,n) +#define md_swapout_zsymbols(s,n) +#define md_swapin_reloc(r,n) +#define md_swapout_reloc(r,n) +#define md_swapin__dynamic(l) +#define md_swapout__dynamic(l) +#define md_swapin_section_dispatch_table(l) +#define md_swapout_section_dispatch_table(l) +#define md_swapin_so_debug(d) +#define md_swapout_so_debug(d) +#define md_swapin_rrs_hash(f,n) +#define md_swapout_rrs_hash(f,n) +#define md_swapin_sod(l,n) +#define md_swapout_sod(l,n) +#define md_swapout_jmpslot(j,n) +#define md_swapout_got(g,n) +#define md_swapin_ranlib_hdr(h,n) +#define md_swapout_ranlib_hdr(h,n) + +#endif /* NEED_SWAP */ + +#ifdef CROSS_LINKER + +#ifdef NEED_SWAP + +/* Define IO byte swapping routines */ + +void md_swapin_exec_hdr __P((struct exec *)); +void md_swapout_exec_hdr __P((struct exec *)); +void md_swapin_reloc __P((struct relocation_info *, int)); +void md_swapout_reloc __P((struct relocation_info *, int)); +void md_swapout_jmpslot __P((jmpslot_t *, int)); + +#define md_swapin_symbols(s,n) swap_symbols(s,n) +#define md_swapout_symbols(s,n) swap_symbols(s,n) +#define md_swapin_zsymbols(s,n) swap_zsymbols(s,n) +#define md_swapout_zsymbols(s,n) swap_zsymbols(s,n) +#define md_swapin__dynamic(l) swap__dynamic(l) +#define md_swapout__dynamic(l) swap__dynamic(l) +#define md_swapin_section_dispatch_table(l) swap_section_dispatch_table(l) +#define md_swapout_section_dispatch_table(l) swap_section_dispatch_table(l) +#define md_swapin_so_debug(d) swap_so_debug(d) +#define md_swapout_so_debug(d) swap_so_debug(d) +#define md_swapin_rrs_hash(f,n) swap_rrs_hash(f,n) +#define md_swapout_rrs_hash(f,n) swap_rrs_hash(f,n) +#define md_swapin_sod(l,n) swapin_sod(l,n) +#define md_swapout_sod(l,n) swapout_sod(l,n) +#define md_swapout_got(g,n) swap_longs((long*)(g),n) +#define md_swapin_ranlib_hdr(h,n) swap_ranlib_hdr(h,n) +#define md_swapout_ranlib_hdr(h,n) swap_ranlib_hdr(h,n) + +#define md_swap_short(x) ( (((x) >> 8) & 0xff) | (((x) & 0xff) << 8) ) + +#define md_swap_long(x) ( (((x) >> 24) & 0xff ) | (((x) >> 8 ) & 0xff00 ) | \ + (((x) << 8 ) & 0xff0000) | (((x) << 24) & 0xff000000)) + +#define get_byte(p) ( ((unsigned char *)(p))[0] ) + +#define get_short(p) ( ( ((unsigned char *)(p))[1] << 8) | \ + ( ((unsigned char *)(p))[0] ) \ + ) +#define get_long(p) ( ( ((unsigned char *)(p))[3] << 24) | \ + ( ((unsigned char *)(p))[2] << 16) | \ + ( ((unsigned char *)(p))[1] << 8 ) | \ + ( ((unsigned char *)(p))[0] ) \ + ) + +#define put_byte(p, v) { ((unsigned char *)(p))[0] = ((unsigned long)(v)); } + +#define put_short(p, v) { ((unsigned char *)(p))[1] = \ + ((((unsigned long)(v)) >> 8) & 0xff); \ + ((unsigned char *)(p))[0] = \ + ((((unsigned long)(v)) ) & 0xff); } + +#define put_long(p, v) { ((unsigned char *)(p))[3] = \ + ((((unsigned long)(v)) >> 24) & 0xff); \ + ((unsigned char *)(p))[2] = \ + ((((unsigned long)(v)) >> 16) & 0xff); \ + ((unsigned char *)(p))[1] = \ + ((((unsigned long)(v)) >> 8) & 0xff); \ + ((unsigned char *)(p))[0] = \ + ((((unsigned long)(v)) ) & 0xff); } + +#else /* We need not swap, but must pay attention to alignment: */ + +#define md_swap_short(x) (x) +#define md_swap_long(x) (x) + +#define get_byte(p) ( ((unsigned char *)(p))[0] ) + +#define get_short(p) ( ( ((unsigned char *)(p))[0] << 8) | \ + ( ((unsigned char *)(p))[1] ) \ + ) + +#define get_long(p) ( ( ((unsigned char *)(p))[0] << 24) | \ + ( ((unsigned char *)(p))[1] << 16) | \ + ( ((unsigned char *)(p))[2] << 8 ) | \ + ( ((unsigned char *)(p))[3] ) \ + ) + + +#define put_byte(p, v) { ((unsigned char *)(p))[0] = ((unsigned long)(v)); } + +#define put_short(p, v) { ((unsigned char *)(p))[0] = \ + ((((unsigned long)(v)) >> 8) & 0xff); \ + ((unsigned char *)(p))[1] = \ + ((((unsigned long)(v)) ) & 0xff); } + +#define put_long(p, v) { ((unsigned char *)(p))[0] = \ + ((((unsigned long)(v)) >> 24) & 0xff); \ + ((unsigned char *)(p))[1] = \ + ((((unsigned long)(v)) >> 16) & 0xff); \ + ((unsigned char *)(p))[2] = \ + ((((unsigned long)(v)) >> 8) & 0xff); \ + ((unsigned char *)(p))[3] = \ + ((((unsigned long)(v)) ) & 0xff); } + +#endif /* NEED_SWAP */ + +#else /* Not a cross linker: use native */ + +#define md_swap_short(x) (x) +#define md_swap_long(x) (x) + +#define get_byte(where) (*(char *)(where)) +#define get_short(where) (*(short *)(where)) +#define get_long(where) (*(long *)(where)) + +#define put_byte(where,what) (*(char *)(where) = (what)) +#define put_short(where,what) (*(short *)(where) = (what)) +#define put_long(where,what) (*(long *)(where) = (what)) + +#endif /* CROSS_LINKER */ + diff --git a/gnu/usr.bin/ld/i386/mdprologue.S b/gnu/usr.bin/ld/i386/mdprologue.S new file mode 100644 index 000000000000..b5f13520c15e --- /dev/null +++ b/gnu/usr.bin/ld/i386/mdprologue.S @@ -0,0 +1,124 @@ +/* + * Copyright (c) 1993 Paul Kranenburg + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Paul Kranenburg. + * 4. The name of the author may not be used to endorse or promote products + * derived from this software withough specific prior written permission + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * $Id: mdprologue.S,v 1.3 1993/12/10 10:16:00 jkh Exp $ + */ + +/* + * i386 run-time link editor entry points. + */ + +#include <sys/syscall.h> +#define LCALL(x,y) .byte 0x9a ; .long y; .word x + + .text + .globl _binder, _binder_entry + +/* + * _rtl(int version, struct crt_ldso *crtp) + */ +#define FRAME 12 /* Size of stack frame */ + + +_rtl: # crt0 calls us here + pushl %ebp # Allocate stack frame + movl %esp, %ebp + subl $FRAME, %esp + pushl %ebx + call 1f # PIC function prologue +1: + popl %ebx + addl $_GLOBAL_OFFSET_TABLE_+[.-1b], %ebx + + movl 12(%ebp), %eax # Extract data from interface structure + movl (%eax),%eax # base address of ld.so (first field) + # setup arguments for rtld() + movl (%ebx), %ecx # 1st entry in GOT is our __DYNAMIC + addl %eax, %ecx # add load address + pushl %ecx # 3rd arg + pushl 12(%ebp) # 2nd arg == &crt. + pushl 8(%ebp) # 1st arg == version + addl _rtld@GOT(%ebx), %eax # relocate address of function + call %eax # _rtld(version, crtp, DYNAMIC) + addl $12,%esp # pop arguments + + movl (-FRAME-4)(%ebp), %ebx # restore %ebx + leave # remove stack frame, + ret # lets rock + + # First call to a procedure generally comes through here for + # binding. + +_binder_entry: + pushl %ebp # setup a stack frame + movl %esp, %ebp + pusha # save all regs + + movl $0, %eax # clear + movl 4(%ebp), %esi # return address in PLT + movw (%esi), %ax # get hold of relocation number + subl $6, %esi # make it point to the jmpslot + + pushl %eax # pushd arguments + pushl %esi # + call _binder@PLT # _binder(rpc, index) + addl $8, %esp # pop arguments + movl %eax, 4(%ebp) # return value from _binder() == actual + # address of function + popa # restore regs + leave # remove our stack frame + ret + + # Special system call stubs which return real and effective user and group + # ids. Saves overhead of making separate calls for each. + # !! Relies on compatability option in BSD 4.three-and-a-half + + .globl _getreuid, _getregid +_getreuid: + lea SYS_getuid, %eax + LCALL(7,0) + jc out + movl 4(%esp), %ecx # get 1st arg + movl %eax, (%ecx) # put value in it + movl 8(%esp), %ecx # same for 2nd arg + movl %edx, (%ecx) # + ret # done + +_getregid: + lea SYS_getgid, %eax + LCALL(7,0) + jc out + movl 4(%esp), %ecx # get 1st arg + movl %eax, (%ecx) # put value in it + movl 8(%esp), %ecx # same for 2nd arg + movl %edx, (%ecx) # + ret # done + +out: jmp cerror@PLT # Call common error routine + diff --git a/gnu/usr.bin/ld/ld.1 b/gnu/usr.bin/ld/ld.1 new file mode 100644 index 000000000000..b181fd70f9cc --- /dev/null +++ b/gnu/usr.bin/ld/ld.1 @@ -0,0 +1,202 @@ +.\" +.\" Copyright (c) 1993 Paul Kranenburg +.\" All rights reserved. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions +.\" are met: +.\" 1. Redistributions of source code must retain the above copyright +.\" notice, this list of conditions and the following disclaimer. +.\" 2. Redistributions in binary form must reproduce the above copyright +.\" notice, this list of conditions and the following disclaimer in the +.\" documentation and/or other materials provided with the distribution. +.\" 3. All advertising materials mentioning features or use of this software +.\" must display the following acknowledgement: +.\" This product includes software developed by Paul Kranenburg. +.\" 3. The name of the author may not be used to endorse or promote products +.\" derived from this software without specific prior written permission +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR +.\" IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +.\" OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +.\" IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, +.\" INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +.\" NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +.\" DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +.\" THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +.\" (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +.\" THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +.\" +.\" $Id: ld.1,v 1.5.2.1 1994/05/01 16:03:59 jkh Exp $ +.\" +.Dd October 14, 1993 +.Dt LD 8 +.Os FreeBSD 1.1 +.Sh NAME +.Nm ld +.Nd link editor +.Sh SYNOPSIS +.Nm ld +.Op Fl MNnrSstXxz +.Bk -words +.Op Fl A Ar symbol-file +.Op Fl assert Ar keyword +.Op Fl B Ar linkmode +.Op Fl D Ar datasize +.Op Fl d Ar c +.Op Fl d Ar p +.Op Fl e Ar entry +.Op Fl l Ar library-specifier +.Op Fl L Ar library-search-path +.Op Fl o Ar filename +.Op Fl T Ar address +.Op Fl u Ar symbol +.Op Fl V Ar shlib-version +.Op Fl y Ar symbol +.Ek +.Sh DESCRIPTION +.Nm +combines the object and archive files given on the command line into a new +object file. The output object file is either an executable program, a +shared object suitable for loading at run-time, or an object file that can +once again be processed by +.Nm ld. +Object files and archives are processed in the order given on the command line. +.Pp +The options are as follows: +.Pp +.Bl -tag -width indent +.It Fl A Ar symbol-file +The the symbol-file is taken as a base for link-editing the object files +on the command line. +.It Fl a\&ssert Ar keyword +This option has currently no effect. It is here for compatibility with +SunOS ld. All conditions which would cause a Sun assertion to fail will +currently always cause error or warning messages from +.Nm ld\&. +.It Fl B Ar dynamic +Specifies that linking against dynamic libraries can take place. If a library +specifier of the form -lx appears on the command line, +.Nm ld +searches for a library of the from libx.so.n.m (see the +.Ar l +option) according to the search rules in effect. If such a file can not be +found a traditional archive is looked for. +This options can appear anywhere on the command line and is complementary +to -Bstatic. +.It Fl B Ar static +The counterpart of -Bdynamic. This option turns off dynamic linking for +all library specifiers until a -Bdynamic is once again given. Any explicitly +mentioned shared object encountered on the command line while this option is +in effect is flagged as an error. +.It Fl B Ar shareable +Instructs the linker to build a shared object from the object files rather +than a normal executable image. +.It Fl B Ar symbolic +This option causes all symbolic references in the output to be resolved in +this link-edit session. The only remaining run-time relocation requirements are +.Em base-relative +relocations, ie. translation with respect to the load address. Failure to +resolve any symbolic reference causes an error to be reported. +.It Fl B Ar forcearchive +Force all members of archives to be loaded, whether or not such members +contribute a definition to any plain object files. Useful for making a +shared library from an archive of PIC objects without having to unpack +the archive. +.It Fl D Ar data-size +Set the size of the data segment. For sanity's sake, this should be larger +than the cumulative data sizes of the input files. +.It Fl d Ar c +Force allocation of commons even producing relocatable output. +.It Fl d Ar p +Force alias definitions of procedure calls in non-PIC code. Useful to +obtain shareable code in the presence of run-time relocations as such +calls will be re-directed through the Procedure Linkage Table (see +.Xr link 5) +.It Fl e Ar entry-symbol +Specifies the entry symbol for an executable. +.It Fl L Ar path +Add +.Ar path +to the list of directories to search for libraries specified with the +.Ar -l +option. +.It Fl l Ar lib-spec +This option specifies a library to be considered for inclusion in the +output. If the -Bdynamic option is in effect, a shared library of the +form lib<spec>.so.m.n (where +.Em m +is the major, and +.Em n +is the minor version number, respectively) is searched for first. The +library with the highest version found in the search path is selected. +If no shared library is found or the -Bstatic options is in effect, +an archive of the form lib<spec>.a is looked for in the library seach path. +.It Fl M +Produce output about the mapping of segments of the input files and the +values assigned to (global) symbols in the output file. +.It Fl N +Produce a OMAGIC output file. +.It Fl n +Produce a NMAGIC output file. +.It Fl o Ar filename +Specifies the name of the output file. Defaults to +.Dq a.out. +.It Fl Q +Make a BSD/386 / FreeBSD 1.1 output file. This is the default. +.It Fl r +Produce relocatable object file, suitable for another pass through +.Nm ld. +.It Fl S +Strip all debugger symbols from the output. +.It Fl s +Strip all symbols from the output. +.It Fl T +Specifies the start address of the text segment, with respect to which +all input files will be relocated. +.It Fl t +Leave a trace of the input files as they are processed. +.It Fl u Ar symbol +Force +.Ar symbol +to be marked as undefined. Useful to force loading of an archive member +in the absence of any other references to that member. +.It Fl V Ar version +Put the given version number into the output shared library (if one is +created). Useful to make shared libaries compatible with other operating +systems. Eg. SunOS 4.x libraries use version number 3. Defaults to 8. +.It Fl X +Discard local symbols in the input files that start with the letter +.Dq L +.It Fl x +Discard all local symbols in the input files. +.It Fl y Ar symbol +Trace the manipulations inflicted on +.Ar symbol +.It Fl Z +Make a 386BSD ZMAGIC output file. +.It Fl z +Make a NetBSD 0.9 ZMAGIC output file. +.Sh FILES +.Sh SEE ALSO +.Xr ldconfig 1 , +.Xr link 5 +.Sh CAVEATS +An entry point must now explicitly be given if the output is intended to be +a normal executable program. This was not the case for the previous version of +.Nm ld\&. +.Sh BUGS +Shared objects are not properly checked for undefined symbols. +.Pp +Cascading of shared object defeats the +.Dq -Bstatic +option. +.Pp +All shared objects presented to +.Nm ld +are marked for run-time loading in the output file, even if no symbols +are needed from them. +.Sh HISTORY +The shared library model employed by +.Nm ld +appeared first in SunOS 4.0 diff --git a/gnu/usr.bin/ld/ld.c b/gnu/usr.bin/ld/ld.c new file mode 100644 index 000000000000..ac887511ebbf --- /dev/null +++ b/gnu/usr.bin/ld/ld.c @@ -0,0 +1,3427 @@ +/*- + * This code is derived from software copyrighted by the Free Software + * Foundation. + * + * Modified 1991 by Donn Seeley at UUNET Technologies, Inc. + * + * Modified 1993 by Paul Kranenburg, Erasmus University + */ + +#ifndef lint +static char sccsid[] = "@(#)ld.c 6.10 (Berkeley) 5/22/91"; +#endif /* not lint */ + +/* Linker `ld' for GNU + Copyright (C) 1988 Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 1, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ + +/* Written by Richard Stallman with some help from Eric Albert. + Set, indirect, and warning symbol features added by Randy Smith. */ + +/* + * $Id: ld.c,v 1.21 1994/02/17 03:57:00 davidg Exp $ + */ + +/* Define how to initialize system-dependent header fields. */ + +#include <sys/param.h> +#include <stdio.h> +#include <stdlib.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <sys/file.h> +#include <sys/time.h> +#include <sys/resource.h> +#include <fcntl.h> +#include <ar.h> +#include <ranlib.h> +#include <a.out.h> +#include <stab.h> +#include <string.h> +#include <strings.h> + +#include "ld.h" + +/* Vector of entries for input files specified by arguments. + These are all the input files except for members of specified libraries. */ +struct file_entry *file_table; +int number_of_files; + +/* 1 => write relocation into output file so can re-input it later. */ +int relocatable_output; + +/* 1 => building a shared object, set by `-Bshareable'. */ +int building_shared_object; + +/* 1 => create the output executable. */ +int make_executable; + +/* Force the executable to be output, even if there are non-fatal errors */ +int force_executable; + +/* 1 => assign space to common symbols even if `relocatable_output'. */ +int force_common_definition; + +/* 1 => assign jmp slots to text symbols in shared objects even if non-PIC */ +int force_alias_definition; + +/* 1 => some files contain PIC code, affects relocation bits + if `relocatable_output'. */ +int pic_code_seen; + +/* 1 => segments must be page aligned (ZMAGIC, QMAGIC) */ +int page_align_segments; + +/* 1 => data segment must be page aligned, even if `-n' or `-N' */ +int page_align_data; + +/* Version number to put in __DYNAMIC (set by -V) */ +int soversion; + +int text_size; /* total size of text. */ +int text_start; /* start of text */ +int text_pad; /* clear space between text and data */ +int data_size; /* total size of data. */ +int data_start; /* start of data */ +int data_pad; /* part of bss segment as part of data */ + +int bss_size; /* total size of bss. */ +int bss_start; /* start of bss */ + +int text_reloc_size; /* total size of text relocation. */ +int data_reloc_size; /* total size of data relocation. */ + +int rrs_section_type; /* What's in the RRS section */ +int rrs_text_size; /* Size of RRS text additions */ +int rrs_text_start; /* Location of above */ +int rrs_data_size; /* Size of RRS data additions */ +int rrs_data_start; /* Location of above */ + +/* Specifications of start and length of the area reserved at the end + of the data segment for the set vectors. Computed in 'digest_symbols' */ +int set_sect_start; /* start of set element vectors */ +int set_sect_size; /* size of above */ + +int link_mode; /* Current link mode */ + +/* + * When loading the text and data, we can avoid doing a close + * and another open between members of the same library. + * + * These two variables remember the file that is currently open. + * Both are zero if no file is open. + * + * See `each_file' and `file_close'. + */ +struct file_entry *input_file; +int input_desc; + +/* The name of the file to write; "a.out" by default. */ +char *output_filename; /* Output file name. */ +int outdesc; /* Output file descriptor. */ +struct exec outheader; /* Output file header. */ +int magic; /* Output file magic. */ +int oldmagic; +int relocatable_output; /* `-r'-ed output */ + +symbol *entry_symbol; +int entry_offset; + +int page_size; /* Size of a page (machine dependent) */ + +/* Keep a list of any symbols referenced from the command line (so + that error messages for these guys can be generated). This list is + zero terminated. */ +struct glosym **cmdline_references; +int cl_refs_allocated; + +/* + * Which symbols should be stripped (omitted from the output): none, all, or + * debugger symbols. + */ +enum { + STRIP_NONE, STRIP_ALL, STRIP_DEBUGGER +} strip_symbols; + +/* + * Which local symbols should be omitted: none, all, or those starting with L. + * This is irrelevant if STRIP_NONE. + */ +enum { + DISCARD_NONE, DISCARD_ALL, DISCARD_L +} discard_locals; + +int global_sym_count; /* # of nlist entries for global symbols */ +int size_sym_count; /* # of N_SIZE nlist entries for output + (relocatable_output only) */ +int local_sym_count; /* # of nlist entries for local symbols. */ +int non_L_local_sym_count; /* # of nlist entries for non-L symbols */ +int debugger_sym_count; /* # of nlist entries for debugger info. */ +int undefined_global_sym_count; /* # of global symbols referenced and + not defined. */ +int undefined_shobj_sym_count; /* # of undefined symbols referenced + by shared objects */ +int multiple_def_count; /* # of multiply defined symbols. */ +int defined_global_sym_count; /* # of defined global symbols. */ +int common_defined_global_count; /* # of common symbols. */ + +int special_sym_count; /* # of linker defined symbols. */ + /* XXX - Currently, only __DYNAMIC and _G_O_T_ go here if required, + * perhaps _etext, _edata and _end should go here too. + */ +int global_alias_count; /* # of aliased symbols */ +int set_symbol_count; /* # of N_SET* symbols. */ +int set_vector_count; /* # of set vectors in output. */ +int warning_count; /* # of warning symbols encountered. */ + +struct string_list_element *set_element_prefixes; + +int trace_files; /* print names of input files as processed (`-t'). */ +int write_map; /* write a load map (`-M') */ + +/* + * `text-start' address is normally this much plus a page boundary. + * This is not a user option; it is fixed for each system. + */ +int text_start_alignment; + +/* + * Nonzero if -T was specified in the command line. + * This prevents text_start from being set later to default values. + */ +int T_flag_specified; + +/* + * Nonzero if -Tdata was specified in the command line. + * This prevents data_start from being set later to default values. + */ +int Tdata_flag_specified; + +/* + * Size to pad data section up to. + * We simply increase the size of the data section, padding with zeros, + * and reduce the size of the bss section to match. + */ +int specified_data_size; + +long *set_vectors; +int setv_fill_count; + +static void decode_option __P((char *, char *)); +static void decode_command __P((int, char **)); +static int classify_arg __P((char *)); +static void load_symbols __P((void)); +static void enter_global_ref __P((struct localsymbol *, + char *, struct file_entry *)); +static void digest_symbols __P((void)); +static void digest_pass1 __P((void)), digest_pass2 __P((void)); +static void consider_file_section_lengths __P((struct file_entry *)); +static void relocate_file_addresses __P((struct file_entry *)); +static void consider_relocation __P((struct file_entry *, int)); +static void consider_local_symbols __P((struct file_entry *)); +static void perform_relocation __P((char *, int, + struct relocation_info *, int, + struct file_entry *, int)); +static void copy_text __P((struct file_entry *)); +static void copy_data __P((struct file_entry *)); +static void coptxtrel __P((struct file_entry *)); +static void copdatrel __P((struct file_entry *)); +static void write_output __P((void)); +static void write_header __P((void)); +static void write_text __P((void)); +static void write_data __P((void)); +static void write_rel __P((void)); +static void write_syms __P((void)); +static void assign_symbolnums __P((struct file_entry *, int *)); +static void myfatal __P((void)); + + +int +main(argc, argv) + char **argv; + int argc; +{ + + if ((progname = strrchr(argv[0], '/')) == NULL) + progname = argv[0]; + else + progname++; + + /* Added this to stop ld core-dumping on very large .o files. */ +#ifdef RLIMIT_STACK + /* Get rid of any avoidable limit on stack size. */ + { + struct rlimit rlim; + + /* Set the stack limit huge so that alloca does not fail. */ + getrlimit(RLIMIT_STACK, &rlim); + rlim.rlim_cur = rlim.rlim_max; + setrlimit(RLIMIT_STACK, &rlim); + } +#endif /* RLIMIT_STACK */ + + page_size = PAGSIZ; + + /* Clear the cumulative info on the output file. */ + + text_size = 0; + data_size = 0; + bss_size = 0; + text_reloc_size = 0; + data_reloc_size = 0; + + data_pad = 0; + text_pad = 0; + page_align_segments = 0; + page_align_data = 0; + + /* Initialize the data about options. */ + + specified_data_size = 0; + strip_symbols = STRIP_NONE; + trace_files = 0; + discard_locals = DISCARD_NONE; + entry_symbol = 0; + write_map = 0; + relocatable_output = 0; + force_common_definition = 0; + T_flag_specified = 0; + Tdata_flag_specified = 0; + magic = DEFAULT_MAGIC; + make_executable = 1; + force_executable = 0; + link_mode = DYNAMIC; +#ifdef SUNOS4 + link_mode |= SILLYARCHIVE; +#endif + soversion = DEFAULT_SOVERSION; + + /* Initialize the cumulative counts of symbols. */ + + local_sym_count = 0; + non_L_local_sym_count = 0; + debugger_sym_count = 0; + undefined_global_sym_count = 0; + warning_count = 0; + multiple_def_count = 0; + common_defined_global_count = 0; + + /* Keep a list of symbols referenced from the command line */ + cl_refs_allocated = 10; + cmdline_references + = (struct glosym **) xmalloc(cl_refs_allocated + * sizeof(struct glosym *)); + *cmdline_references = 0; + + /* Completely decode ARGV. */ + decode_command(argc, argv); + + building_shared_object = + (!relocatable_output && (link_mode & SHAREABLE)); + + if (building_shared_object && entry_symbol) { + fatal("`-Bshareable' and `-e' options are mutually exclusive"); + } + + /* Create the symbols `etext', `edata' and `end'. */ + symtab_init(relocatable_output); + + /* Prepare for the run-time linking support. */ + init_rrs(); + + /* + * Determine whether to count the header as part of the text size, + * and initialize the text size accordingly. This depends on the kind + * of system and on the output format selected. + */ + if (magic == ZMAGIC || magic == QMAGIC) + page_align_segments = 1; + + md_init_header(&outheader, magic, 0); + + text_size = sizeof(struct exec); + text_size -= N_TXTOFF(outheader); + + if (text_size < 0) + text_size = 0; + entry_offset = text_size; + + if (!T_flag_specified && !relocatable_output) + text_start = TEXT_START(outheader); + + /* The text-start address is normally this far past a page boundary. */ + text_start_alignment = text_start % page_size; + + /* + * Load symbols of all input files. Also search all libraries and + * decide which library members to load. + */ + load_symbols(); + + /* Compute where each file's sections go, and relocate symbols. */ + digest_symbols(); + + /* + * Print error messages for any missing symbols, for any warning + * symbols, and possibly multiple definitions + */ + make_executable = do_warnings(stderr); + + /* Print a map, if requested. */ + if (write_map) + print_symbols(stdout); + + /* Write the output file. */ + if (make_executable || force_executable) + write_output(); + + exit(!make_executable); +} + +/* + * Analyze a command line argument. Return 0 if the argument is a filename. + * Return 1 if the argument is a option complete in itself. Return 2 if the + * argument is a option which uses an argument. + * + * Thus, the value is the number of consecutive arguments that are part of + * options. + */ + +static int +classify_arg(arg) + register char *arg; +{ + if (*arg != '-') + return 0; + switch (arg[1]) { + case 'a': + if (!strcmp(&arg[2], "ssert")) + return 2; + case 'A': + case 'D': + case 'e': + case 'L': + case 'l': + case 'o': + case 'u': + case 'V': + case 'y': + if (arg[2]) + return 1; + return 2; + + case 'B': + if (!strcmp(&arg[2], "static")) + return 1; + if (!strcmp(&arg[2], "dynamic")) + return 1; + + case 'T': + if (arg[2] == 0) + return 2; + if (!strcmp(&arg[2], "text")) + return 2; + if (!strcmp(&arg[2], "data")) + return 2; + return 1; + } + + return 1; +} + +/* + * Process the command arguments, setting up file_table with an entry for + * each input file, and setting variables according to the options. + */ + +static void +decode_command(argc, argv) + int argc; + char **argv; +{ + register int i; + register struct file_entry *p; + char *cp; + + number_of_files = 0; + output_filename = "a.out"; + + /* + * First compute number_of_files so we know how long to make + * file_table. + * Also process most options completely. + */ + + for (i = 1; i < argc; i++) { + register int code = classify_arg(argv[i]); + if (code) { + if (i + code > argc) + fatal("no argument following %s\n", argv[i]); + + decode_option(argv[i], argv[i + 1]); + + if (argv[i][1] == 'l' || argv[i][1] == 'A') + number_of_files++; + + i += code - 1; + } else + number_of_files++; + } + + if (!number_of_files) + fatal("no input files"); + + p = file_table = (struct file_entry *) + xmalloc(number_of_files * sizeof(struct file_entry)); + bzero(p, number_of_files * sizeof(struct file_entry)); + + /* Now scan again and fill in file_table. */ + /* All options except -A and -l are ignored here. */ + + for (i = 1; i < argc; i++) { + char *string; + register int code = classify_arg(argv[i]); + + if (code == 0) { + p->filename = argv[i]; + p->local_sym_name = argv[i]; + p++; + continue; + } + if (code == 2) + string = argv[i + 1]; + else + string = &argv[i][2]; + + if (argv[i][1] == 'B') { + if (strcmp(string, "static") == 0) + link_mode &= ~DYNAMIC; + else if (strcmp(string, "dynamic") == 0) + link_mode |= DYNAMIC; + else if (strcmp(string, "symbolic") == 0) + link_mode |= SYMBOLIC; + else if (strcmp(string, "forcearchive") == 0) + link_mode |= FORCEARCHIVE; + else if (strcmp(string, "shareable") == 0) + link_mode |= SHAREABLE; +#ifdef SUN_COMPAT + else if (strcmp(string, "silly") == 0) + link_mode |= SILLYARCHIVE; + else if (strcmp(string, "~silly") == 0) + link_mode &= ~SILLYARCHIVE; +#endif + } + if (argv[i][1] == 'A') { + if (p != file_table) + fatal("-A specified before an input file other than the first"); + p->filename = string; + p->local_sym_name = string; + p->flags |= E_JUST_SYMS; + p++; + } + if (argv[i][1] == 'l') { + p->filename = string; + p->local_sym_name = concat("-l", string, ""); + p->flags |= E_SEARCH_DIRS; + if (link_mode & DYNAMIC && !relocatable_output) + p->flags |= E_SEARCH_DYNAMIC; + p++; + } + i += code - 1; + } + + /* Now check some option settings for consistency. */ + + if (page_align_segments + && (text_start - text_start_alignment) & (page_size - 1)) + fatal("-T argument not multiple of page size, with sharable output"); + + /* Append the standard search directories to the user-specified ones. */ + std_search_dirs(getenv("LD_LIBRARY_PATH")); +} + +void +add_cmdline_ref(sp) + symbol *sp; +{ + symbol **ptr; + + for (ptr = cmdline_references; + ptr < cmdline_references + cl_refs_allocated && *ptr; + ptr++); + + if (ptr >= cmdline_references + cl_refs_allocated - 1) { + int diff = ptr - cmdline_references; + + cl_refs_allocated *= 2; + cmdline_references = (struct glosym **) + xrealloc(cmdline_references, + cl_refs_allocated * sizeof(struct glosym *)); + ptr = cmdline_references + diff; + } + *ptr++ = sp; + *ptr = (symbol *) 0; +} + +int +set_element_prefixed_p(name) + char *name; +{ + struct string_list_element *p; + int i; + + for (p = set_element_prefixes; p; p = p->next) { + + for (i = 0; p->str[i] != '\0' && (p->str[i] == name[i]); i++); + if (p->str[i] == '\0') + return 1; + } + return 0; +} + +/* + * Record an option and arrange to act on it later. ARG should be the + * following command argument, which may or may not be used by this option. + * + * The `l' and `A' options are ignored here since they actually specify input + * files. + */ + +static void +decode_option(swt, arg) + register char *swt, *arg; +{ + if (!strcmp(swt + 1, "Bstatic")) + return; + if (!strcmp(swt + 1, "Bdynamic")) + return; + if (!strcmp(swt + 1, "Bsymbolic")) + return; + if (!strcmp(swt + 1, "Bforcearchive")) + return; + if (!strcmp(swt + 1, "Bshareable")) + return; + if (!strcmp(swt + 1, "assert")) + return; +#ifdef SUN_COMPAT + if (!strcmp(swt + 1, "Bsilly")) + return; +#endif + if (!strcmp(swt + 1, "Ttext")) { + text_start = parse(arg, "%x", "invalid argument to -Ttext"); + T_flag_specified = 1; + return; + } + if (!strcmp(swt + 1, "Tdata")) { + rrs_data_start = parse(arg, "%x", "invalid argument to -Tdata"); + Tdata_flag_specified = 1; + return; + } + if (!strcmp(swt + 1, "noinhibit-exec")) { + force_executable = 1; + return; + } + if (swt[2] != 0) + arg = &swt[2]; + + switch (swt[1]) { + case 'A': + return; + + case 'D': + specified_data_size = parse(arg, "%x", "invalid argument to -D"); + return; + + case 'd': + if (*arg == 'c') + force_common_definition = 1; + else if (*arg == 'p') + force_alias_definition = 1; + else + fatal("-d option takes 'c' or 'p' argument"); + return; + + case 'e': + entry_symbol = getsym(arg); + if (!entry_symbol->defined && + !(entry_symbol->flags & GS_REFERENCED)) + undefined_global_sym_count++; + entry_symbol->flags |= GS_REFERENCED; + add_cmdline_ref(entry_symbol); + return; + + case 'l': + return; + + case 'L': + add_search_dir(arg); + return; + + case 'M': + write_map = 1; + return; + + case 'N': + magic = OMAGIC; + return; + + case 'n': + magic = NMAGIC; + return; + + case 'o': + output_filename = arg; + return; + + case 'p': + page_align_data = 1; + return; + +#ifdef QMAGIC + case 'Q': + magic = QMAGIC; + return; +#endif + + case 'r': + relocatable_output = 1; + magic = OMAGIC; + text_start = 0; + return; + + case 'S': + strip_symbols = STRIP_DEBUGGER; + return; + + case 's': + strip_symbols = STRIP_ALL; + return; + + case 'T': + text_start = parse(arg, "%x", "invalid argument to -T"); + T_flag_specified = 1; + return; + + case 't': + trace_files = 1; + return; + + case 'u': + { + register symbol *sp = getsym(arg); + + if (!sp->defined && !(sp->flags & GS_REFERENCED)) + undefined_global_sym_count++; + sp->flags |= GS_REFERENCED; + add_cmdline_ref(sp); + } + return; + +#if 1 + case 'V': + soversion = parse(arg, "%d", "invalid argument to -V"); + return; +#endif + + case 'X': + discard_locals = DISCARD_L; + return; + + case 'x': + discard_locals = DISCARD_ALL; + return; + + case 'y': + { + register symbol *sp = getsym(&swt[2]); + sp->flags |= GS_TRACE; + } + return; + + case 'z': + magic = ZMAGIC; + oldmagic = 0; +#ifdef __FreeBSD__ + netzmagic = 1; +#endif + return; + + case 'Z': + magic = oldmagic = ZMAGIC; +#ifdef __FreeBSD__ + netzmagic = 0; +#endif + return; + + default: + fatal("invalid command option `%s'", swt); + } +} + +/* Convenient functions for operating on one or all files being loaded. */ + +/* + * Call FUNCTION on each input file entry. Do not call for entries for + * libraries; instead, call once for each library member that is being + * loaded. + * + * FUNCTION receives two arguments: the entry, and ARG. + */ + +void +each_file(function, arg) + register void (*function) (); + register int arg; +{ + register int i; + + for (i = 0; i < number_of_files; i++) { + register struct file_entry *entry = &file_table[i]; + register struct file_entry *subentry; + + if (entry->flags & E_SCRAPPED) + continue; + + if (!(entry->flags & E_IS_LIBRARY)) + (*function) (entry, arg); + + subentry = entry->subfiles; + for (; subentry; subentry = subentry->chain) { + if (subentry->flags & E_SCRAPPED) + continue; + (*function) (subentry, arg); + } + +#ifdef SUN_COMPAT + if (entry->silly_archive) { + + if (!(entry->flags & E_DYNAMIC)) + error("Silly"); + + if (!(entry->silly_archive->flags & E_IS_LIBRARY)) + error("Sillier"); + + subentry = entry->silly_archive->subfiles; + for (; subentry; subentry = subentry->chain) { + if (subentry->flags & E_SCRAPPED) + continue; + (*function) (subentry, arg); + } + } +#endif + } +} + +/* + * Call FUNCTION on each input file entry until it returns a non-zero value. + * Return this value. Do not call for entries for libraries; instead, call + * once for each library member that is being loaded. + * + * FUNCTION receives two arguments: the entry, and ARG. It must be a function + * returning unsigned long (though this can probably be fudged). + */ + +unsigned long +check_each_file(function, arg) + register unsigned long (*function) (); + register int arg; +{ + register int i; + register unsigned long return_val; + + for (i = 0; i < number_of_files; i++) { + register struct file_entry *entry = &file_table[i]; + if (entry->flags & E_SCRAPPED) + continue; + if (entry->flags & E_IS_LIBRARY) { + register struct file_entry *subentry = entry->subfiles; + for (; subentry; subentry = subentry->chain) { + if (subentry->flags & E_SCRAPPED) + continue; + if (return_val = (*function) (subentry, arg)) + return return_val; + } + } else if (return_val = (*function) (entry, arg)) + return return_val; + } + return 0; +} + +/* Like `each_file' but ignore files that were just for symbol definitions. */ + +void +each_full_file(function, arg) + register void (*function) (); + register int arg; +{ + register int i; + + for (i = 0; i < number_of_files; i++) { + register struct file_entry *entry = &file_table[i]; + register struct file_entry *subentry; + + if (entry->flags & (E_SCRAPPED | E_JUST_SYMS)) + continue; + +#ifdef SUN_COMPAT + if (entry->silly_archive) { + + if (!(entry->flags & E_DYNAMIC)) + error("Silly"); + + if (!(entry->silly_archive->flags & E_IS_LIBRARY)) + error("Sillier"); + + subentry = entry->silly_archive->subfiles; + for (; subentry; subentry = subentry->chain) { + if (subentry->flags & E_SCRAPPED) + continue; + (*function) (subentry, arg); + } + } +#endif + if (entry->flags & E_DYNAMIC) + continue; + + if (!(entry->flags & E_IS_LIBRARY)) + (*function) (entry, arg); + + subentry = entry->subfiles; + for (; subentry; subentry = subentry->chain) { + if (subentry->flags & E_SCRAPPED) + continue; + (*function) (subentry, arg); + } + + } +} + +/* Close the input file that is now open. */ + +void +file_close() +{ + close(input_desc); + input_desc = 0; + input_file = 0; +} + +/* + * Open the input file specified by 'entry', and return a descriptor. The + * open file is remembered; if the same file is opened twice in a row, a new + * open is not actually done. + */ +int +file_open (entry) + register struct file_entry *entry; +{ + register int desc; + + if (entry->superfile && (entry->superfile->flags & E_IS_LIBRARY)) + return file_open (entry->superfile); + + if (entry == input_file) + return input_desc; + + if (input_file) file_close (); + + if (entry->flags & E_SEARCH_DIRS) { + desc = findlib(entry); + } else + desc = open (entry->filename, O_RDONLY, 0); + + if (desc > 0) { + input_file = entry; + input_desc = desc; + return desc; + } + + perror_file (entry); + /* NOTREACHED */ +} + +int +text_offset (entry) + struct file_entry *entry; +{ + return entry->starting_offset + N_TXTOFF (entry->header); +} + +/*---------------------------------------------------------------------------*/ + +/* + * Read a file's header into the proper place in the file_entry. DESC is the + * descriptor on which the file is open. ENTRY is the file's entry. + */ +void +read_header (desc, entry) + int desc; + register struct file_entry *entry; +{ + register int len, mid; + + if (lseek (desc, entry->starting_offset, L_SET) != + entry->starting_offset) + fatal_with_file("read_header: lseek failure ", entry); + + len = read (desc, &entry->header, sizeof (struct exec)); + if (len != sizeof (struct exec)) + fatal_with_file ("failure reading header of ", entry); + + md_swapin_exec_hdr(&entry->header); + + if (N_BADMAG (entry->header)) + fatal_with_file ("bad magic number in ", entry); + + if (N_BADMID(entry->header)) + fatal_with_file ("non-native input file ", entry); + + entry->flags |= E_HEADER_VALID; +} + +/* + * Read the symbols of file ENTRY into core. Assume it is already open, on + * descriptor DESC. Also read the length of the string table, which follows + * the symbol table, but don't read the contents of the string table. + */ + +void +read_entry_symbols (desc, entry) + struct file_entry *entry; + int desc; +{ + int str_size; + struct nlist *np; + int i; + + if (!(entry->flags & E_HEADER_VALID)) + read_header (desc, entry); + + np = (struct nlist *) alloca (entry->header.a_syms); + entry->nsymbols = entry->header.a_syms / sizeof(struct nlist); + entry->symbols = (struct localsymbol *) + xmalloc(entry->nsymbols * sizeof(struct localsymbol)); + + if (lseek(desc, N_SYMOFF(entry->header) + entry->starting_offset, L_SET) + != N_SYMOFF(entry->header) + entry->starting_offset) + fatal_with_file ("read_symbols(h): lseek failure ", entry); + + if (entry->header.a_syms != read (desc, np, entry->header.a_syms)) + fatal_with_file ("premature end of file in symbols of ", entry); + + md_swapin_symbols(np, entry->header.a_syms / sizeof(struct nlist)); + + for (i = 0; i < entry->nsymbols; i++) { + entry->symbols[i].nzlist.nlist = *np++; + entry->symbols[i].nzlist.nz_size = 0; + entry->symbols[i].symbol = NULL; + entry->symbols[i].next = NULL; + entry->symbols[i].entry = entry; + entry->symbols[i].gotslot_offset = -1; + entry->symbols[i].flags = 0; + } + + entry->strings_offset = N_STROFF(entry->header) + + entry->starting_offset; + if (lseek(desc, entry->strings_offset, 0) == (off_t)-1) + fatal_with_file ("read_symbols(s): lseek failure ", entry); + if (sizeof str_size != read (desc, &str_size, sizeof str_size)) + fatal_with_file ("bad string table size in ", entry); + + entry->string_size = md_swap_long(str_size); +} + +/* + * Read the string table of file ENTRY into core. Assume it is already open, + * on descriptor DESC. + */ +void +read_entry_strings (desc, entry) + struct file_entry *entry; + int desc; +{ + int buffer; + + if (!(entry->flags & E_HEADER_VALID) || !entry->strings_offset) + fatal_with_file("internal error: cannot read string table for ", + entry); + + if (lseek (desc, entry->strings_offset, L_SET) != entry->strings_offset) + fatal_with_file ("read_strings: lseek failure ", entry); + + if (entry->string_size != + read (desc, entry->strings, entry->string_size)) + fatal_with_file ("premature end of file in strings of ", entry); + + return; +} + +/* Read in the relocation sections of ENTRY if necessary */ + +void +read_entry_relocation (desc, entry) + int desc; + struct file_entry *entry; +{ + register struct relocation_info *reloc; + off_t pos; + + if (!entry->textrel) { + + reloc = (struct relocation_info *) + xmalloc(entry->header.a_trsize); + + pos = text_offset(entry) + + entry->header.a_text + entry->header.a_data; + + if (lseek(desc, pos, L_SET) != pos) + fatal_with_file("read_reloc(t): lseek failure ", entry); + + if (entry->header.a_trsize != + read(desc, reloc, entry->header.a_trsize)) { + fatal_with_file ( + "premature eof in text relocation of ", entry); + } + md_swapin_reloc(reloc, entry->header.a_trsize / sizeof(*reloc)); + entry->textrel = reloc; + entry->ntextrel = entry->header.a_trsize / sizeof(*reloc); + + } + + if (!entry->datarel) { + + reloc = (struct relocation_info *) + xmalloc(entry->header.a_drsize); + + pos = text_offset(entry) + entry->header.a_text + + entry->header.a_data + entry->header.a_trsize; + + if (lseek(desc, pos, L_SET) != pos) + fatal_with_file("read_reloc(d): lseek failure ", entry); + + if (entry->header.a_drsize != + read (desc, reloc, entry->header.a_drsize)) { + fatal_with_file ( + "premature eof in data relocation of ", entry); + } + md_swapin_reloc(reloc, entry->header.a_drsize / sizeof(*reloc)); + entry->datarel = reloc; + entry->ndatarel = entry->header.a_drsize / sizeof(*reloc); + + } +} + +/*---------------------------------------------------------------------------*/ + +/* + * Read in the symbols of all input files. + */ +static void +load_symbols () +{ + register int i; + + if (trace_files) + fprintf(stderr, "Loading symbols:\n\n"); + + for (i = 0; i < number_of_files; i++) + read_file_symbols(&file_table[i]); + + if (trace_files) + fprintf (stderr, "\n"); +} + +/* + * If ENTRY is a rel file, read its symbol and string sections into core. If + * it is a library, search it and load the appropriate members (which means + * calling this function recursively on those members). + */ + +void +read_file_symbols (entry) + register struct file_entry *entry; +{ + register int desc; + register int len; + struct exec hdr; + + desc = file_open (entry); + + len = read (desc, &hdr, sizeof hdr); + if (len != sizeof hdr) + fatal_with_file ("failure reading header of ", entry); + + md_swapin_exec_hdr(&hdr); + + if (!N_BADMAG (hdr)) { + if (N_IS_DYNAMIC(hdr) && !(entry->flags & E_JUST_SYMS)) { + if (relocatable_output) { + fatal_with_file( + "-r and shared objects currently not supported ", + entry); + return; + } + entry->flags |= E_DYNAMIC; + if (entry->superfile || rrs_add_shobj(entry)) + read_shared_object(desc, entry); + else + entry->flags |= E_SCRAPPED; + } else { + read_entry_symbols (desc, entry); + entry->strings = (char *) alloca (entry->string_size); + read_entry_strings (desc, entry); + read_entry_relocation(desc, entry); + enter_file_symbols (entry); + entry->strings = 0; + } + } else { + char armag[SARMAG]; + + lseek (desc, 0, 0); + if (SARMAG != read (desc, armag, SARMAG) || + strncmp (armag, ARMAG, SARMAG)) + fatal_with_file( + "malformed input file (not rel or archive) ", entry); + entry->flags |= E_IS_LIBRARY; + search_library (desc, entry); + } + + file_close (); +} + + +/* + * Enter the external symbol defs and refs of ENTRY in the hash table. + */ + +void +enter_file_symbols (entry) + struct file_entry *entry; +{ + struct localsymbol *lsp, *lspend; + + if (trace_files) prline_file_name (entry, stderr); + + lspend = entry->symbols + entry->nsymbols; + + for (lsp = entry->symbols; lsp < lspend; lsp++) { + register struct nlist *p = &lsp->nzlist.nlist; + + if (p->n_type == (N_SETV | N_EXT)) + continue; + + /* + * Turn magically prefixed symbols into set symbols of + * a corresponding type. + */ + if (set_element_prefixes && + set_element_prefixed_p(entry->strings+lsp->nzlist.nz_strx)) + lsp->nzlist.nz_type += (N_SETA - N_ABS); + + if (SET_ELEMENT_P(p->n_type)) { + set_symbol_count++; + if (!relocatable_output) + enter_global_ref(lsp, + p->n_un.n_strx + entry->strings, entry); + } else if (p->n_type == N_WARNING) { + char *name = p->n_un.n_strx + entry->strings; + + /* Grab the next entry. */ + p++; + if (p->n_type != (N_UNDF | N_EXT)) { + error("Warning symbol found in %s without external reference following.", + get_file_name(entry)); + make_executable = 0; + p--; /* Process normally. */ + } else { + symbol *sp; + char *sname = p->n_un.n_strx + entry->strings; + /* Deal with the warning symbol. */ + enter_global_ref(lsp, + p->n_un.n_strx + entry->strings, entry); + sp = getsym (sname); + sp->warning = (char *)xmalloc(strlen(name)+1); + strcpy (sp->warning, name); + warning_count++; + } + } else if (p->n_type & N_EXT) { + enter_global_ref(lsp, + p->n_un.n_strx + entry->strings, entry); + } else if (p->n_un.n_strx && + (p->n_un.n_strx + entry->strings)[0] == LPREFIX) + lsp->flags |= LS_L_SYMBOL; + } + +} + +/* + * Enter one global symbol in the hash table. LSP points to the `struct + * localsymbol' from the file that describes the global symbol. NAME is the + * symbol's name. ENTRY is the file entry for the file the symbol comes from. + * + * LSP is put on the chain of all such structs that refer to the same symbol. + * This chain starts in the `refs' for symbols from relocatable objects. A + * backpointer to the global symbol is kept in LSP. + * + * Symbols from shared objects are linked through `soref'. For such symbols + * that's all we do at this stage, with the exception of the case where the + * symbol is a common. The `referenced' bit is only set for references from + * relocatable objects. + * + */ + +static void +enter_global_ref (lsp, name, entry) + struct localsymbol *lsp; + char *name; + struct file_entry *entry; +{ + register struct nzlist *nzp = &lsp->nzlist; + register symbol *sp = getsym (name); + register int type = nzp->nz_type; + int oldref = (sp->flags & GS_REFERENCED); + int olddef = sp->defined; + int com = sp->defined && sp->common_size; + + if (type == (N_INDR | N_EXT)) { + sp->alias = getsym(entry->strings + (lsp + 1)->nzlist.nz_strx); + if (sp == sp->alias) { + error("%s: %s is alias for itself", + get_file_name(entry), name); + /* Rewrite symbol as global text symbol with value 0 */ + lsp->nzlist.nz_type = N_TEXT|N_EXT; + lsp->nzlist.nz_value = 0; + make_executable = 0; + } else { + global_alias_count++; + } + } + + if (entry->flags & E_DYNAMIC) { + lsp->next = sp->sorefs; + sp->sorefs = lsp; + + /* + * Handle commons from shared objects: + * 1) If symbol hitherto undefined, turn it into a common. + * 2) If symbol already common, update size if necessary. + */ +/*XXX - look at case where commons are only in shared objects */ + if (type == (N_UNDF | N_EXT) && nzp->nz_value) { + if (!olddef) { + if (oldref) + undefined_global_sym_count--; + common_defined_global_count++; + sp->common_size = nzp->nz_value; + sp->defined = N_UNDF | N_EXT; + } else if (com && sp->common_size < nzp->nz_value) { + sp->common_size = nzp->nz_value; + } + } else if (type != (N_UNDF | N_EXT) && !oldref) { + /* + * This is an ex common... + */ + sp->common_size = 0; + sp->defined = 0; + } + + /* + * Handle size information in shared objects. + */ + if (nzp->nz_size > sp->size) + sp->size = nzp->nz_size; + + lsp->symbol = sp; + return; + } + + lsp->next = sp->refs; + sp->refs = lsp; + lsp->symbol = sp; + + sp->flags |= GS_REFERENCED; + + if (sp == dynamic_symbol || sp == got_symbol) { + if (type != (N_UNDF | N_EXT) && !(entry->flags & E_JUST_SYMS)) + fatal("Linker reserved symbol %s defined as type %x ", + name, type); + return; + } + +#ifdef N_SIZE + if (type == (N_SIZE | N_EXT)) { + if (relocatable_output && nzp->nz_value != 0 && sp->size == 0) + size_sym_count++; + if (sp->size < nzp->nz_value) + sp->size = nzp->nz_value; + } else +#endif + if (type != (N_UNDF | N_EXT) || nzp->nz_value) { + + /* + * Set `->defined' here, so commons and undefined globals + * can be counted correctly. + */ + if (!sp->defined || sp->defined == (N_UNDF | N_EXT)) + sp->defined = type; + + if (oldref && !olddef) + /* + * It used to be undefined and we're defining it. + */ + undefined_global_sym_count--; + + if (!olddef && type == (N_UNDF | N_EXT) && nzp->nz_value) { + /* + * First definition and it's common. + */ + common_defined_global_count++; + sp->common_size = nzp->nz_value; + } else if (com && type != (N_UNDF | N_EXT)) { + /* + * It used to be common and we're defining + * it as something else. + */ + common_defined_global_count--; + sp->common_size = 0; + } else if (com && type == (N_UNDF | N_EXT) + && sp->common_size < nzp->nz_value) + /* + * It used to be common and this is a new common entry + * to which we need to pay attention. + */ + sp->common_size = nzp->nz_value; + + if (SET_ELEMENT_P(type) && (!olddef || com)) + set_vector_count++; + + } else if (!oldref && !com) + /* + * An unreferenced symbol can already be defined + * as common by shared objects. + */ + undefined_global_sym_count++; + + + if (sp == end_symbol && (entry->flags & E_JUST_SYMS) && + !T_flag_specified) + text_start = nzp->nz_value; + + if (sp->flags & GS_TRACE) { + register char *reftype; + switch (type & N_TYPE) { + case N_UNDF: + reftype = nzp->nz_value? + "defined as common":"referenced"; + break; + + case N_ABS: + reftype = "defined as absolute"; + break; + + case N_TEXT: + reftype = "defined in text section"; + break; + + case N_DATA: + reftype = "defined in data section"; + break; + + case N_BSS: + reftype = "defined in BSS section"; + break; + + default: + reftype = "I don't know this type"; + break; + } + + fprintf (stderr, "symbol %s %s in ", sp->name, reftype); + print_file_name (entry, stderr); + fprintf (stderr, "\n"); + } +} + +/* + * This returns 0 if the given file entry's symbol table does *not* contain + * the nlist point entry, and it returns the files entry pointer (cast to + * unsigned long) if it does. + */ + +unsigned long +contains_symbol (entry, np) + struct file_entry *entry; + register struct nlist *np; +{ + if (np >= &entry->symbols->nzlist.nlist && + np < &(entry->symbols + entry->nsymbols)->nzlist.nlist) + return (unsigned long) entry; + return 0; +} + + +/* + * Having entered all the global symbols and found the sizes of sections of + * all files to be linked, make all appropriate deductions from this data. + * + * We propagate global symbol values from definitions to references. We compute + * the layout of the output file and where each input file's contents fit + * into it. + * + * This is now done in several stages. + * + * 1) All global symbols are examined for definitions in relocatable (.o) + * files. The symbols' type is set according to the definition found, + * but its value can not yet be determined. In stead, we keep a pointer + * to the file entry's localsymbol that bequeathed the global symbol with + * its definition. Also, multiple (incompatible) definitions are checked + * for in this pass. If no definition comes forward, the set of local + * symbols originating from shared objects is searched for a definition. + * + * 2) Then the relocation information of each relocatable file is examined + * for possible contributions to the RRS section. + * + * 3) When this is done, the sizes and start addresses are set of all segments + * that will appear in the output file (including the RRS segment). + * + * 4) Finally, all symbols are relocated according according to the start + * of the entry they are part of. Then global symbols are assigned their + * final values. Also, space for commons and imported data are allocated + * during this pass, if the link mode in effect so demands. + * + */ + +static void +digest_symbols () +{ + + if (trace_files) + fprintf(stderr, "Digesting symbol information:\n\n"); + + if (!relocatable_output) { + /* + * The set sector size is the number of set elements + a word + * for each symbol for the length word at the beginning of + * the vector, plus a word for each symbol for a zero at the + * end of the vector (for incremental linking). + */ + set_sect_size = (set_symbol_count + 2 * set_vector_count) * + sizeof (unsigned long); + set_vectors = (long *)xmalloc (set_sect_size); + setv_fill_count = 0; + } + + /* Pass 1: check and define symbols */ + defined_global_sym_count = 0; + digest_pass1(); + + each_full_file(consider_relocation, 0); /* Text */ + each_full_file(consider_relocation, 1); /* Data */ + + each_file(consider_local_symbols, 0); + + /* + * Compute total size of sections. + * RRS data is the first output data section, RRS text is the last + * text section. Thus, DATA_START is calculated from RRS_DATA_START + * and RRS_DATA_SIZE, while RRS_TEXT_START is derived from TEXT_START + * and TEXT_SIZE. + */ + consider_rrs_section_lengths(); + each_full_file(consider_file_section_lengths, 0); + rrs_text_start = text_start + text_size; + text_size += rrs_text_size; + data_size += rrs_data_size; + + /* + * If necessary, pad text section to full page in the file. Include + * the padding in the text segment size. + */ + + if (page_align_segments || page_align_data) { + int text_end = text_size + N_TXTOFF(outheader); + text_pad = PALIGN(text_end, page_size) - text_end; + text_size += text_pad; + } + outheader.a_text = text_size; + + /* + * Make the data segment address start in memory on a suitable + * boundary. + */ + + if (!Tdata_flag_specified) + rrs_data_start = text_start + + DATA_START(outheader) - TEXT_START(outheader); + + data_start = rrs_data_start + rrs_data_size; + if (!relocatable_output) { + set_sect_start = rrs_data_start + data_size; + data_size += set_sect_size; + } + bss_start = rrs_data_start + data_size; + +#ifdef DEBUG +printf("textstart = %#x, textsize = %#x, rrs_text_start = %#x, rrs_text_size %#x\n", + text_start, text_size, rrs_text_start, rrs_text_size); +printf("datastart = %#x, datasize = %#x, rrs_data_start %#x, rrs_data_size %#x\n", + data_start, data_size, rrs_data_start, rrs_data_size); +printf("bssstart = %#x, bsssize = %#x\n", + bss_start, bss_size); +#endif + + /* Compute start addresses of each file's sections and symbols. */ + + each_full_file(relocate_file_addresses, 0); + relocate_rrs_addresses(); + + /* Pass 2: assign values to symbols */ + digest_pass2(); + + if (end_symbol) { /* These are null if -r. */ + etext_symbol->value = text_start + text_size - text_pad; + edata_symbol->value = rrs_data_start + data_size; + end_symbol->value = rrs_data_start + data_size + bss_size; + } + /* + * Figure the data_pad now, so that it overlaps with the bss + * addresses. + */ + + if (specified_data_size && specified_data_size > data_size) + data_pad = specified_data_size - data_size; + + if (page_align_segments) + data_pad = PALIGN(data_pad + data_size, page_size) - data_size; + + bss_size -= data_pad; + if (bss_size < 0) + bss_size = 0; + + data_size += data_pad; + + /* + * Calculate total number of symbols that will go into + * the output symbol table (barring DISCARD_* settings). + */ + global_sym_count = defined_global_sym_count + + undefined_global_sym_count; + + if (dynamic_symbol->flags & GS_REFERENCED) + global_sym_count++; + + if (got_symbol->flags & GS_REFERENCED) + global_sym_count++; + + if (relocatable_output || building_shared_object) + /* For each alias we write out two struct nlists */ + global_sym_count += global_alias_count; + + if (relocatable_output) + /* We write out the original N_SET* symbols */ + global_sym_count += size_sym_count; + +#ifdef DEBUG +printf("global symbols %d (defined %d, undefined %d, aliases %d), locals: %d, \ +debug symbols: %d, set_symbols %d\n", + global_sym_count, + defined_global_sym_count, undefined_global_sym_count, global_alias_count, + local_sym_count, debugger_sym_count, set_symbol_count); +#endif +} + +/* + * Determine the definition of each global symbol. + */ +static void +digest_pass1() +{ + + /* + * For each symbol, verify that it is defined globally at most + * once within relocatable files (except when building a shared lib). + * and set the `defined' field if there is a definition. + * + * Then check the shared object symbol chain for any remaining + * undefined symbols. Set the `so_defined' field for any + * definition find this way. + */ + FOR_EACH_SYMBOL(i, sp) { + struct localsymbol *lsp; + int defs = 0; + + if (!(sp->flags & GS_REFERENCED)) { +#if 0 + /* Check for undefined symbols in shared objects */ + int type; + for (lsp = sp->sorefs; lsp; lsp = lsp->next) { + type = lsp->nzlist.nlist.n_type; + if ((type & N_EXT) && type != (N_UNDF | N_EXT)) + break; + } + if ((type & N_EXT) && type == (N_UNDF | N_EXT)) + undefined_shobj_sym_count++; +#endif + + /* Superfluous symbol from shared object */ + continue; + } + + if (sp == got_symbol || sp == dynamic_symbol) + continue; + + for (lsp = sp->refs; lsp; lsp = lsp->next) { + register struct nlist *p = &lsp->nzlist.nlist; + register int type = p->n_type; + + if (SET_ELEMENT_P(type)) { + if (relocatable_output) + fatal( + "internal error: global ref to set el %s with -r", + sp->name); + if (!defs++) { + sp->defined = N_SETV | N_EXT; + sp->value = + setv_fill_count++ * sizeof(long); + } else if ((sp->defined & N_TYPE) != N_SETV) { + sp->mult_defs = 1; + multiple_def_count++; + } + /* Keep count and remember symbol */ + sp->setv_count++; + set_vectors[setv_fill_count++] = (long)p; + if (building_shared_object) { + struct relocation_info reloc; + + /* + * Make sure to relocate the contents + * of this set vector. + */ + bzero(&reloc, sizeof(reloc)); + RELOC_ADDRESS(&reloc) = + setv_fill_count * sizeof(long); + alloc_rrs_segment_reloc(NULL, &reloc); + } + + } else if ((type & N_EXT) && type != (N_UNDF | N_EXT) + && (type & N_TYPE) != N_FN + && (type & N_TYPE) != N_SIZE) { + /* non-common definition */ + if (defs++ && sp->value != p->n_value + && entry_symbol/*XXX*/) { + sp->mult_defs = 1; + multiple_def_count++; + } + sp->def_nlist = p; + lsp->entry->flags |= E_SYMBOLS_USED; + sp->defined = type; + sp->aux = N_AUX(p); + } + } + + if (sp->defined) { + if ((sp->defined & N_TYPE) == N_SETV) + /* Allocate zero entry in set vector */ + setv_fill_count++; + /* + * At this stage, we do not know whether an alias + * is going to be defined for real here, or whether + * it refers to a shared object symbol. The decision + * is deferred until digest_pass2(). + */ + if (!sp->alias) + defined_global_sym_count++; + continue; + } + + if (relocatable_output) + /* We're done */ + continue; + + /* + * Still undefined, search the shared object symbols for a + * definition. This symbol must go into the RRS. + */ + if (building_shared_object) { + /* Just punt for now */ + undefined_global_sym_count--; + continue; + } + + again: + for (lsp = sp->sorefs; lsp; lsp = lsp->next) { + register struct nlist *p = &lsp->nzlist.nlist; + register int type = p->n_type; + + if ((type & N_EXT) && type != (N_UNDF | N_EXT) + && (type & N_TYPE) != N_FN) { + /* non-common definition */ + sp->def_nlist = p; + lsp->entry->flags |= E_SYMBOLS_USED; + sp->so_defined = type; + sp->aux = N_AUX(p); + if (sp->flags & GS_REFERENCED) + undefined_global_sym_count--; + else + sp->flags |= GS_REFERENCED; +#ifdef DEBUG +printf("shr: %s gets defined to %x with value %x\n", sp->name, type, sp->value); +#endif + if (sp->alias && !(sp->alias->flags & GS_REFERENCED)) { + sp = sp->alias; + goto again; + } + break; + } + } + } END_EACH_SYMBOL; + + if (setv_fill_count != set_sect_size/sizeof(long)) + fatal("internal error: allocated set symbol space (%d) \ +doesn't match actual (%d)", + set_sect_size/sizeof(long), setv_fill_count); +} + + +/* + * Scan relocation info in ENTRY for contributions to the RRS section + * of the output file. + */ +static void +consider_relocation (entry, dataseg) + struct file_entry *entry; + int dataseg; +{ + struct relocation_info *reloc, *end; + struct localsymbol *lsp; + symbol *sp; + + if (dataseg == 0) { + /* Text relocations */ + reloc = entry->textrel; + end = entry->textrel + entry->ntextrel; + } else { + /* Data relocations */ + reloc = entry->datarel; + end = entry->datarel + entry->ndatarel; + } + + for (; reloc < end; reloc++) { + + if (relocatable_output) { + lsp = &entry->symbols[reloc->r_symbolnum]; + if (RELOC_BASEREL_P(reloc)) { + pic_code_seen = 1; + if (!RELOC_EXTERN_P(reloc)) + lsp->flags |= LS_RENAME; + } + continue; + } + + /* + * First, do the PIC specific relocs. + * r_relative and r_copy should not occur at this point + * (we do output them). The others break down to these + * combinations: + * + * jmptab: extern: needs jmp slot + * !extern: "intersegment" jump/call, + * should get resolved in output + * + * baserel: extern: need GOT entry + * !extern: may need GOT entry, + * machine dependent + * + * baserel's always refer to symbol through `r_symbolnum' + * whether extern or not. Internal baserels refer to statics + * that must be accessed either *through* the GOT table like + * global data, or by means of an offset from the GOT table. + * The macro RELOC_STATICS_THROUGH_GOT_P() determines which + * applies, since this is a machine (compiler?) dependent + * addressing mode. + */ + + if (RELOC_JMPTAB_P(reloc)) { + + if (!RELOC_EXTERN_P(reloc)) + continue; + + lsp = &entry->symbols[reloc->r_symbolnum]; + sp = lsp->symbol; + if (sp->alias) + sp = sp->alias; + alloc_rrs_jmpslot(entry, sp); + + } else if (RELOC_BASEREL_P(reloc)) { + + lsp = &entry->symbols[reloc->r_symbolnum]; + alloc_rrs_gotslot(entry, reloc, lsp); + + } else if (RELOC_EXTERN_P(reloc)) { + + /* + * Non-PIC relocations. + * If the definition comes from a shared object + * we need a relocation entry in RRS. + * + * If the .so definition is N_TEXT a jmpslot is + * allocated. + * + * If it is N_DATA we allocate an address in BSS (?) + * and arrange for the data to be copied at run-time. + * The symbol is temporarily marked with N_SIZE in + * the `defined' field, so we know what to do in + * pass2() and during actual relocation. We convert + * the type back to something real again when writing + * out the symbols. + * + */ + lsp = &entry->symbols[reloc->r_symbolnum]; + sp = lsp->symbol; + if (sp == NULL) + fatal_with_file( + "internal error, sp==NULL", entry); + + if (sp->alias) + sp = sp->alias; + + /* + * Skip refs to _GLOBAL_OFFSET_TABLE_ and __DYNAMIC + */ + if (sp == got_symbol) { + if (!CHECK_GOT_RELOC(reloc)) + fatal_with_file( + "Unexpected relocation type ", entry); + continue; + } + + /* + * This symbol gives rise to a RRS entry + */ + + if (building_shared_object) { + alloc_rrs_reloc(entry, sp); + continue; + } + + if (force_alias_definition && sp->so_defined && + sp->aux == AUX_FUNC) { + + /* Call to shared library procedure */ + alloc_rrs_jmpslot(entry, sp); + + } else if (sp->size && sp->so_defined && + sp->aux == AUX_OBJECT) { + + /* Reference to shared library data */ + alloc_rrs_cpy_reloc(entry, sp); + sp->defined = N_SIZE; + + } else if (!sp->defined && sp->common_size == 0) + alloc_rrs_reloc(entry, sp); + + } else { + /* + * Segment relocation. + * Prepare an RRS relocation as these are load + * address dependent. + */ + if (building_shared_object) { + alloc_rrs_segment_reloc(entry, reloc); + } + } + } +} + +/* + * Determine the disposition of each local symbol. + */ +static void +consider_local_symbols(entry) + register struct file_entry *entry; +{ + register struct localsymbol *lsp, *lspend; + + if (entry->flags & E_DYNAMIC) + return; + + lspend = entry->symbols + entry->nsymbols; + + /* + * For each symbol determine whether it should go + * in the output symbol table. + */ + + for (lsp = entry->symbols; lsp < lspend; lsp++) { + register struct nlist *p = &lsp->nzlist.nlist; + register int type = p->n_type; + + if (type == N_WARNING) + continue; + + if (SET_ELEMENT_P (type)) { + /* + * This occurs even if global. These types of + * symbols are never written globally, though + * they are stored globally. + */ + if (relocatable_output) + lsp->flags |= LS_WRITE; + + } else if (!(type & (N_STAB | N_EXT))) { + + /* + * Ordinary local symbol + */ + if ((lsp->flags & LS_RENAME) || ( + discard_locals != DISCARD_ALL && + !(discard_locals == DISCARD_L && + (lsp->flags & LS_L_SYMBOL))) ) { + + lsp->flags |= LS_WRITE; + local_sym_count++; + } + + } else if (!(type & N_EXT)) { + + /* + * Debugger symbol + */ + if (strip_symbols == STRIP_NONE) { + lsp->flags |= LS_WRITE; + debugger_sym_count++; + } + } + } + + /* + * Count one for the local symbol that we generate, + * whose name is the file's name (usually) and whose address + * is the start of the file's text. + */ + if (discard_locals != DISCARD_ALL) + local_sym_count++; +} + +/* + * Accumulate the section sizes of input file ENTRY into the section sizes of + * the output file. + */ +static void +consider_file_section_lengths (entry) + register struct file_entry *entry; +{ + + entry->text_start_address = text_size; + /* If there were any vectors, we need to chop them off */ + text_size += entry->header.a_text; + entry->data_start_address = data_size; + data_size += entry->header.a_data; + entry->bss_start_address = bss_size; + bss_size += entry->header.a_bss; + + text_reloc_size += entry->header.a_trsize; + data_reloc_size += entry->header.a_drsize; +} + +/* + * Determine where the sections of ENTRY go into the output file, + * whose total section sizes are already known. + * Also relocate the addresses of the file's local and debugger symbols. + */ +static void +relocate_file_addresses (entry) + register struct file_entry *entry; +{ + register struct localsymbol *lsp, *lspend; + + entry->text_start_address += text_start; + /* + * Note that `data_start' and `data_size' have not yet been + * adjusted for `data_pad'. If they had been, we would get the wrong + * results here. + */ + entry->data_start_address += data_start; + entry->bss_start_address += bss_start; +#ifdef DEBUG +printf("%s: datastart: %#x, bss %#x\n", get_file_name(entry), + entry->data_start_address, entry->bss_start_address); +#endif + + lspend = entry->symbols + entry->nsymbols; + + for (lsp = entry->symbols; lsp < lspend; lsp++) { + register struct nlist *p = &lsp->nzlist.nlist; + register int type = p->n_type; + + /* + * If this belongs to a section, update it + * by the section's start address + */ + + switch (type & N_TYPE) { + case N_TEXT: + case N_SETT: + p->n_value += entry->text_start_address; + break; + case N_DATA: + case N_SETD: + case N_SETV: + /* + * A symbol whose value is in the data section is + * present in the input file as if the data section + * started at an address equal to the length of the + * file's text. + */ + p->n_value += entry->data_start_address - + entry->header.a_text; + break; + case N_BSS: + case N_SETB: + /* likewise for symbols with value in BSS. */ + p->n_value += entry->bss_start_address + - entry->header.a_text - entry->header.a_data; + break; + } + + } + +} + +/* + * Assign a value to each global symbol. + */ +static void +digest_pass2() +{ + FOR_EACH_SYMBOL(i, sp) { + int size; + int align = sizeof(int); + + if (!(sp->flags & GS_REFERENCED)) + continue; + + if (sp->alias && + (relocatable_output || building_shared_object || + (sp->alias->defined && !sp->alias->so_defined))) + /* + * The alias points at a defined symbol, so it + * must itself be counted as one too, in order to + * compute the correct number of symbol table entries. + */ + defined_global_sym_count++; + + if ((sp->defined & N_TYPE) == N_SETV) { + /* + * Set length word at front of vector and zero byte + * at end. Reverse the vector itself to put it in + * file order. + */ + unsigned long i, *p, *q; + unsigned long length_word_index = + sp->value / sizeof(long); + + /* Relocate symbol value */ + sp->value += set_sect_start; + + set_vectors[length_word_index] = sp->setv_count; + + /* + * Relocate vector to final address. + */ + for (i = 0; i < sp->setv_count; i++) { + struct nlist *p = (struct nlist *) + set_vectors[1+i+length_word_index]; + + set_vectors[1+i+length_word_index] = p->n_value; + if (building_shared_object) { + struct relocation_info reloc; + + bzero(&reloc, sizeof(reloc)); + RELOC_ADDRESS(&reloc) = + (1 + i + length_word_index) * + sizeof(long) + + set_sect_start; + RELOC_TYPE(&reloc) = + (p->n_type - (N_SETA - N_ABS)) & N_TYPE; + claim_rrs_segment_reloc(NULL, &reloc); + } + } + + /* + * Reverse the vector. + */ + p = &set_vectors[length_word_index + 1]; + q = &set_vectors[length_word_index + sp->setv_count]; + while (p < q) { + unsigned long tmp = *p; + *p++ = *q; + *q-- = tmp; + } + + /* Clear terminating entry */ + set_vectors[length_word_index + sp->setv_count + 1] = 0; + continue; + } + + + if (sp->defined && sp->def_nlist && + ((sp->defined & ~N_EXT) != N_SETV)) + sp->value = sp->def_nlist->n_value; + + /* + * If not -r'ing, allocate common symbols in the BSS section. + */ + if (building_shared_object && !(link_mode & SYMBOLIC)) + /* No common allocation in shared objects */ + continue; + + if ((size = sp->common_size) != 0) { + /* + * It's a common. + */ + if (sp->defined != (N_UNDF + N_EXT)) + fatal("%s: common isn't", sp->name); + + } else if ((size = sp->size) != 0 && sp->defined == N_SIZE) { + /* + * It's data from shared object with size info. + */ + if (!sp->so_defined) + fatal("%s: Bogus N_SIZE item", sp->name); + + } else + /* + * It's neither + */ + continue; + + + if (relocatable_output && !force_common_definition) { + sp->defined = 0; + undefined_global_sym_count++; + defined_global_sym_count--; + continue; + } + + /* + * Round up to nearest sizeof (int). I don't know whether + * this is necessary or not (given that alignment is taken + * care of later), but it's traditional, so I'll leave it in. + * Note that if this size alignment is ever removed, ALIGN + * above will have to be initialized to 1 instead of sizeof + * (int). + */ + + size = PALIGN(size, sizeof(int)); + + while (!(size & align)) + align <<= 1; + + align = align > MAX_ALIGNMENT ? MAX_ALIGNMENT : align; + + bss_size = PALIGN(bss_size + data_size + rrs_data_start, align) + - (data_size + rrs_data_start); + + sp->value = rrs_data_start + data_size + bss_size; + if (sp->defined == (N_UNDF | N_EXT)) + sp->defined = N_BSS | N_EXT; + else { + sp->so_defined = 0; + defined_global_sym_count++; + } + bss_size += size; + if (write_map) + printf("Allocating %s %s: %x at %x\n", + sp->defined==(N_BSS|N_EXT)?"common":"data", + sp->name, size, sp->value); + + } END_EACH_SYMBOL; +} + + +/* -------------------------------------------------------------------*/ + +/* Write the output file */ +void +write_output () +{ + struct stat statbuf; + int filemode; + + if (lstat(output_filename, &statbuf) != -1) { + if (!S_ISDIR(statbuf.st_mode)) + (void)unlink(output_filename); + } + + outdesc = open (output_filename, O_WRONLY | O_CREAT | O_TRUNC, 0666); + if (outdesc < 0) + perror_name (output_filename); + + fatal_cleanup_hook = myfatal; + + if (fstat (outdesc, &statbuf) < 0) + perror_name (output_filename); + + filemode = statbuf.st_mode; + + chmod (output_filename, filemode & ~0111); + + /* Output the a.out header. */ + write_header (); + + /* Output the text and data segments, relocating as we go. */ + write_text (); + write_data (); + + /* Output the merged relocation info, if requested with `-r'. */ + if (relocatable_output) + write_rel (); + + /* Output the symbol table (both globals and locals). */ + write_syms (); + + /* Output the RSS section */ + write_rrs (); + + close (outdesc); + + if (chmod (output_filename, filemode | 0111) == -1) + perror_name (output_filename); +} + +/* Total number of symbols to be written in the output file. */ +static int nsyms; + +void +write_header () +{ + int flags = (rrs_section_type == RRS_FULL) ? EX_DYNAMIC : 0; + + if (oldmagic && (flags & EX_DYNAMIC)) + error("Cannot set flag in old magic headers\n"); + + N_SET_FLAG (outheader, flags); + + outheader.a_text = text_size; + outheader.a_data = data_size; + outheader.a_bss = bss_size; + outheader.a_entry = (entry_symbol ? entry_symbol->value + : text_start + entry_offset); + + if (strip_symbols == STRIP_ALL) + nsyms = 0; + else + nsyms = global_sym_count + local_sym_count + debugger_sym_count; + + if (relocatable_output) + nsyms += set_symbol_count; + + outheader.a_syms = nsyms * sizeof (struct nlist); + + if (relocatable_output) { + outheader.a_trsize = text_reloc_size; + outheader.a_drsize = data_reloc_size; + } else { + outheader.a_trsize = 0; + outheader.a_drsize = 0; + } + + md_swapout_exec_hdr(&outheader); + mywrite (&outheader, sizeof (struct exec), 1, outdesc); + md_swapin_exec_hdr(&outheader); + + /* + * Output whatever padding is required in the executable file + * between the header and the start of the text. + */ + +#ifndef COFF_ENCAPSULATE + padfile (N_TXTOFF(outheader) - sizeof outheader, outdesc); +#endif +} + +/* Relocate the text segment of each input file + and write to the output file. */ + +void +write_text () +{ + + if (trace_files) + fprintf (stderr, "Copying and relocating text:\n\n"); + + each_full_file (copy_text, 0); + file_close (); + + if (trace_files) + fprintf (stderr, "\n"); + + padfile (text_pad, outdesc); +} + +/* + * Read the text segment contents of ENTRY, relocate them, and write the + * result to the output file. If `-r', save the text relocation for later + * reuse. + */ +void +copy_text (entry) + struct file_entry *entry; +{ + register char *bytes; + register int desc; + + if (trace_files) + prline_file_name (entry, stderr); + + desc = file_open (entry); + + /* Allocate space for the file's text section */ + bytes = (char *) alloca (entry->header.a_text); + + /* Deal with relocation information however is appropriate */ + if (entry->textrel == NULL) + fatal_with_file("no text relocation of ", entry); + + /* Read the text section into core. */ + lseek (desc, text_offset (entry), 0); + if (entry->header.a_text != read (desc, bytes, entry->header.a_text)) + fatal_with_file ("premature eof in text section of ", entry); + + + /* Relocate the text according to the text relocation. */ + perform_relocation (bytes, entry->header.a_text, + entry->textrel, entry->ntextrel, entry, 0); + + /* Write the relocated text to the output file. */ + mywrite (bytes, 1, entry->header.a_text, outdesc); +} + +/* Relocate the data segment of each input file + and write to the output file. */ + +void +write_data () +{ + long pos; + + if (trace_files) + fprintf (stderr, "Copying and relocating data:\n\n"); + + pos = N_DATOFF(outheader) + data_start - rrs_data_start; + if (lseek(outdesc, pos, L_SET) != pos) + fatal("write_data: lseek: cant position data offset"); + + each_full_file (copy_data, 0); + file_close (); + + /* + * Write out the set element vectors. See digest symbols for + * description of length of the set vector section. + */ + + if (set_vector_count) { + swap_longs(set_vectors, set_symbol_count + 2*set_vector_count); + mywrite (set_vectors, set_symbol_count + 2*set_vector_count, + sizeof (unsigned long), outdesc); + } + + if (trace_files) + fprintf (stderr, "\n"); + + padfile (data_pad, outdesc); +} + +/* + * Read the data segment contents of ENTRY, relocate them, and write the + * result to the output file. If `-r', save the data relocation for later + * reuse. See comments in `copy_text'. + */ +void +copy_data (entry) + struct file_entry *entry; +{ + register char *bytes; + register int desc; + + if (trace_files) + prline_file_name (entry, stderr); + + desc = file_open (entry); + + bytes = (char *)alloca(entry->header.a_data); + + if (entry->datarel == NULL) + fatal_with_file("no data relocation of ", entry); + + lseek (desc, text_offset (entry) + entry->header.a_text, 0); + if (entry->header.a_data != read(desc, bytes, entry->header.a_data)) + fatal_with_file ("premature eof in data section of ", entry); + + perform_relocation (bytes, entry->header.a_data, + entry->datarel, entry->ndatarel, entry, 1); + + mywrite (bytes, 1, entry->header.a_data, outdesc); +} + +/* + * Relocate ENTRY's text or data section contents. DATA is the address of the + * contents, in core. DATA_SIZE is the length of the contents. PC_RELOCATION + * is the difference between the address of the contents in the output file + * and its address in the input file. RELOC is the address of the + * relocation info, in core. NRELOC says how many there are. + */ + +/* HACK: md.c may need access to this */ +int pc_relocation; + +void +perform_relocation(data, data_size, reloc, nreloc, entry, dataseg) + char *data; + int data_size; + struct relocation_info *reloc; + int nreloc; + struct file_entry *entry; + int dataseg; +{ + + register struct relocation_info *r = reloc; + struct relocation_info *end = reloc + nreloc; + + int text_relocation = entry->text_start_address; + int data_relocation = entry->data_start_address - entry->header.a_text; + int bss_relocation = entry->bss_start_address - + entry->header.a_text - entry->header.a_data; + pc_relocation = dataseg? + entry->data_start_address - entry->header.a_text: + entry->text_start_address; + + for (; r < end; r++) { + int addr = RELOC_ADDRESS(r); + long addend = md_get_addend(r, data+addr); + long relocation; + + /* + * Loop over the relocations again as we did in + * consider_relocation(), claiming the reserved RRS + * relocations. + */ + + if (addr >= data_size) + fatal_with_file( + "relocation address out of range in ", entry); + + if (RELOC_JMPTAB_P(r)) { + + int symindex = RELOC_SYMBOL(r); + struct localsymbol *lsp = &entry->symbols[symindex]; + symbol *sp; + + if (symindex >= entry->nsymbols) + fatal_with_file( + "relocation symbolnum out of range in ", entry); + + sp = lsp->symbol; + if (sp->alias) + sp = sp->alias; + + if (relocatable_output) + relocation = addend; + else if (!RELOC_EXTERN_P(r)) { + relocation = addend + + data_relocation - text_relocation; + } else + relocation = addend + + claim_rrs_jmpslot(entry, r, sp, addend); + + } else if (RELOC_BASEREL_P(r)) { + + int symindex = RELOC_SYMBOL(r); + struct localsymbol *lsp = &entry->symbols[symindex]; + + if (symindex >= entry->nsymbols) + fatal_with_file( + "relocation symbolnum out of range in ", entry); + + if (relocatable_output) + relocation = addend; + else if (!RELOC_EXTERN_P(r)) + relocation = claim_rrs_internal_gotslot(entry, + r, lsp, addend); + else + relocation = claim_rrs_gotslot(entry, + r, lsp, addend); + + } else if (RELOC_EXTERN_P(r)) { + + int symindex = RELOC_SYMBOL(r); + symbol *sp; + + if (symindex >= entry->nsymbols) + fatal_with_file( + "relocation symbolnum out of range in ", entry); + + sp = entry->symbols[symindex].symbol; + if (sp->alias) + sp = sp->alias; + + if (relocatable_output) { + relocation = addend; + /* + * In PIC code, we keep the reference to the + * external symbol, even if defined now. + */ + if (!pic_code_seen) + relocation += sp->value; + } else if (sp->defined) { + if (sp == got_symbol) { + /* Handle _GOT_ refs */ + relocation = addend + sp->value + + md_got_reloc(r); + } else if (building_shared_object) { + /* + * Normal (non-PIC) relocation needs + * to be converted into an RRS reloc + * when building a shared object. + */ + r->r_address += dataseg? + entry->data_start_address: + entry->text_start_address; + relocation = addend; + if (claim_rrs_reloc(entry, r, + sp, &relocation)) + continue; + } else if (sp->defined == N_SIZE) { + /* + * If size is known, arrange a + * run-time copy. + */ + if (!sp->size) + fatal("Copy item isn't: %s", + sp->name); + + relocation = addend + sp->value; + r->r_address = sp->value; + claim_rrs_cpy_reloc(entry, r, sp); + } else + /* Plain old relocation */ + relocation = addend + sp->value; + } else { + /* + * If the symbol is undefined, we relocate it + * in a way similar to -r case. We use an + * RRS relocation to resolve the symbol at + * run-time. The r_address field is updated + * to reflect the changed position in the + * output file. + * + * In case the symbol is defined in a shared + * object as N_TEXT or N_DATA, an appropriate + * jmpslot or copy relocation is generated. + */ + switch (sp->so_defined) { + + case N_TEXT+N_EXT: + /* + * Claim a jmpslot if one was + * allocated (dependent on + * `force_alias_flag'). + */ + + if (sp->jmpslot_offset == -1) + goto undefined; + + relocation = addend + + claim_rrs_jmpslot(entry, r, + sp, addend); + break; + + case N_DATA+N_EXT: + /*FALLTHROUGH*/ + case 0: + undefined: + r->r_address += dataseg? + entry->data_start_address: + entry->text_start_address; + relocation = addend; + if (claim_rrs_reloc(entry, r, + sp, &relocation)) + continue; + break; + + case N_BSS+N_EXT: +printf("%s: BSS found in so_defined\n", sp->name); + /*break;*/ + + default: + fatal("%s: shobj symbol with unknown type %#x", sp->name, sp->so_defined); + break; + } + } + + } else { + + switch (RELOC_TYPE(r)) { + case N_TEXT: + case N_TEXT | N_EXT: + relocation = addend + text_relocation; + break; + + case N_DATA: + case N_DATA | N_EXT: + /* + * A word that points to beginning of the the + * data section initially contains not 0 but + * rather the "address" of that section in + * the input file, which is the length of the + * file's text. + */ + relocation = addend + data_relocation; + break; + + case N_BSS: + case N_BSS | N_EXT: + /* + * Similarly, an input word pointing to the + * beginning of the bss initially contains + * the length of text plus data of the file. + */ + relocation = addend + bss_relocation; + break; + + case N_ABS: + case N_ABS | N_EXT: + /* + * Don't know why this code would occur, but + * apparently it does. + */ + break; + + default: + fatal_with_file( + "nonexternal relocation code invalid in ", entry); + } + + /* + * When building a shared object, these segment + * relocations need a "load address relative" + * RRS fixup. + */ + if (building_shared_object) { + r->r_address += dataseg? + entry->data_start_address: + entry->text_start_address; + claim_rrs_segment_reloc(entry, r); + } + } + + if (RELOC_PCREL_P(r)) + relocation -= pc_relocation; + + md_relocate(r, relocation, data+addr, relocatable_output); + + } +} + +/* + * For relocatable_output only: write out the relocation, + * relocating the addresses-to-be-relocated. + */ + +void +write_rel () +{ + int count = 0; + + if (trace_files) + fprintf (stderr, "Writing text relocation:\n\n"); + + /* + * Assign each global symbol a sequence number, giving the order + * in which `write_syms' will write it. + * This is so we can store the proper symbolnum fields + * in relocation entries we write. + * + + /* BLECH - Assign number 0 to __DYNAMIC (!! Sun compatibility) */ + + if (dynamic_symbol->flags & GS_REFERENCED) + dynamic_symbol->symbolnum = count++; + FOR_EACH_SYMBOL(i, sp) { + if (sp != dynamic_symbol && (sp->flags & GS_REFERENCED)) { + sp->symbolnum = count++; + if (sp->size) + count++; + if (sp->alias) + count++; + } + } END_EACH_SYMBOL; + + if (count != global_sym_count) + fatal ("internal error: write_rel: count = %d", count); + + each_full_file (assign_symbolnums, &count); + + /* Write out the relocations of all files, remembered from copy_text. */ + each_full_file (coptxtrel, 0); + + if (trace_files) + fprintf (stderr, "\nWriting data relocation:\n\n"); + + each_full_file (copdatrel, 0); + + if (trace_files) + fprintf (stderr, "\n"); +} + + +/* + * Assign symbol ordinal numbers to local symbols in each entry. + */ +static void +assign_symbolnums(entry, countp) + struct file_entry *entry; + int *countp; +{ + struct localsymbol *lsp, *lspend; + int n = *countp; + + lspend = entry->symbols + entry->nsymbols; + + if (discard_locals != DISCARD_ALL) + /* Count the N_FN symbol for this entry */ + n++; + + for (lsp = entry->symbols; lsp < lspend; lsp++) { + if (lsp->flags & LS_WRITE) + lsp->symbolnum = n++; + } + *countp = n; +} + +static void +coptxtrel(entry) + struct file_entry *entry; +{ + register struct relocation_info *r, *end; + register int reloc = entry->text_start_address; + + r = entry->textrel; + end = r + entry->ntextrel; + + for (; r < end; r++) { + register int symindex; + struct localsymbol *lsp; + symbol *sp; + + RELOC_ADDRESS(r) += reloc; + + symindex = RELOC_SYMBOL(r); + lsp = &entry->symbols[symindex]; + + if (!RELOC_EXTERN_P(r)) { + if (!pic_code_seen) + continue; + if (RELOC_BASEREL_P(r)) + RELOC_SYMBOL(r) = lsp->symbolnum; + continue; + } + + if (symindex >= entry->nsymbols) + fatal_with_file( + "relocation symbolnum out of range in ", entry); + + sp = lsp->symbol; + +#ifdef N_INDR + /* Resolve indirection. */ + if ((sp->defined & ~N_EXT) == N_INDR) { + if (sp->alias == NULL) + fatal("internal error: alias in hyperspace"); + sp = sp->alias; + } +#endif + + /* + * If the symbol is now defined, change the external + * relocation to an internal one. + */ + + if (sp->defined) { + if (!pic_code_seen) { + RELOC_EXTERN_P(r) = 0; + RELOC_SYMBOL(r) = (sp->defined & N_TYPE); + } else + RELOC_SYMBOL(r) = sp->symbolnum; +#ifdef RELOC_ADD_EXTRA + /* + * If we aren't going to be adding in the + * value in memory on the next pass of the + * loader, then we need to add it in from the + * relocation entry, unless the symbol remains + * external in our output. Otherwise the work we + * did in this pass is lost. + */ + if (!RELOC_MEMORY_ADD_P(r) && !RELOC_EXTERN_P(r)) + RELOC_ADD_EXTRA(r) += sp->value; +#endif + } else + /* + * Global symbols come first. + */ + RELOC_SYMBOL(r) = sp->symbolnum; + } + md_swapout_reloc(entry->textrel, entry->ntextrel); + mywrite(entry->textrel, entry->ntextrel, + sizeof(struct relocation_info), outdesc); +} + +static void +copdatrel(entry) + struct file_entry *entry; +{ + register struct relocation_info *r, *end; + /* + * Relocate the address of the relocation. Old address is relative to + * start of the input file's data section. New address is relative to + * start of the output file's data section. + */ + register int reloc = entry->data_start_address - text_size; + + r = entry->datarel; + end = r + entry->ndatarel; + + for (; r < end; r++) { + register int symindex; + symbol *sp; + int symtype; + + RELOC_ADDRESS(r) += reloc; + + if (!RELOC_EXTERN_P(r)) { + if (RELOC_BASEREL_P(r)) + fatal_with_file( + "Unsupported relocation type in ", + entry); + continue; + } + + symindex = RELOC_SYMBOL(r); + sp = entry->symbols[symindex].symbol; + + if (symindex >= entry->header.a_syms) + fatal_with_file( + "relocation symbolnum out of range in ", entry); + +#ifdef N_INDR + /* Resolve indirection. */ + if ((sp->defined & ~N_EXT) == N_INDR) { + if (sp->alias == NULL) + fatal("internal error: alias in hyperspace"); + sp = sp->alias; + } +#endif + + symtype = sp->defined & N_TYPE; + + if (!pic_code_seen && ( symtype == N_BSS || + symtype == N_DATA || + symtype == N_TEXT || + symtype == N_ABS)) { + RELOC_EXTERN_P(r) = 0; + RELOC_SYMBOL(r) = symtype; + } else + /* + * Global symbols come first. + */ + RELOC_SYMBOL(r) = + entry->symbols[symindex].symbol->symbolnum; + } + md_swapout_reloc(entry->datarel, entry->ndatarel); + mywrite(entry->datarel, entry->ndatarel, + sizeof(struct relocation_info), outdesc); +} + +void write_file_syms __P((struct file_entry *, int *)); +void write_string_table __P((void)); + +/* Offsets and current lengths of symbol and string tables in output file. */ + +static int symbol_table_offset; +static int symbol_table_len; + +/* Address in output file where string table starts. */ +static int string_table_offset; + +/* Offset within string table + where the strings in `strtab_vector' should be written. */ +static int string_table_len; + +/* Total size of string table strings allocated so far, + including strings in `strtab_vector'. */ +static int strtab_size; + +/* Vector whose elements are strings to be added to the string table. */ +static char **strtab_vector; + +/* Vector whose elements are the lengths of those strings. */ +static int *strtab_lens; + +/* Index in `strtab_vector' at which the next string will be stored. */ +static int strtab_index; + +/* + * Add the string NAME to the output file string table. Record it in + * `strtab_vector' to be output later. Return the index within the string + * table that this string will have. + */ + +static int +assign_string_table_index(name) + char *name; +{ + register int index = strtab_size; + register int len = strlen(name) + 1; + + strtab_size += len; + strtab_vector[strtab_index] = name; + strtab_lens[strtab_index++] = len; + + return index; +} + +FILE *outstream = (FILE *) 0; + +/* + * Write the contents of `strtab_vector' into the string table. This is done + * once for each file's local&debugger symbols and once for the global + * symbols. + */ +void +write_string_table () +{ + register int i; + + lseek (outdesc, string_table_offset + string_table_len, 0); + + if (!outstream) + outstream = fdopen (outdesc, "w"); + + for (i = 0; i < strtab_index; i++) { + fwrite (strtab_vector[i], 1, strtab_lens[i], outstream); + string_table_len += strtab_lens[i]; + } + + fflush (outstream); + + /* Report I/O error such as disk full. */ + if (ferror (outstream)) + perror_name (output_filename); +} + +/* Write the symbol table and string table of the output file. */ + +void +write_syms() +{ + /* Number of symbols written so far. */ + int syms_written = 0; + struct nlist nl; + + /* + * Buffer big enough for all the global symbols. One extra struct + * for each indirect symbol to hold the extra reference following. + */ + struct nlist *buf = (struct nlist *) + alloca(global_sym_count * sizeof(struct nlist)); + /* Pointer for storing into BUF. */ + register struct nlist *bufp = buf; + + /* Size of string table includes the bytes that store the size. */ + strtab_size = sizeof strtab_size; + + symbol_table_offset = N_SYMOFF(outheader); + symbol_table_len = 0; + string_table_offset = N_STROFF(outheader); + string_table_len = strtab_size; + + if (strip_symbols == STRIP_ALL) + return; + + /* First, write out the global symbols. */ + + /* + * Allocate two vectors that record the data to generate the string + * table from the global symbols written so far. This must include + * extra space for the references following indirect outputs. + */ + + strtab_vector = (char **) alloca((global_sym_count) * sizeof(char *)); + strtab_lens = (int *) alloca((global_sym_count) * sizeof(int)); + strtab_index = 0; + + /* + * __DYNAMIC symbol *must* be first for Sun compatibility, as Sun's + * ld.so reads the shared object's first symbol. This means that + * (Sun's) shared libraries cannot be stripped! (We only assume + * that __DYNAMIC is the first item in the data segment) + * + * If defined (ie. not relocatable_output), make it look + * like an internal symbol. + */ + if (dynamic_symbol->flags & GS_REFERENCED) { + nl.n_other = 0; + nl.n_desc = 0; + nl.n_type = dynamic_symbol->defined; + if (nl.n_type == N_UNDF) + nl.n_type |= N_EXT; + else + nl.n_type &= ~N_EXT; + nl.n_value = dynamic_symbol->value; + nl.n_un.n_strx = assign_string_table_index(dynamic_symbol->name); + *bufp++ = nl; + syms_written++; + } + + /* Scan the symbol hash table, bucket by bucket. */ + + FOR_EACH_SYMBOL(i, sp) { + + if (sp == dynamic_symbol) + /* Already dealt with above */ + continue; + + if (!(sp->flags & GS_REFERENCED)) + /* Came from shared object but was not used */ + continue; + + if (sp->so_defined || (sp->alias && sp->alias->so_defined)) + /* + * Definition came from shared object, + * don't mention it here + */ + continue; + + if (!sp->defined && !relocatable_output) { + /* + * We're building a shared object and there + * are still undefined symbols. Don't output + * these, symbol was discounted in digest_pass1() + * (they are in the RRS symbol table). + */ + if (!building_shared_object) + error("symbol %s remains undefined", sp->name); + continue; + } + + if (syms_written >= global_sym_count) + fatal( + "internal error: number of symbols exceeds alloc'd %d", + global_sym_count); + + /* + * Construct a `struct nlist' for the symbol. + */ + nl.n_other = 0; + nl.n_desc = 0; + + if (sp->defined > 1) { + /* + * defined with known type + */ + if (!relocatable_output && !building_shared_object && + sp->alias && sp->alias->defined > 1) { + /* + * If the target of an indirect symbol has + * been defined and we are outputting an + * executable, resolve the indirection; it's + * no longer needed. + */ + nl.n_type = sp->alias->defined; + nl.n_value = sp->alias->value; + nl.n_other = N_OTHER(0, sp->alias->aux); + } else { + if (sp->defined == N_SIZE) + nl.n_type = N_DATA | N_EXT; + else + nl.n_type = sp->defined; + if (nl.n_type == (N_INDR|N_EXT) && + sp->value != 0) + fatal("%s: N_INDR has value %#x", + sp->name, sp->value); + nl.n_value = sp->value; + nl.n_other = N_OTHER(0, sp->aux); + } + + } else if (sp->common_size) { + /* + * defined as common but not allocated, + * happens only with -r and not -d, write out + * a common definition. + * + * common condition needs to be before undefined + * condition because unallocated commons are set + * undefined in digest_symbols. + */ + nl.n_type = N_UNDF | N_EXT; + nl.n_value = sp->common_size; + } else if (!sp->defined) { + /* undefined -- legit only if -r */ + nl.n_type = N_UNDF | N_EXT; + nl.n_value = 0; + } else + fatal( + "internal error: %s defined in mysterious way", + sp->name); + + /* + * Allocate string table space for the symbol name. + */ + + nl.n_un.n_strx = assign_string_table_index(sp->name); + + /* Output to the buffer and count it. */ + + *bufp++ = nl; + syms_written++; + + /* + * Write second symbol of an alias pair. + */ + if (nl.n_type == N_INDR + N_EXT) { + if (sp->alias == NULL) + fatal("internal error: alias in hyperspace"); + nl.n_type = N_UNDF + N_EXT; + nl.n_un.n_strx = + assign_string_table_index(sp->alias->name); + nl.n_value = 0; + nl.n_other = 0; + nl.n_desc = 0; + *bufp++ = nl; + syms_written++; + } + + /* + * Write N_SIZE symbol for a symbol with a known size. + */ + if (relocatable_output && sp->size) { + nl.n_type = N_SIZE + N_EXT; + nl.n_un.n_strx = assign_string_table_index(sp->name); + nl.n_value = sp->size; + nl.n_other = 0; + nl.n_desc = 0; + *bufp++ = nl; + syms_written++; + } + +#ifdef DEBUG +printf("writesym(#%d): %s, type %x\n", syms_written, sp->name, sp->defined); +#endif + } END_EACH_SYMBOL; + + if (syms_written != strtab_index || strtab_index != global_sym_count) + fatal("internal error:\ +wrong number (%d) of global symbols written into output file, should be %d", + syms_written, global_sym_count); + + /* Output the buffer full of `struct nlist's. */ + + lseek(outdesc, symbol_table_offset + symbol_table_len, 0); + md_swapout_symbols(buf, bufp - buf); + mywrite(buf, bufp - buf, sizeof(struct nlist), outdesc); + symbol_table_len += sizeof(struct nlist) * (bufp - buf); + + /* Write the strings for the global symbols. */ + write_string_table(); + + /* Write the local symbols defined by the various files. */ + each_file(write_file_syms, &syms_written); + file_close(); + + if (syms_written != nsyms) + fatal("internal error:\ +wrong number of symbols (%d) written into output file, should be %d", + syms_written, nsyms); + + if (symbol_table_offset + symbol_table_len != string_table_offset) + fatal( + "internal error: inconsistent symbol table length: %d vs %s", + symbol_table_offset + symbol_table_len, string_table_offset); + + lseek(outdesc, string_table_offset, 0); + strtab_size = md_swap_long(strtab_size); + mywrite(&strtab_size, sizeof(int), 1, outdesc); +} + + +/* + * Write the local and debugger symbols of file ENTRY. Increment + * *SYMS_WRITTEN_ADDR for each symbol that is written. + */ + +/* + * Note that we do not combine identical names of local symbols. dbx or gdb + * would be confused if we did that. + */ +void +write_file_syms(entry, syms_written_addr) + struct file_entry *entry; + int *syms_written_addr; +{ + struct localsymbol *lsp, *lspend; + + /* Upper bound on number of syms to be written here. */ + int max_syms = entry->nsymbols + 1; + + /* + * Buffer to accumulate all the syms before writing them. It has one + * extra slot for the local symbol we generate here. + */ + struct nlist *buf = (struct nlist *) + alloca(max_syms * sizeof(struct nlist)); + + register struct nlist *bufp = buf; + + if (entry->flags & E_DYNAMIC) + return; + + /* + * Make tables that record, for each symbol, its name and its name's + * length. The elements are filled in by `assign_string_table_index'. + */ + + strtab_vector = (char **) alloca(max_syms * sizeof(char *)); + strtab_lens = (int *) alloca(max_syms * sizeof(int)); + strtab_index = 0; + + /* Generate a local symbol for the start of this file's text. */ + + if (discard_locals != DISCARD_ALL) { + struct nlist nl; + + nl.n_type = N_FN | N_EXT; + nl.n_un.n_strx = assign_string_table_index(entry->local_sym_name); + nl.n_value = entry->text_start_address; + nl.n_desc = 0; + nl.n_other = 0; + *bufp++ = nl; + (*syms_written_addr)++; + } + /* Read the file's string table. */ + + entry->strings = (char *) alloca(entry->string_size); + read_entry_strings(file_open(entry), entry); + + lspend = entry->symbols + entry->nsymbols; + + for (lsp = entry->symbols; lsp < lspend; lsp++) { + register struct nlist *p = &lsp->nzlist.nlist; + register int type = p->n_type; + register int write = 0; + char *name; + + if (!(lsp->flags & LS_WRITE)) + continue; + + if (p->n_un.n_strx == 0) + name = NULL; + else if (!(lsp->flags & LS_RENAME)) + name = p->n_un.n_strx + entry->strings; + else { + char *cp = p->n_un.n_strx + entry->strings; + name = (char *)alloca( + strlen(entry->local_sym_name) + + strlen(cp) + 2 ); + (void)sprintf(name, "%s.%s", entry->local_sym_name, cp); + } + + /* + * If this symbol has a name, allocate space for it + * in the output string table. + */ + + if (name) + p->n_un.n_strx = assign_string_table_index(name); + + /* Output this symbol to the buffer and count it. */ + + *bufp++ = *p; + (*syms_written_addr)++; + } + + /* All the symbols are now in BUF; write them. */ + + lseek(outdesc, symbol_table_offset + symbol_table_len, 0); + md_swapout_symbols(buf, bufp - buf); + mywrite(buf, bufp - buf, sizeof(struct nlist), outdesc); + symbol_table_len += sizeof(struct nlist) * (bufp - buf); + + /* + * Write the string-table data for the symbols just written, using + * the data in vectors `strtab_vector' and `strtab_lens'. + */ + + write_string_table(); + entry->strings = 0; /* Since it will disappear anyway. */ +} + +/* + * Output COUNT*ELTSIZE bytes of data at BUF to the descriptor DESC. + */ +void +mywrite (buf, count, eltsize, desc) + void *buf; + int count; + int eltsize; + int desc; +{ + register int val; + register int bytes = count * eltsize; + + while (bytes > 0) { + val = write (desc, buf, bytes); + if (val <= 0) + perror(output_filename); + buf += val; + bytes -= val; + } +} + +static void +myfatal() +{ + if (outdesc > 0) + unlink(output_filename); +} + +/* + * Output PADDING zero-bytes to descriptor OUTDESC. + * PADDING may be negative; in that case, do nothing. + */ +void +padfile (padding, outdesc) + int padding; + int outdesc; +{ + register char *buf; + if (padding <= 0) + return; + + buf = (char *) alloca (padding); + bzero (buf, padding); + mywrite (buf, padding, 1, outdesc); +} diff --git a/gnu/usr.bin/ld/ld.h b/gnu/usr.bin/ld/ld.h new file mode 100644 index 000000000000..27ff136708f0 --- /dev/null +++ b/gnu/usr.bin/ld/ld.h @@ -0,0 +1,687 @@ +/* + * $Id: ld.h,v 1.10 1994/02/13 20:41:34 jkh Exp $ + */ +/*- + * This code is derived from software copyrighted by the Free Software + * Foundation. + * + * Modified 1991 by Donn Seeley at UUNET Technologies, Inc. + */ + +#define SUN_COMPAT + +#ifndef N_SIZE +#define N_SIZE 0xc +#endif + +#ifndef min +#define min(a,b) ((a) < (b) ? (a) : (b)) +#endif + +#ifndef __P +#ifndef __STDC__ +#define __P(a) () +#else +#define __P(a) a +#endif +#endif + +/* If compiled with GNU C, use the built-in alloca */ +#if defined(__GNUC__) || defined(sparc) +#define alloca __builtin_alloca +#endif + +#ifdef __FreeBSD__ +#define FreeBSD +#endif + +#include "md.h" +#include "link.h" + +/* Macro to control the number of undefined references printed */ +#define MAX_UREFS_PRINTED 10 + +/* Align to power-of-two boundary */ +#define PALIGN(x,p) (((x) + (u_long)(p) - 1) & (-(u_long)(p))) + +/* Align to machine dependent boundary */ +#define MALIGN(x) PALIGN(x,MAX_ALIGNMENT) + +/* Name this program was invoked by. */ +char *progname; + +/* System dependencies */ + +/* Define this to specify the default executable format. */ + +#ifndef DEFAULT_MAGIC +#ifdef FreeBSD +#define DEFAULT_MAGIC QMAGIC +extern int netzmagic; +#else +#define DEFAULT_MAGIC ZMAGIC +#endif +#endif + + +/* + * Ok. Following are the relocation information macros. If your + * system should not be able to use the default set (below), you must + * define the following: + + * relocation_info: This must be typedef'd (or #define'd) to the type + * of structure that is stored in the relocation info section of your + * a.out files. Often this is defined in the a.out.h for your system. + * + * RELOC_ADDRESS (rval): Offset into the current section of the + * <whatever> to be relocated. *Must be an lvalue*. + * + * RELOC_EXTERN_P (rval): Is this relocation entry based on an + * external symbol (1), or was it fully resolved upon entering the + * loader (0) in which case some combination of the value in memory + * (if RELOC_MEMORY_ADD_P) and the extra (if RELOC_ADD_EXTRA) contains + * what the value of the relocation actually was. *Must be an lvalue*. + * + * RELOC_TYPE (rval): If this entry was fully resolved upon + * entering the loader, what type should it be relocated as? + * + * RELOC_SYMBOL (rval): If this entry was not fully resolved upon + * entering the loader, what is the index of it's symbol in the symbol + * table? *Must be a lvalue*. + * + * RELOC_MEMORY_ADD_P (rval): This should return true if the final + * relocation value output here should be added to memory, or if the + * section of memory described should simply be set to the relocation + * value. + * + * RELOC_ADD_EXTRA (rval): (Optional) This macro, if defined, gives + * an extra value to be added to the relocation value based on the + * individual relocation entry. *Must be an lvalue if defined*. + * + * RELOC_PCREL_P (rval): True if the relocation value described is + * pc relative. + * + * RELOC_VALUE_RIGHTSHIFT (rval): Number of bits right to shift the + * final relocation value before putting it where it belongs. + * + * RELOC_TARGET_SIZE (rval): log to the base 2 of the number of + * bytes of size this relocation entry describes; 1 byte == 0; 2 bytes + * == 1; 4 bytes == 2, and etc. This is somewhat redundant (we could + * do everything in terms of the bit operators below), but having this + * macro could end up producing better code on machines without fancy + * bit twiddling. Also, it's easier to understand/code big/little + * endian distinctions with this macro. + * + * RELOC_TARGET_BITPOS (rval): The starting bit position within the + * object described in RELOC_TARGET_SIZE in which the relocation value + * will go. + * + * RELOC_TARGET_BITSIZE (rval): How many bits are to be replaced + * with the bits of the relocation value. It may be assumed by the + * code that the relocation value will fit into this many bits. This + * may be larger than RELOC_TARGET_SIZE if such be useful. + * + * + * Things I haven't implemented + * ---------------------------- + * + * Values for RELOC_TARGET_SIZE other than 0, 1, or 2. + * + * Pc relative relocation for External references. + * + * + */ + + +/* Default macros */ +#ifndef RELOC_ADDRESS + +#define RELOC_ADDRESS(r) ((r)->r_address) +#define RELOC_EXTERN_P(r) ((r)->r_extern) +#define RELOC_TYPE(r) ((r)->r_symbolnum) +#define RELOC_SYMBOL(r) ((r)->r_symbolnum) +#define RELOC_MEMORY_SUB_P(r) 0 +#define RELOC_MEMORY_ADD_P(r) 1 +#undef RELOC_ADD_EXTRA +#define RELOC_PCREL_P(r) ((r)->r_pcrel) +#define RELOC_VALUE_RIGHTSHIFT(r) 0 +#if defined(RTLD) && defined(SUN_COMPAT) +#define RELOC_TARGET_SIZE(r) (2) /* !!!!! Sun BUG compatible */ +#else +#define RELOC_TARGET_SIZE(r) ((r)->r_length) +#endif +#define RELOC_TARGET_BITPOS(r) 0 +#define RELOC_TARGET_BITSIZE(r) 32 + +#define RELOC_JMPTAB_P(r) ((r)->r_jmptable) +#define RELOC_BASEREL_P(r) ((r)->r_baserel) +#define RELOC_RELATIVE_P(r) ((r)->r_relative) +#define RELOC_COPY_P(r) ((r)->r_copy) +#define RELOC_LAZY_P(r) ((r)->r_jmptable) + +#define CHECK_GOT_RELOC(r) ((r)->r_pcrel) + +#endif + +/* + * Internal representation of relocation types + */ +#define RELTYPE_EXTERN 1 +#define RELTYPE_JMPSLOT 2 +#define RELTYPE_BASEREL 4 +#define RELTYPE_RELATIVE 8 +#define RELTYPE_COPY 16 + +#ifdef nounderscore +#define LPREFIX '.' +#else +#define LPREFIX 'L' +#endif + +#ifndef TEXT_START +#define TEXT_START(x) N_TXTADDR(x) +#endif + +#ifndef DATA_START +#define DATA_START(x) N_DATADDR(x) +#endif + +/* If a this type of symbol is encountered, its name is a warning + message to print each time the symbol referenced by the next symbol + table entry is referenced. + + This feature may be used to allow backwards compatibility with + certain functions (eg. gets) but to discourage programmers from + their use. + + So if, for example, you wanted to have ld print a warning whenever + the function "gets" was used in their C program, you would add the + following to the assembler file in which gets is defined: + + .stabs "Obsolete function \"gets\" referenced",30,0,0,0 + .stabs "_gets",1,0,0,0 + + These .stabs do not necessarily have to be in the same file as the + gets function, they simply must exist somewhere in the compilation. */ + +#ifndef N_WARNING +#define N_WARNING 0x1E /* Warning message to print if symbol + included */ +#endif /* This is input to ld */ + +/* Special global symbol types understood by GNU LD. */ + +/* The following type indicates the definition of a symbol as being + an indirect reference to another symbol. The other symbol + appears as an undefined reference, immediately following this symbol. + + Indirection is asymmetrical. The other symbol's value will be used + to satisfy requests for the indirect symbol, but not vice versa. + If the other symbol does not have a definition, libraries will + be searched to find a definition. + + So, for example, the following two lines placed in an assembler + input file would result in an object file which would direct gnu ld + to resolve all references to symbol "foo" as references to symbol + "bar". + + .stabs "_foo",11,0,0,0 + .stabs "_bar",1,0,0,0 + + Note that (11 == (N_INDR | N_EXT)) and (1 == (N_UNDF | N_EXT)). */ + +#ifndef N_INDR +#define N_INDR 0xa +#endif + +/* The following symbols refer to set elements. These are expected + only in input to the loader; they should not appear in loader + output (unless relocatable output is requested). To be recognized + by the loader, the input symbols must have their N_EXT bit set. + All the N_SET[ATDB] symbols with the same name form one set. The + loader collects all of these elements at load time and outputs a + vector for each name. + Space (an array of 32 bit words) is allocated for the set in the + data section, and the n_value field of each set element value is + stored into one word of the array. + The first word of the array is the length of the set (number of + elements). The last word of the vector is set to zero for possible + use by incremental loaders. The array is ordered by the linkage + order; the first symbols which the linker encounters will be first + in the array. + + In C syntax this looks like: + + struct set_vector { + unsigned int length; + unsigned int vector[length]; + unsigned int always_zero; + }; + + Before being placed into the array, each element is relocated + according to its type. This allows the loader to create an array + of pointers to objects automatically. N_SETA type symbols will not + be relocated. + + The address of the set is made into an N_SETV symbol + whose name is the same as the name of the set. + This symbol acts like a N_DATA global symbol + in that it can satisfy undefined external references. + + For the purposes of determining whether or not to load in a library + file, set element definitions are not considered "real + definitions"; they will not cause the loading of a library + member. + + If relocatable output is requested, none of this processing is + done. The symbols are simply relocated and passed through to the + output file. + + So, for example, the following three lines of assembler code + (whether in one file or scattered between several different ones) + will produce a three element vector (total length is five words; + see above), referenced by the symbol "_xyzzy", which will have the + addresses of the routines _init1, _init2, and _init3. + + *NOTE*: If symbolic addresses are used in the n_value field of the + defining .stabs, those symbols must be defined in the same file as + that containing the .stabs. + + .stabs "_xyzzy",23,0,0,_init1 + .stabs "_xyzzy",23,0,0,_init2 + .stabs "_xyzzy",23,0,0,_init3 + + Note that (23 == (N_SETT | N_EXT)). */ + +#ifndef N_SETA +#define N_SETA 0x14 /* Absolute set element symbol */ +#endif /* This is input to LD, in a .o file. */ + +#ifndef N_SETT +#define N_SETT 0x16 /* Text set element symbol */ +#endif /* This is input to LD, in a .o file. */ + +#ifndef N_SETD +#define N_SETD 0x18 /* Data set element symbol */ +#endif /* This is input to LD, in a .o file. */ + +#ifndef N_SETB +#define N_SETB 0x1A /* Bss set element symbol */ +#endif /* This is input to LD, in a .o file. */ + +/* Macros dealing with the set element symbols defined in a.out.h */ +#define SET_ELEMENT_P(x) ((x) >= N_SETA && (x) <= (N_SETB|N_EXT)) +#define TYPE_OF_SET_ELEMENT(x) ((x) - N_SETA + N_ABS) + +#ifndef N_SETV +#define N_SETV 0x1C /* Pointer to set vector in data area. */ +#endif /* This is output from LD. */ + + +#ifndef __GNU_STAB__ + +/* Line number for the data section. This is to be used to describe + the source location of a variable declaration. */ +#ifndef N_DSLINE +#define N_DSLINE (N_SLINE+N_DATA-N_TEXT) +#endif + +/* Line number for the bss section. This is to be used to describe + the source location of a variable declaration. */ +#ifndef N_BSLINE +#define N_BSLINE (N_SLINE+N_BSS-N_TEXT) +#endif + +#endif /* not __GNU_STAB__ */ + + +typedef struct localsymbol { + struct nzlist nzlist; /* n[z]list from file */ + struct glosym *symbol; /* Corresponding global symbol, + if any */ + struct localsymbol *next; /* List of definitions */ + struct file_entry *entry; /* Backpointer to file */ + long gotslot_offset; /* Position in GOT, if any */ + int symbolnum; /* Position in output nlist */ + int flags; +#define LS_L_SYMBOL 1 /* Local symbol starts with an `L' */ +#define LS_WRITE 2 /* Symbol goes in output symtable */ +#define LS_RENAME 4 /* xlat name to `<file>.<name>' */ +#define LS_GOTSLOTCLAIMED 8 /* This symbol has a GOT entry */ +} localsymbol_t; + +/* Symbol table */ + +/* + * Global symbol data is recorded in these structures, one for each global + * symbol. They are found via hashing in 'symtab', which points to a vector + * of buckets. Each bucket is a chain of these structures through the link + * field. + */ + +typedef struct glosym { + struct glosym *link; /* Next symbol hash bucket. */ + char *name; /* Name of this symbol. */ + long value; /* Value of this symbol */ + localsymbol_t *refs; /* Chain of local symbols from object + files pertaining to this global + symbol */ + localsymbol_t *sorefs;/* Same for local symbols from shared + object files. */ + + char *warning; /* message, from N_WARNING nlists */ + int common_size; /* Common size */ + int symbolnum; /* Symbol index in output symbol table */ + int rrs_symbolnum; /* Symbol index in RRS symbol table */ + + struct nlist *def_nlist; /* The local symbol that gave this + global symbol its definition */ + + char defined; /* Definition of this symbol */ + char so_defined; /* Definition of this symbol in a shared + object. These go into the RRS symbol table */ + u_char undef_refs; /* Count of number of "undefined" + messages printed for this symbol */ + u_char mult_defs; /* Same for "multiply defined" symbols */ + struct glosym *alias; /* For symbols of type N_INDR, this + points at the real symbol. */ + int setv_count; /* Number of elements in N_SETV symbols */ + int size; /* Size of this symbol (either from N_SIZE + symbols or a from shared object's RRS */ + int aux; /* Auxiliary type information conveyed in + the `n_other' field of nlists */ + + /* The offset into one of the RRS tables, -1 if not used */ + long jmpslot_offset; + long gotslot_offset; + + long flags; + +#define GS_DEFINED 1 /* Symbol has definition (notyetused)*/ +#define GS_REFERENCED 2 /* Symbol is referred to by something + interesting */ +#define GS_TRACE 4 /* Symbol will be traced */ +#define GS_JMPSLOTCLAIMED 8 /* */ +#define GS_GOTSLOTCLAIMED 0x10 /* Some state bits concerning */ +#define GS_CPYRELOCRESERVED 0x20 /* entries in GOT and PLT tables */ +#define GS_CPYRELOCCLAIMED 0x40 /* */ + +} symbol; + +/* Number of buckets in symbol hash table */ +#define SYMTABSIZE 1009 + +/* The symbol hash table: a vector of SYMTABSIZE pointers to struct glosym. */ +extern symbol *symtab[]; +#define FOR_EACH_SYMBOL(i,sp) { \ + int i; \ + for (i = 0; i < SYMTABSIZE; i++) { \ + register symbol *sp; \ + for (sp = symtab[i]; sp; sp = sp->link) + +#define END_EACH_SYMBOL }} + +/* # of global symbols referenced and not defined. */ +extern int undefined_global_sym_count; + +/* # of undefined symbols referenced by shared objects */ +extern int undefined_shobj_sym_count; + +/* # of multiply defined symbols. */ +extern int multiple_def_count; + +/* # of common symbols. */ +extern int common_defined_global_count; + +/* # of warning symbols encountered. */ +extern int warning_count; + +/* + * Define a linked list of strings which define symbols which should be + * treated as set elements even though they aren't. Any symbol with a prefix + * matching one of these should be treated as a set element. + * + * This is to make up for deficiencies in many assemblers which aren't willing + * to pass any stabs through to the loader which they don't understand. + */ +struct string_list_element { + char *str; + struct string_list_element *next; +}; + +extern symbol *entry_symbol; /* the entry symbol, if any */ +extern symbol *edata_symbol; /* the symbol _edata */ +extern symbol *etext_symbol; /* the symbol _etext */ +extern symbol *end_symbol; /* the symbol _end */ +extern symbol *got_symbol; /* the symbol __GLOBAL_OFFSET_TABLE_ */ +extern symbol *dynamic_symbol; /* the symbol __DYNAMIC */ + +/* + * Each input file, and each library member ("subfile") being loaded, has a + * `file_entry' structure for it. + * + * For files specified by command args, these are contained in the vector which + * `file_table' points to. + * + * For library members, they are dynamically allocated, and chained through the + * `chain' field. The chain is found in the `subfiles' field of the + * `file_entry'. The `file_entry' objects for the members have `superfile' + * fields pointing to the one for the library. + */ + +struct file_entry { + char *filename; /* Name of this file. */ + /* + * Name to use for the symbol giving address of text start Usually + * the same as filename, but for a file spec'd with -l this is the -l + * switch itself rather than the filename. + */ + char *local_sym_name; + struct exec header; /* The file's a.out header. */ + localsymbol_t *symbols; /* Symbol table of the file. */ + int nsymbols; /* Number of symbols in above array. */ + int string_size; /* Size in bytes of string table. */ + char *strings; /* Pointer to the string table when + in core, NULL otherwise */ + int strings_offset; /* Offset of string table, + (normally N_STROFF() + 4) */ + /* + * Next two used only if `relocatable_output' or if needed for + * output of undefined reference line numbers. + */ + struct relocation_info *textrel; /* Text relocations */ + int ntextrel; /* # of text relocations */ + struct relocation_info *datarel; /* Data relocations */ + int ndatarel; /* # of data relocations */ + + /* + * Relation of this file's segments to the output file. + */ + int text_start_address; /* Start of this file's text segment + in the output file core image. */ + int data_start_address; /* Start of this file's data segment + in the output file core image. */ + int bss_start_address; /* Start of this file's bss segment + in the output file core image. */ + struct file_entry *subfiles; /* For a library, points to chain of + entries for the library members. */ + struct file_entry *superfile; /* For library member, points to the + library's own entry. */ + struct file_entry *chain; /* For library member, points to next + entry for next member. */ + int starting_offset; /* For a library member, offset of the + member within the archive. Zero for + files that are not library members.*/ + int total_size; /* Size of contents of this file, + if library member. */ +#ifdef SUN_COMPAT + struct file_entry *silly_archive;/* For shared libraries which have + a .sa companion */ +#endif + int lib_major, lib_minor; /* Version numbers of a shared object */ + + int flags; +#define E_IS_LIBRARY 1 /* File is a an archive */ +#define E_HEADER_VALID 2 /* File's header has been read */ +#define E_SEARCH_DIRS 4 /* Search directories for file */ +#define E_SEARCH_DYNAMIC 8 /* Search for shared libs allowed */ +#define E_JUST_SYMS 0x10 /* File is used for incremental load */ +#define E_DYNAMIC 0x20 /* File is a shared object */ +#define E_SCRAPPED 0x40 /* Ignore this file */ +#define E_SYMBOLS_USED 0x80 /* Symbols from this entry were used */ +}; + +/* + * Section start addresses. + */ +extern int text_size; /* total size of text. */ +extern int text_start; /* start of text */ +extern int text_pad; /* clear space between text and data */ +extern int data_size; /* total size of data. */ +extern int data_start; /* start of data */ +extern int data_pad; /* part of bss segment within data */ + +extern int bss_size; /* total size of bss. */ +extern int bss_start; /* start of bss */ + +extern int text_reloc_size; /* total size of text relocation. */ +extern int data_reloc_size; /* total size of data relocation. */ + +/* + * Runtime Relocation Section (RRS). + * This describes the data structures that go into the output text and data + * segments to support the run-time linker. The RRS can be empty (plain old + * static linking), or can just exist of GOT and PLT entries (in case of + * statically linked PIC code). + */ +extern int rrs_section_type; /* What's in the RRS section */ +#define RRS_NONE 0 +#define RRS_PARTIAL 1 +#define RRS_FULL 2 +extern int rrs_text_size; /* Size of RRS text additions */ +extern int rrs_text_start; /* Location of above */ +extern int rrs_data_size; /* Size of RRS data additions */ +extern int rrs_data_start; /* Location of above */ + +/* Version number to put in __DYNAMIC (set by -V) */ +extern int soversion; +#ifndef DEFAULT_SOVERSION +#define DEFAULT_SOVERSION LD_VERSION_BSD +#endif + +extern int pc_relocation; /* Current PC reloc value */ + +extern int number_of_shobjs; /* # of shared objects linked in */ + +/* Current link mode */ +extern int link_mode; +#define DYNAMIC 1 /* Consider shared libraries */ +#define SYMBOLIC 2 /* Force symbolic resolution */ +#define FORCEARCHIVE 4 /* Force inclusion of all members + of archives */ +#define SHAREABLE 8 /* Build a shared object */ +#define SILLYARCHIVE 16 /* Process .sa companions, if any */ + +extern int outdesc; /* Output file descriptor. */ +extern struct exec outheader; /* Output file header. */ +extern int magic; /* Output file magic. */ +extern int oldmagic; +extern int relocatable_output; + +/* Size of a page. */ +extern int page_size; + +extern char **search_dirs; /* Directories to search for libraries. */ +extern int n_search_dirs; /* Length of above. */ + +extern int write_map; /* write a load map (`-M') */ + +extern void (*fatal_cleanup_hook)__P((void)); + +void read_header __P((int, struct file_entry *)); +void read_entry_symbols __P((int, struct file_entry *)); +void read_entry_strings __P((int, struct file_entry *)); +void read_entry_relocation __P((int, struct file_entry *)); +void enter_file_symbols __P((struct file_entry *)); +void read_file_symbols __P((struct file_entry *)); +void mywrite __P((void *, int, int, int)); + +/* In warnings.c: */ +void perror_name __P((char *)); +void perror_file __P((struct file_entry *)); +void fatal_with_file __P((char *, struct file_entry *, ...)); +void print_symbols __P((FILE *)); +char *get_file_name __P((struct file_entry *)); +void print_file_name __P((struct file_entry *, FILE *)); +void prline_file_name __P((struct file_entry *, FILE *)); +int do_warnings __P((FILE *)); + +/* In etc.c: */ +void *xmalloc __P((int)); +void *xrealloc __P((void *, int)); +void fatal __P((char *, ...)); +void error __P((char *, ...)); +void padfile __P((int,int)); +char *concat __P((const char *, const char *, const char *)); +int parse __P((char *, char *, char *)); + +/* In symbol.c: */ +void symtab_init __P((int)); +symbol *getsym __P((char *)), *getsym_soft __P((char *)); + +/* In lib.c: */ +void search_library __P((int, struct file_entry *)); +void read_shared_object __P((int, struct file_entry *)); +int findlib __P((struct file_entry *)); + +/* In shlib.c: */ +char *findshlib __P((char *, int *, int *, int)); +void add_search_dir __P((char *)); +void std_search_dirs __P((char *)); + +/* In rrs.c: */ +void init_rrs __P((void)); +int rrs_add_shobj __P((struct file_entry *)); +void alloc_rrs_reloc __P((struct file_entry *, symbol *)); +void alloc_rrs_segment_reloc __P((struct file_entry *, struct relocation_info *)); +void alloc_rrs_jmpslot __P((struct file_entry *, symbol *)); +void alloc_rrs_gotslot __P((struct file_entry *, struct relocation_info *, localsymbol_t *)); +void alloc_rrs_cpy_reloc __P((struct file_entry *, symbol *)); + +int claim_rrs_reloc __P((struct file_entry *, struct relocation_info *, symbol *, long *)); +long claim_rrs_jmpslot __P((struct file_entry *, struct relocation_info *, symbol *, long)); +long claim_rrs_gotslot __P((struct file_entry *, struct relocation_info *, struct localsymbol *, long)); +long claim_rrs_internal_gotslot __P((struct file_entry *, struct relocation_info *, struct localsymbol *, long)); +void claim_rrs_cpy_reloc __P((struct file_entry *, struct relocation_info *, symbol *)); +void claim_rrs_segment_reloc __P((struct file_entry *, struct relocation_info *)); + +/* In <md>.c */ +void md_init_header __P((struct exec *, int, int)); +long md_get_addend __P((struct relocation_info *, unsigned char *)); +void md_relocate __P((struct relocation_info *, long, unsigned char *, int)); +void md_make_jmpslot __P((jmpslot_t *, long, long)); +void md_fix_jmpslot __P((jmpslot_t *, long, u_long)); +int md_make_reloc __P((struct relocation_info *, struct relocation_info *, int)); +void md_make_jmpreloc __P((struct relocation_info *, struct relocation_info *, int)); +void md_make_gotreloc __P((struct relocation_info *, struct relocation_info *, int)); +void md_make_copyreloc __P((struct relocation_info *, struct relocation_info *)); + +#ifdef NEED_SWAP +void md_swapin_exec_hdr __P((struct exec *)); +void md_swapout_exec_hdr __P((struct exec *)); +void md_swapin_reloc __P((struct relocation_info *, int)); +void md_swapout_reloc __P((struct relocation_info *, int)); +void md_swapout_jmpslot __P((jmpslot_t *, int)); + +/* In xbits.c: */ +void swap_longs __P((long *, int)); +void swap_symbols __P((struct nlist *, int)); +void swap_zsymbols __P((struct nzlist *, int)); +void swap_ranlib_hdr __P((struct ranlib *, int)); +void swap__dynamic __P((struct link_dynamic *)); +void swap_section_dispatch_table __P((struct section_dispatch_table *)); +void swap_so_debug __P((struct so_debug *)); +void swapin_sod __P((struct sod *, int)); +void swapout_sod __P((struct sod *, int)); +void swapout_fshash __P((struct fshash *, int)); +#endif diff --git a/gnu/usr.bin/ld/ldconfig/Makefile b/gnu/usr.bin/ld/ldconfig/Makefile new file mode 100644 index 000000000000..04768a7c9b3c --- /dev/null +++ b/gnu/usr.bin/ld/ldconfig/Makefile @@ -0,0 +1,13 @@ +# $Id: Makefile,v 1.6 1994/02/13 20:42:18 jkh Exp $ + +PROG= ldconfig +SRCS= ldconfig.c shlib.c etc.c +LDDIR?= $(.CURDIR)/.. +CFLAGS+=-I$(LDDIR) -I$(.CURDIR) -I$(LDDIR)/$(MACHINE) +LDSTATIC=-static +BINDIR= /sbin +MAN8= ldconfig.8 + +.PATH: $(LDDIR) $(LDDIR)/$(MACHINE) + +.include <bsd.prog.mk> diff --git a/gnu/usr.bin/ld/ldconfig/ldconfig.8 b/gnu/usr.bin/ld/ldconfig/ldconfig.8 new file mode 100644 index 000000000000..32c35afc8041 --- /dev/null +++ b/gnu/usr.bin/ld/ldconfig/ldconfig.8 @@ -0,0 +1,100 @@ +.Dd October 3, 1993 +.Dt LDCONFIG 8 +.Os FreeBSD 1.1 +.Sh NAME +.Nm ldconfig +.Nd configure the shared library cache +.Sh SYNOPSIS +.Nm ldconfig +.Op Fl rsv +.Op Ar directory Ar ... +.Sh DESCRIPTION +.Nm +is used to prepare a set of +.Dq hints +for use by the run-time linker +.Xr ld.so +to facilitate quick lookup of shared libraries available in multiple +directories. It scans a set of built-in system directories and any +.Ar directories +specified on the command line (in the given order) looking for shared +libraries and stores the results in the file +.Xr /var/run/ld.so.hints +to forstall the overhead that would otherwise result from the +directory search operations +.Xr ld.so +would have to perform to load the required shared libraries. +.Pp +The shared libraries so found will be automatically available for loading +if needed by the program being prepared for execution. This obviates the need +for storing search paths within the executable. +.Pp +The +.Ev LD_LIBRARY_PATH +environment variable can be used to override the use of +directories (or the order thereof) from the cache or to specify additional +directories where shared libraries might be found. +.Ev LD_LIBRARY_PATH +is a +.Sq \: +separated list of directory paths which are searched by +.Xr ld.so +when it needs to load a shared library. It can be viewed as the run-time +equivalent of the +.Fl L +switch of +.Xr ld. +.Pp +.Nm Ldconfig +is typically run as part of the boot sequence. +.Pp +The following options recognized by +.Nm ldconfig: +.Bl -tag -width indent +.It Fl r +Lists the current contents of +.Xr ld.so.hints +on the standard output. The hints file will not be modified. +.It Fl s +Do not scan +.Nm ldconfig +\'s builtin system directories +.Sq /usr/lib +, +.Sq /usr/X386/lib +and +.Sq /usr/local/lib +for shared libraries. +.It Fl v +Switch on verbose mode. +.Sh Security +Special care must be taken when loading shared libraries into the address +space of +.Ev set-user-Id +programs. Whenever such a program is run, +.Xr ld.so +will only load shared libraries from the +.Ev ld.so.hints +file. In particular, the +.Ev LD_LIBRARY_PATH +is not used to search for libraries. Thus, the role of ldconfig is dual. In +addition to building a set of hints for quick lookup, it also serves to +specify the trusted collection of directories from which shared objects can +be safely loaded. It is presumed that the set of directories specified to +.Nm ldconfig +are under control of the system's administrator. +.Xr ld.so +further assists set-user-Id programs by erasing the +.Ev LD_LIBRARY_PATH +from the environment. + +.Sh FILES +.Xr /var/run/ld.so.hints +.Sh SEE ALSO +.Xr ld 1 , +.Xr link 5 +.Sh HISTORY +A +.Nm +utility first appeared in SunOS 4.0, it appeared in its current form +in FreeBSD 1.1. diff --git a/gnu/usr.bin/ld/ldconfig/ldconfig.c b/gnu/usr.bin/ld/ldconfig/ldconfig.c new file mode 100644 index 000000000000..4c840ffd3144 --- /dev/null +++ b/gnu/usr.bin/ld/ldconfig/ldconfig.c @@ -0,0 +1,426 @@ +/* + * Copyright (c) 1993 Paul Kranenburg + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Paul Kranenburg. + * 4. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * $Id: ldconfig.c,v 1.5 1994/02/13 20:42:30 jkh Exp $ + */ + +#include <sys/param.h> +#include <stdio.h> +#include <stdlib.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <sys/file.h> +#include <sys/time.h> +#include <sys/mman.h> +#include <sys/resource.h> +#include <fcntl.h> +#include <errno.h> +#include <ar.h> +#include <ranlib.h> +#include <a.out.h> +#include <stab.h> +#include <string.h> +#include <dirent.h> + +#include "ld.h" + +#undef major +#undef minor + +char *progname; +static int verbose; +static int nostd; +static int justread; + +struct shlib_list { + /* Internal list of shared libraries found */ + char *name; + char *path; + int dewey[MAXDEWEY]; + int ndewey; +#define major dewey[0] +#define minor dewey[1] + struct shlib_list *next; +}; + +static struct shlib_list *shlib_head = NULL, **shlib_tail = &shlib_head; + +static void enter __P((char *, char *, char *, int *, int)); +static int dodir __P((char *, int)); +static int build_hints __P((void)); + +int +main(argc, argv) +int argc; +char *argv[]; +{ + int i, c; + int rval = 0; + extern int optind; + + if ((progname = strrchr(argv[0], '/')) == NULL) + progname = argv[0]; + else + progname++; + + while ((c = getopt(argc, argv, "rsv")) != EOF) { + switch (c) { + case 'v': + verbose = 1; + break; + case 's': + nostd = 1; + break; + case 'r': + justread = 1; + break; + default: + fprintf(stderr, "Usage: %s [-v] [dir ...]\n", progname); + exit(1); + break; + } + } + + if (justread) + return listhints(); + + if (!nostd) + std_search_dirs(NULL); + + for (i = 0; i < n_search_dirs; i++) + rval |= dodir(search_dirs[i], 1); + + for (i = optind; i < argc; i++) + rval |= dodir(argv[i], 0); + + rval |= build_hints(); + + return rval; +} + +int +dodir(dir, silent) +char *dir; +int silent; +{ + DIR *dd; + struct dirent *dp; + char name[MAXPATHLEN], rest[MAXPATHLEN]; + int dewey[MAXDEWEY], ndewey; + + if ((dd = opendir(dir)) == NULL) { + if (!silent || errno != ENOENT) + perror(dir); + return -1; + } + + while ((dp = readdir(dd)) != NULL) { + int n; + + name[0] = rest[0] = '\0'; + + n = sscanf(dp->d_name, "lib%[^.].so.%s", + name, rest); + + if (n < 2 || rest[0] == '\0') + continue; + + ndewey = getdewey(dewey, rest); + enter(dir, dp->d_name, name, dewey, ndewey); + } + + return 0; +} + +static void +enter(dir, file, name, dewey, ndewey) +char *dir, *file, *name; +int dewey[], ndewey; +{ + struct shlib_list *shp; + + for (shp = shlib_head; shp; shp = shp->next) { + if (strcmp(name, shp->name) != 0 || major != shp->major) + continue; + + /* Name matches existing entry */ + if (cmpndewey(dewey, ndewey, shp->dewey, shp->ndewey) > 0) { + + /* Update this entry with higher versioned lib */ + if (verbose) + printf("Updating lib%s.%d.%d to %s/%s\n", + shp->name, shp->major, shp->minor, + dir, file); + + free(shp->name); + shp->name = strdup(name); + free(shp->path); + shp->path = concat(dir, "/", file); + bcopy(dewey, shp->dewey, sizeof(shp->dewey)); + shp->ndewey = ndewey; + } + break; + } + + if (shp) + /* Name exists: older version or just updated */ + return; + + /* Allocate new list element */ + if (verbose) + printf("Adding %s/%s\n", dir, file); + + shp = (struct shlib_list *)xmalloc(sizeof *shp); + shp->name = strdup(name); + shp->path = concat(dir, "/", file); + bcopy(dewey, shp->dewey, MAXDEWEY); + shp->ndewey = ndewey; + shp->next = NULL; + + *shlib_tail = shp; + shlib_tail = &shp->next; +} + + +#if DEBUG +/* test */ +#undef _PATH_LD_HINTS +#define _PATH_LD_HINTS "./ld.so.hints" +#endif + +int +hinthash(cp, vmajor, vminor) +char *cp; +int vmajor, vminor; +{ + int k = 0; + + while (*cp) + k = (((k << 1) + (k >> 14)) ^ (*cp++)) & 0x3fff; + + k = (((k << 1) + (k >> 14)) ^ (vmajor*257)) & 0x3fff; + k = (((k << 1) + (k >> 14)) ^ (vminor*167)) & 0x3fff; + + return k; +} + +int +build_hints() +{ + struct hints_header hdr; + struct hints_bucket *blist; + struct shlib_list *shp; + char *strtab; + int i, n, str_index = 0; + int strtab_sz = 0; /* Total length of strings */ + int nhints = 0; /* Total number of hints */ + int fd; + char *tmpfile; + + for (shp = shlib_head; shp; shp = shp->next) { + strtab_sz += 1 + strlen(shp->name); + strtab_sz += 1 + strlen(shp->path); + nhints++; + } + + /* Fill hints file header */ + hdr.hh_magic = HH_MAGIC; + hdr.hh_version = LD_HINTS_VERSION_1; + hdr.hh_nbucket = 1 * nhints; + n = hdr.hh_nbucket * sizeof(struct hints_bucket); + hdr.hh_hashtab = sizeof(struct hints_header); + hdr.hh_strtab = hdr.hh_hashtab + n; + hdr.hh_strtab_sz = strtab_sz; + hdr.hh_ehints = hdr.hh_strtab + hdr.hh_strtab_sz; + + if (verbose) + printf("Totals: entries %d, buckets %d, string size %d\n", + nhints, hdr.hh_nbucket, strtab_sz); + + /* Allocate buckets and string table */ + blist = (struct hints_bucket *)xmalloc(n); + bzero((char *)blist, n); + for (i = 0; i < hdr.hh_nbucket; i++) + /* Empty all buckets */ + blist[i].hi_next = -1; + + strtab = (char *)xmalloc(strtab_sz); + + /* Enter all */ + for (shp = shlib_head; shp; shp = shp->next) { + struct hints_bucket *bp; + + bp = blist + + (hinthash(shp->name, shp->major, shp->minor) % hdr.hh_nbucket); + + if (bp->hi_pathx) { + int i; + + for (i = 0; i < hdr.hh_nbucket; i++) { + if (blist[i].hi_pathx == 0) + break; + } + if (i == hdr.hh_nbucket) { + fprintf(stderr, "Bummer!\n"); + return -1; + } + while (bp->hi_next != -1) + bp = &blist[bp->hi_next]; + bp->hi_next = i; + bp = blist + i; + } + + /* Insert strings in string table */ + bp->hi_namex = str_index; + strcpy(strtab + str_index, shp->name); + str_index += 1 + strlen(shp->name); + + bp->hi_pathx = str_index; + strcpy(strtab + str_index, shp->path); + str_index += 1 + strlen(shp->path); + + /* Copy versions */ + bcopy(shp->dewey, bp->hi_dewey, sizeof(bp->hi_dewey)); + bp->hi_ndewey = shp->ndewey; + } + + tmpfile = concat(_PATH_LD_HINTS, "+", ""); + if ((fd = open(tmpfile, O_RDWR|O_CREAT|O_TRUNC, 0444)) == -1) { + perror(_PATH_LD_HINTS); + return -1; + } + + if (write(fd, &hdr, sizeof(struct hints_header)) != + sizeof(struct hints_header)) { + perror(_PATH_LD_HINTS); + return -1; + } + if (write(fd, blist, hdr.hh_nbucket * sizeof(struct hints_bucket)) != + hdr.hh_nbucket * sizeof(struct hints_bucket)) { + perror(_PATH_LD_HINTS); + return -1; + } + if (write(fd, strtab, strtab_sz) != strtab_sz) { + perror(_PATH_LD_HINTS); + return -1; + } + if (close(fd) != 0) { + perror(_PATH_LD_HINTS); + return -1; + } + + /* Install it */ + if (unlink(_PATH_LD_HINTS) != 0 && errno != ENOENT) { + perror(_PATH_LD_HINTS); + return -1; + } + + if (rename(tmpfile, _PATH_LD_HINTS) != 0) { + perror(_PATH_LD_HINTS); + return -1; + } + + return 0; +} + +int +listhints() +{ + int fd; + caddr_t addr; + long msize; + struct hints_header *hdr; + struct hints_bucket *blist; + char *strtab; + int i; + + if ((fd = open(_PATH_LD_HINTS, O_RDONLY, 0)) == -1) { + perror(_PATH_LD_HINTS); + return -1; + } + + msize = PAGSIZ; + addr = mmap(0, msize, PROT_READ, MAP_FILE|MAP_COPY, fd, 0); + + if (addr == (caddr_t)-1) { + perror(_PATH_LD_HINTS); + return -1; + } + + hdr = (struct hints_header *)addr; + if (HH_BADMAG(*hdr)) { + fprintf(stderr, "%s: Bad magic: %d\n"); + return -1; + } + + if (hdr->hh_version != LD_HINTS_VERSION_1) { + fprintf(stderr, "Unsupported version: %d\n", hdr->hh_version); + return -1; + } + + if (hdr->hh_ehints > msize) { + if (mmap(addr+msize, hdr->hh_ehints - msize, + PROT_READ, MAP_FILE|MAP_COPY|MAP_FIXED, + fd, msize) != (caddr_t)(addr+msize)) { + + perror(_PATH_LD_HINTS); + return -1; + } + } + close(fd); + + blist = (struct hints_bucket *)(addr + hdr->hh_hashtab); + strtab = (char *)(addr + hdr->hh_strtab); + + printf("%s:\n", _PATH_LD_HINTS); + for (i = 0; i < hdr->hh_nbucket; i++) { + struct hints_bucket *bp = &blist[i]; + + /* Sanity check */ + if (bp->hi_namex >= hdr->hh_strtab_sz) { + fprintf(stderr, "Bad name index: %#x\n", bp->hi_namex); + return -1; + } + if (bp->hi_pathx >= hdr->hh_strtab_sz) { + fprintf(stderr, "Bad path index: %#x\n", bp->hi_pathx); + return -1; + } + + printf("\t%d:-l%s.%d.%d => %s (%d -> %d)\n", + i, + strtab + bp->hi_namex, bp->hi_major, bp->hi_minor, + strtab + bp->hi_pathx, + hinthash(strtab+bp->hi_namex, bp->hi_major, bp->hi_minor) + % hdr->hh_nbucket, + bp->hi_next); + } + + return 0; +} + diff --git a/gnu/usr.bin/ld/ldd/Makefile b/gnu/usr.bin/ld/ldd/Makefile new file mode 100644 index 000000000000..2d2473fa7661 --- /dev/null +++ b/gnu/usr.bin/ld/ldd/Makefile @@ -0,0 +1,7 @@ +# $Id: Makefile,v 1.3 1993/12/16 21:51:27 nate Exp $ + +PROG= ldd +SRCS= ldd.c +BINDIR= /usr/bin + +.include <bsd.prog.mk> diff --git a/gnu/usr.bin/ld/ldd/ldd.1 b/gnu/usr.bin/ld/ldd/ldd.1 new file mode 100644 index 000000000000..f5a6abadcf49 --- /dev/null +++ b/gnu/usr.bin/ld/ldd/ldd.1 @@ -0,0 +1,25 @@ +.Dd October 22, 1993 +.Dt LDD 1 +.Os FreeBSD 1.1 +.Sh NAME +.Nm ldd +.Nd list dynamic object dependencies +.Sh SYNOPSIS +.Nm ldd +.Op Ar filename Ar ... +.Sh DESCRIPTION +.Nm ldd +displays all shared objects that are needed to run the given program. +Contrary to nm(1), the list includes +.Dq indirect +depedencies that are the result of needed shared objects which themselves +depend on yet other shared objects. +.Sh SEE ALSO +.Xr ld 1 , +.Xr ld.so 1 , +.Xr nm 1 +.Sh HISTORY +A +.Nm ldd +utility first appeared in SunOS 4.0, it appeared in its current form +in FreeBSD 1.1. diff --git a/gnu/usr.bin/ld/ldd/ldd.c b/gnu/usr.bin/ld/ldd/ldd.c new file mode 100644 index 000000000000..74e5de2ef82b --- /dev/null +++ b/gnu/usr.bin/ld/ldd/ldd.c @@ -0,0 +1,140 @@ +/* + * Copyright (c) 1993 Paul Kranenburg + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Paul Kranenburg. + * 4. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * $Id: ldd.c,v 1.3 1994/02/13 20:42:43 jkh Exp $ + */ + +#include <sys/param.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <errno.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <sys/file.h> +#include <sys/time.h> +#include <sys/resource.h> +#include <fcntl.h> +#include <sys/wait.h> +#include <a.out.h> + +static char *progname; + +void +usage() +{ + fprintf(stderr, "Usage: %s <filename> ...\n", progname); +} + +int +main(argc, argv) +int argc; +char *argv[]; +{ + int rval = 0; + int c; + extern int optind; + + if ((progname = strrchr(argv[0], '/')) == NULL) + progname = argv[0]; + else + progname++; + + while ((c = getopt(argc, argv, "")) != EOF) { + switch (c) { + default: + usage(); + exit(1); + } + } + argc -= optind; + argv += optind; + + if (argc <= 0) { + usage(); + exit(1); + } + + /* ld.so magic */ + setenv("LD_TRACE_LOADED_OBJECTS", "", 1); + + while (argc--) { + int fd; + struct exec hdr; + int status; + + if ((fd = open(*argv, O_RDONLY, 0)) < 0) { + perror(*argv); + rval |= 1; + argv++; + continue; + } + if (read(fd, &hdr, sizeof hdr) != sizeof hdr || + !(N_GETFLAG(hdr) & EX_DYNAMIC)) { + fprintf(stderr, "%s: not a dynamic executable\n", + *argv); + (void)close(fd); + rval |= 1; + argv++; + continue; + } + (void)close(fd); + + printf("%s:\n", *argv); + fflush(stdout); + + switch (fork()) { + case -1: + perror("fork"); + exit(1); + break; + default: + if (wait(&status) <= 0) + perror("wait"); + + if (WIFSIGNALED(status)) { + fprintf(stderr, "%s: signal %d\n", + *argv, WTERMSIG(status)); + rval |= 1; + } else if (WIFEXITED(status) && WEXITSTATUS(status)) { + fprintf(stderr, "%s: exit status %d\n", + *argv, WEXITSTATUS(status)); + rval |= 1; + } + break; + case 0: + rval != execl(*argv, *argv, NULL) != 0; + perror(*argv); + _exit(1); + } + argv++; + } + + return rval; +} diff --git a/gnu/usr.bin/ld/lib.c b/gnu/usr.bin/ld/lib.c new file mode 100644 index 000000000000..f9d8de0fbd7c --- /dev/null +++ b/gnu/usr.bin/ld/lib.c @@ -0,0 +1,819 @@ +/* + * $Id: lib.c,v 1.9 1994/02/13 20:41:37 jkh Exp $ - library routines + */ + +#include <sys/param.h> +#include <stdio.h> +#include <stdlib.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <sys/file.h> +#include <sys/time.h> +#include <fcntl.h> +#include <ar.h> +#include <ranlib.h> +#include <a.out.h> +#include <stab.h> +#include <string.h> +#include <dirent.h> + +#include "ld.h" + +static void linear_library __P((int, struct file_entry *)); +static void symdef_library __P((int, struct file_entry *, int)); +static struct file_entry *decode_library_subfile __P((int, + struct file_entry *, + int, int *)); + +/* + * Search the library ENTRY, already open on descriptor DESC. This means + * deciding which library members to load, making a chain of `struct + * file_entry' for those members, and entering their global symbols in the + * hash table. + */ + +void +search_library(desc, entry) + int desc; + struct file_entry *entry; +{ + int member_length; + register char *name; + register struct file_entry *subentry; + + if (!(link_mode & FORCEARCHIVE) && !undefined_global_sym_count) + return; + + /* Examine its first member, which starts SARMAG bytes in. */ + subentry = decode_library_subfile(desc, entry, SARMAG, &member_length); + if (!subentry) + return; + + name = subentry->filename; + free(subentry); + + /* Search via __.SYMDEF if that exists, else linearly. */ + + if (!strcmp(name, "__.SYMDEF")) + symdef_library(desc, entry, member_length); + else + linear_library(desc, entry); +} + +/* + * Construct and return a file_entry for a library member. The library's + * file_entry is library_entry, and the library is open on DESC. + * SUBFILE_OFFSET is the byte index in the library of this member's header. + * We store the length of the member into *LENGTH_LOC. + */ + +static struct file_entry * +decode_library_subfile(desc, library_entry, subfile_offset, length_loc) + int desc; + struct file_entry *library_entry; + int subfile_offset; + int *length_loc; +{ + int bytes_read; + register int namelen; + int member_length, content_length; + int starting_offset; + register char *name; + struct ar_hdr hdr1; + register struct file_entry *subentry; + + lseek(desc, subfile_offset, 0); + + bytes_read = read(desc, &hdr1, sizeof hdr1); + if (!bytes_read) + return 0; /* end of archive */ + + if (sizeof hdr1 != bytes_read) + fatal_with_file("malformed library archive ", library_entry); + + if (sscanf(hdr1.ar_size, "%d", &member_length) != 1) + fatal_with_file("malformatted header of archive member in ", library_entry); + + subentry = (struct file_entry *) xmalloc(sizeof(struct file_entry)); + bzero(subentry, sizeof(struct file_entry)); + + for (namelen = 0; + namelen < sizeof hdr1.ar_name + && hdr1.ar_name[namelen] != 0 && hdr1.ar_name[namelen] != ' ' + && hdr1.ar_name[namelen] != '/'; + namelen++); + + starting_offset = subfile_offset + sizeof hdr1; + content_length = member_length; + +#ifdef AR_EFMT1 + /* + * BSD 4.4 extended AR format: #1/<namelen>, with name as the + * first <namelen> bytes of the file + */ + if (strncmp(hdr1.ar_name, AR_EFMT1, sizeof(AR_EFMT1) - 1) == 0 && + isdigit(hdr1.ar_name[sizeof(AR_EFMT1) - 1])) { + + namelen = atoi(&hdr1.ar_name[sizeof(AR_EFMT1) - 1]); + name = (char *)xmalloc(namelen + 1); + if (read(desc, name, namelen) != namelen) + fatal_with_file( + "malformatted header of archive member in ", + library_entry); + name[namelen] = 0; + content_length -= namelen; + starting_offset += namelen; + } else + +#endif + { + name = (char *)xmalloc(namelen + 1); + strncpy(name, hdr1.ar_name, namelen); + name[namelen] = 0; + } + + subentry->filename = name; + subentry->local_sym_name = name; + subentry->symbols = 0; + subentry->strings = 0; + subentry->subfiles = 0; + subentry->starting_offset = starting_offset; + subentry->superfile = library_entry; + subentry->chain = 0; + subentry->flags = 0; + subentry->total_size = content_length; + + (*length_loc) = member_length; + + return subentry; +} + +static int subfile_wanted_p __P((struct file_entry *)); + +/* + * Search a library that has a __.SYMDEF member. DESC is a descriptor on + * which the library is open. The file pointer is assumed to point at the + * __.SYMDEF data. ENTRY is the library's file_entry. MEMBER_LENGTH is the + * length of the __.SYMDEF data. + */ + +static void +symdef_library(desc, entry, member_length) + int desc; + struct file_entry *entry; + int member_length; +{ + int *symdef_data = (int *) xmalloc(member_length); + register struct ranlib *symdef_base; + char *sym_name_base; + int nsymdefs; + int length_of_strings; + int not_finished; + int bytes_read; + register int i; + struct file_entry *prev = 0; + int prev_offset = 0; + + bytes_read = read(desc, symdef_data, member_length); + if (bytes_read != member_length) + fatal_with_file("malformatted __.SYMDEF in ", entry); + + nsymdefs = md_swap_long(*symdef_data) / sizeof(struct ranlib); + if (nsymdefs < 0 || + nsymdefs * sizeof(struct ranlib) + 2 * sizeof(int) > member_length) + fatal_with_file("malformatted __.SYMDEF in ", entry); + + symdef_base = (struct ranlib *) (symdef_data + 1); + length_of_strings = md_swap_long(*(int *) (symdef_base + nsymdefs)); + + if (length_of_strings < 0 + || nsymdefs * sizeof(struct ranlib) + length_of_strings + + 2 * sizeof(int) > member_length) + fatal_with_file("malformatted __.SYMDEF in ", entry); + + sym_name_base = sizeof(int) + (char *) (symdef_base + nsymdefs); + + /* Check all the string indexes for validity. */ + md_swapin_ranlib_hdr(symdef_base, nsymdefs); + for (i = 0; i < nsymdefs; i++) { + register int index = symdef_base[i].ran_un.ran_strx; + if (index < 0 || index >= length_of_strings + || (index && *(sym_name_base + index - 1))) + fatal_with_file("malformatted __.SYMDEF in ", entry); + } + + /* + * Search the symdef data for members to load. Do this until one + * whole pass finds nothing to load. + */ + + not_finished = 1; + while (not_finished) { + + not_finished = 0; + + /* + * Scan all the symbols mentioned in the symdef for ones that + * we need. Load the library members that contain such + * symbols. + */ + + for (i = 0; (i < nsymdefs && + ((link_mode & FORCEARCHIVE) || + undefined_global_sym_count || + common_defined_global_count)); i++) { + + register symbol *sp; + int junk; + register int j; + register int offset = symdef_base[i].ran_off; + struct file_entry *subentry; + + + if (symdef_base[i].ran_un.ran_strx < 0) + continue; + + sp = getsym_soft(sym_name_base + + symdef_base[i].ran_un.ran_strx); + + /* + * If we find a symbol that appears to be needed, + * think carefully about the archive member that the + * symbol is in. + */ + + /* + * Per Mike Karels' recommendation, we no longer load + * library files if the only reference(s) that would + * be satisfied are 'common' references. This + * prevents some problems with name pollution (e.g. a + * global common 'utime' linked to a function). + */ + if (!(link_mode & FORCEARCHIVE) && + (!sp || sp->defined || + (!(sp->flags & GS_REFERENCED) && + !sp->sorefs))) + continue; + + /* + * Don't think carefully about any archive member + * more than once in a given pass. + */ + + if (prev_offset == offset) + continue; + prev_offset = offset; + + /* + * Read the symbol table of the archive member. + */ + + subentry = decode_library_subfile(desc, + entry, offset, &junk); + if (subentry == 0) + fatal( + "invalid offset for %s in symbol table of %s", + sym_name_base + + symdef_base[i].ran_un.ran_strx, + entry->filename); + + read_entry_symbols(desc, subentry); + subentry->strings = (char *) + malloc(subentry->string_size); + read_entry_strings(desc, subentry); + + /* + * Now scan the symbol table and decide whether to + * load. + */ + + if (!(link_mode & FORCEARCHIVE) && + !subfile_wanted_p(subentry)) { + free(subentry->symbols); + free(subentry); + } else { + /* + * This member is needed; load it. Since we + * are loading something on this pass, we + * must make another pass through the symdef + * data. + */ + + not_finished = 1; + + read_entry_relocation(desc, subentry); + enter_file_symbols(subentry); + + if (prev) + prev->chain = subentry; + else + entry->subfiles = subentry; + prev = subentry; + + /* + * Clear out this member's symbols from the + * symdef data so that following passes won't + * waste time on them. + */ + + for (j = 0; j < nsymdefs; j++) { + if (symdef_base[j].ran_off == offset) + symdef_base[j].ran_un.ran_strx = -1; + } + } + + /* + * We'll read the strings again if we need them + * again. + */ + free(subentry->strings); + subentry->strings = 0; + } + } + + free(symdef_data); +} + +/* + * Search a library that has no __.SYMDEF. ENTRY is the library's file_entry. + * DESC is the descriptor it is open on. + */ + +static void +linear_library(desc, entry) + int desc; + struct file_entry *entry; +{ + register struct file_entry *prev = 0; + register int this_subfile_offset = SARMAG; + + while ((link_mode & FORCEARCHIVE) || + undefined_global_sym_count || common_defined_global_count) { + + int member_length; + register struct file_entry *subentry; + + subentry = decode_library_subfile(desc, entry, + this_subfile_offset, &member_length); + + if (!subentry) + return; + + read_entry_symbols(desc, subentry); + subentry->strings = (char *) alloca(subentry->string_size); + read_entry_strings(desc, subentry); + + if (!(link_mode & FORCEARCHIVE) && + !subfile_wanted_p(subentry)) { + free(subentry->symbols); + free(subentry); + } else { + read_entry_relocation(desc, subentry); + enter_file_symbols(subentry); + + if (prev) + prev->chain = subentry; + else + entry->subfiles = subentry; + prev = subentry; + subentry->strings = 0; /* Since space will dissapear + * on return */ + } + + this_subfile_offset += member_length + sizeof(struct ar_hdr); + if (this_subfile_offset & 1) + this_subfile_offset++; + } +} + +/* + * ENTRY is an entry for a library member. Its symbols have been read into + * core, but not entered. Return nonzero if we ought to load this member. + */ + +static int +subfile_wanted_p(entry) + struct file_entry *entry; +{ + struct localsymbol *lsp, *lspend; +#ifdef DOLLAR_KLUDGE + register int dollar_cond = 0; +#endif + + lspend = entry->symbols + entry->nsymbols; + + for (lsp = entry->symbols; lsp < lspend; lsp++) { + register struct nlist *p = &lsp->nzlist.nlist; + register int type = p->n_type; + register char *name = p->n_un.n_strx + entry->strings; + register symbol *sp = getsym_soft(name); + + /* + * If the symbol has an interesting definition, we could + * potentially want it. + */ + if (! (type & N_EXT) + || (type == (N_UNDF | N_EXT) && p->n_value == 0 + +#ifdef DOLLAR_KLUDGE + && name[1] != '$' +#endif + ) +#ifdef SET_ELEMENT_P + || SET_ELEMENT_P(type) + || set_element_prefixed_p(name) +#endif + ) + continue; + + +#ifdef DOLLAR_KLUDGE + if (name[1] == '$') { + sp = getsym_soft(&name[2]); + dollar_cond = 1; + if (!sp) + continue; + if (sp->flags & SP_REFERENCED) { + if (write_map) { + print_file_name(entry, stdout); + fprintf(stdout, " needed due to $-conditional %s\n", name); + } + return 1; + } + continue; + } +#endif + + /* + * If this symbol has not been hashed, we can't be + * looking for it. + */ + + if (!sp) + continue; + + /* + * We don't load a file if it merely satisfies a + * common reference (see explanation above in + * symdef_library()). + */ + if ((sp->flags & GS_REFERENCED) && !sp->defined) { + /* + * This is a symbol we are looking for. It + * is either not yet defined or defined as a + * common. + */ +#ifdef DOLLAR_KLUDGE + if (dollar_cond) + continue; +#endif + if (type == (N_UNDF | N_EXT)) { + /* + * Symbol being defined as common. + * Remember this, but don't load + * subfile just for this. + */ + + /* + * If it didn't used to be common, up + * the count of common symbols. + */ + if (!sp->common_size) + common_defined_global_count++; + + if (sp->common_size < p->n_value) + sp->common_size = p->n_value; + if (!sp->defined) + undefined_global_sym_count--; + sp->defined = type; + continue; + } + if (write_map) { + print_file_name(entry, stdout); + fprintf(stdout, " needed due to %s\n", sp->name); + } + return 1; + } else { + /* + * Check for undefined symbols or commons + * in shared objects. + */ + struct localsymbol *lsp; + int wascommon = sp->defined && sp->common_size; + int iscommon = type == (N_UNDF|N_EXT) && p->n_value; + + if (wascommon) { + /* + * sp was defined as common by shared object. + */ + if (iscommon && p->n_value < sp->common_size) + sp->common_size = p->n_value; + continue; + } + + if (sp->sorefs == NULL) + continue; + + for (lsp = sp->sorefs; lsp; lsp = lsp->next) { + int type = lsp->nzlist.nlist.n_type; + if ( (type & N_EXT) && + (type & N_STAB) == 0 && + type != (N_UNDF | N_EXT)) + break; /* We don't need it */ + } + if (lsp != NULL) { + /* There's a real definition */ + if (iscommon) + /* + * But this member wants it to be + * a common; ignore it. + continue; + } + + if (iscommon) { + /* + * New symbol is common, just takes its + * size, but don't load. + */ + sp->common_size = p->n_value; + sp->defined = type; + continue; + } + + /* + * THIS STILL MISSES the case where one shared + * object defines a common and the next defines + * more strongly; fix this someday by making + * `struct glosym' and enter_global_ref() more + * symmetric. + */ + + if (write_map) { + print_file_name(entry, stdout); + fprintf(stdout, " needed due to shared lib ref %s\n", sp->name); + } + return 1; + } + } + + return 0; +} + +/* + * Read the symbols of dynamic entity ENTRY into core. Assume it is already + * open, on descriptor DESC. + */ +void +read_shared_object (desc, entry) + struct file_entry *entry; + int desc; +{ + struct _dynamic dyn; + struct section_dispatch_table sdt; + struct nlist *np; + struct nzlist *nzp; + int n, i, has_nz = 0; + + if (!(entry->flags & E_HEADER_VALID)) + read_header (desc, entry); + + /* Read DYNAMIC structure (first in data segment) */ + lseek (desc, + text_offset (entry) + entry->header.a_text, + L_SET); + if (read(desc, &dyn, sizeof dyn) != sizeof dyn) { + fatal_with_file ( + "premature eof in data segment of ", entry); + } + md_swapin__dynamic(&dyn); + + /* Check version */ + switch (dyn.d_version) { + default: + fatal_with_file( "unsupported _DYNAMIC version ", entry); + break; + case LD_VERSION_SUN: + break; + case LD_VERSION_BSD: + has_nz = 1; + break; + } + + /* Read Section Dispatch Table (from data segment) */ + lseek (desc, + text_offset(entry) + (long)dyn.d_un.d_sdt - + (DATA_START(entry->header) - N_DATOFF(entry->header)), + L_SET); + if (read(desc, &sdt, sizeof sdt) != sizeof sdt) { + fatal_with_file( "premature eof in data segment of ", entry); + } + md_swapin_section_dispatch_table(&sdt); + + /* Read symbols (text segment) */ + n = sdt.sdt_strings - sdt.sdt_nzlist; + entry->nsymbols = n / + (has_nz ? sizeof(struct nzlist) : sizeof(struct nlist)); + nzp = (struct nzlist *)(np = (struct nlist *) alloca (n)); + entry->symbols = (struct localsymbol *) + xmalloc(entry->nsymbols * sizeof(struct localsymbol)); + lseek(desc, text_offset(entry) + (long)sdt.sdt_nzlist - + (TEXT_START(entry->header) - N_TXTOFF(entry->header)), + L_SET); + if (read(desc, (char *)nzp, n) != n) { + fatal_with_file( + "premature eof while reading object symbols ", entry); + } + if (has_nz) + md_swapin_zsymbols(nzp, entry->nsymbols); + else + md_swapin_symbols(np, entry->nsymbols); + + /* Convert to structs localsymbol */ + for (i = 0; i < entry->nsymbols; i++) { + if (has_nz) { + entry->symbols[i].nzlist = *nzp++; + } else { + entry->symbols[i].nzlist.nlist = *np++; + entry->symbols[i].nzlist.nz_size = 0; + } + entry->symbols[i].symbol = NULL; + entry->symbols[i].next = NULL; + entry->symbols[i].entry = entry; + entry->symbols[i].gotslot_offset = -1; + entry->symbols[i].flags = 0; + } + + /* Read strings (text segment) */ + n = entry->string_size = sdt.sdt_str_sz; + entry->strings = (char *) alloca(n); + entry->strings_offset = text_offset(entry) + sdt.sdt_strings; + lseek(desc, entry->strings_offset - + (TEXT_START(entry->header) - N_TXTOFF(entry->header)), + L_SET); + if (read(desc, entry->strings, n) != n) { + fatal_with_file( + "premature eof while reading object strings ", entry); + } + enter_file_symbols (entry); + entry->strings = 0; + + /* + * Load any subsidiary shared objects. + */ + if (sdt.sdt_sods) { + struct sod sod; + off_t offset; + struct file_entry *prev = NULL; + + offset = (off_t)sdt.sdt_sods; + while (1) { + struct file_entry *subentry; + char *libname, name[MAXPATHLEN]; /*XXX*/ + + subentry = (struct file_entry *) + xmalloc(sizeof(struct file_entry)); + bzero(subentry, sizeof(struct file_entry)); + subentry->superfile = entry; + + lseek(desc, offset - + (TEXT_START(entry->header) - N_TXTOFF(entry->header)), + L_SET); + if (read(desc, &sod, sizeof(sod)) != sizeof(sod)) { + fatal_with_file( + "premature eof while reading sod ", + entry); + } + md_swapin_sod(&sod, 1); + (void)lseek(desc, (off_t)sod.sod_name - + (TEXT_START(entry->header) - N_TXTOFF(entry->header)), + L_SET); + (void)read(desc, name, sizeof(name)); /*XXX*/ + if (sod.sod_library) { + int sod_major = sod.sod_major; + int sod_minor = sod.sod_minor; + + libname = findshlib(name, + &sod_major, &sod_minor, 0); + if (libname == NULL) + fatal("no shared -l%s.%d.%d available", + name, sod.sod_major, sod.sod_minor); + subentry->filename = libname; + subentry->local_sym_name = concat("-l", name, ""); + } else { + subentry->filename = strdup(name); + subentry->local_sym_name = strdup(name); + } + read_file_symbols(subentry); + + if (prev) + prev->chain = subentry; + else + entry->subfiles = subentry; + prev = subentry; + desc = file_open(entry); + if ((offset = (off_t)sod.sod_next) == 0) + break; + } + } +#ifdef SUN_COMPAT + if (link_mode & SILLYARCHIVE) { + char *cp, *sa_name; + char armag[SARMAG]; + int fd; + struct file_entry *subentry; + + sa_name = strdup(entry->filename); + if (sa_name == NULL) + goto out; + cp = sa_name + strlen(sa_name) - 1; + while (cp > sa_name) { + if (!isdigit(*cp) && *cp != '.') + break; + --cp; + } + if (cp <= sa_name || *cp != 'o') { + /* Not in `libxxx.so.n.m' form */ + free(sa_name); + goto out; + } + + *cp = 'a'; + if ((fd = open(sa_name, O_RDONLY, 0)) < 0) + goto out; + + /* Read archive magic */ + bzero(armag, SARMAG); + (void)read(fd, armag, SARMAG); + (void)close(fd); + if (strncmp(armag, ARMAG, SARMAG) != 0) { + error("%s: malformed silly archive", + get_file_name(entry)); + goto out; + } + + subentry = (struct file_entry *) + xmalloc(sizeof(struct file_entry)); + bzero(subentry, sizeof(struct file_entry)); + + entry->silly_archive = subentry; + subentry->superfile = entry; + subentry->filename = sa_name; + subentry->local_sym_name = sa_name; + subentry->flags |= E_IS_LIBRARY; + search_library(file_open(subentry), subentry); +out: + ; + } +#endif +} + +#undef major +#undef minor + +int +findlib(p) +struct file_entry *p; +{ + int desc; + int i; + int len; + int major = -1, minor = -1; + char *cp, *fname = NULL; + + if (!(p->flags & E_SEARCH_DYNAMIC)) + goto dot_a; + + fname = findshlib(p->filename, &major, &minor, 1); + + if (fname && (desc = open (fname, O_RDONLY, 0)) > 0) { + p->filename = fname; + p->lib_major = major; + p->lib_minor = minor; + p->flags &= ~E_SEARCH_DIRS; + return desc; + } + free (fname); + +dot_a: + p->flags &= ~E_SEARCH_DYNAMIC; + if (cp = strrchr(p->filename, '/')) { + *cp++ = '\0'; + fname = concat(concat(p->filename, "/lib", cp), ".a", ""); + *(--cp) = '/'; + } else + fname = concat("lib", p->filename, ".a"); + + for (i = 0; i < n_search_dirs; i++) { + register char *string + = concat (search_dirs[i], "/", fname); + desc = open (string, O_RDONLY, 0); + if (desc > 0) { + p->filename = string; + p->flags &= ~E_SEARCH_DIRS; + break; + } + free (string); + } + return desc; +} + diff --git a/gnu/usr.bin/ld/rrs.c b/gnu/usr.bin/ld/rrs.c new file mode 100644 index 000000000000..050fcd6552ea --- /dev/null +++ b/gnu/usr.bin/ld/rrs.c @@ -0,0 +1,1174 @@ +/* + * Copyright (c) 1993 Paul Kranenburg + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Paul Kranenburg. + * 4. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * $Id: rrs.c,v 1.11 1994/02/13 20:41:40 jkh Exp $ + */ + +#include <sys/param.h> +#include <stdio.h> +#include <stdlib.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <sys/file.h> +#include <sys/time.h> +#include <sys/resource.h> +#include <fcntl.h> +#include <ar.h> +#include <ranlib.h> +#include <a.out.h> +#include <stab.h> +#include <string.h> +#include <strings.h> + +#include "ld.h" + +static struct _dynamic rrs_dyn; /* defined in link.h */ +static struct so_debug rrs_so_debug; /* defined in link.h */ +static struct section_dispatch_table rrs_sdt; /* defined in link.h */ +static got_t *rrs_got; +static jmpslot_t *rrs_plt; /* defined in md.h */ +static struct relocation_info *rrs_reloc; +static struct nzlist *rrs_symbols; /* RRS symbol table */ +static char *rrs_strtab; /* RRS strings */ +static struct rrs_hash *rrs_hashtab; /* RT hash table */ +static struct shobj *rrs_shobjs; + +static int reserved_rrs_relocs; +static int claimed_rrs_relocs; + +static int number_of_gotslots; +static int number_of_jmpslots; +static int number_of_rrs_hash_entries; +static int number_of_rrs_symbols; +static int rrs_strtab_size; +static int rrs_symbol_size; + +static int current_jmpslot_offset; +static int current_got_offset; +static int current_reloc_offset; +static int current_hash_index; +int number_of_shobjs; + +struct shobj { + struct shobj *next; + struct file_entry *entry; +}; + +/* +RRS text segment: + +-------------------+ <-- sdt_rel (rrs_text_start) + | | + | relocation | + | | + +-------------------+ <-- <sdt>.sdt_hash + | | + | hash buckets | + | | + +-------------------+ <-- <sdt>.sdt_nzlist + | | + | symbols | + | | + +-------------------+ <-- <sdt>.sdt_strings + | | + | strings | + | | + +-------------------+ <-- <sdt>.sdt_sods + | | + | shobjs | + | | + +-------------------+ + | | + | shobjs strings | <-- <shobj>.sod_name + | | + +-------------------+ + + +RRS data segment: + + +-------------------+ <-- __DYNAMIC (rrs_data_start) + | | + | _dymamic | + | | + +-------------------+ <-- __DYNAMIC.d_debug + | | + | so_debug | + | | + +-------------------+ <-- __DYNAMIC.d_un.d_sdt + | | + | sdt | + | | + +-------------------+ <-- _GLOBAL_OFFSET_TABLE_ (sdt_got) + | | + | _GOT_ | + | | + +-------------------+ <-- sdt_plt + | | + | PLT | + | | + +-------------------+ +*/ + +/* + * Initialize RRS + */ + +void +init_rrs() +{ + reserved_rrs_relocs = 0; + claimed_rrs_relocs = 0; + + number_of_rrs_symbols = 0; + rrs_strtab_size = 0; + + /* First jmpslot reserved for run-time binder */ + current_jmpslot_offset = sizeof(jmpslot_t); + number_of_jmpslots = 1; + + /* First gotslot reserved for __DYNAMIC */ + current_got_offset = sizeof(got_t); + number_of_gotslots = 1; + + current_reloc_offset = 0; +} + +/* + * Add NAME to the list of needed run-time objects. + * Return 1 if ENTRY was added to the list. + */ +int +rrs_add_shobj(entry) +struct file_entry *entry; +{ + struct shobj **p; + + for (p = &rrs_shobjs; *p != NULL; p = &(*p)->next) + if (strcmp((*p)->entry->filename, entry->filename) == 0) + return 0; + *p = (struct shobj *)xmalloc(sizeof(struct shobj)); + (*p)->next = NULL; + (*p)->entry = entry; + + number_of_shobjs++; + return 1; +} + +void +alloc_rrs_reloc(entry, sp) +struct file_entry *entry; +symbol *sp; +{ +#ifdef DEBUG +printf("alloc_rrs_reloc: %s in %s\n", sp->name, get_file_name(entry)); +#endif + reserved_rrs_relocs++; +} + +void +alloc_rrs_segment_reloc(entry, r) +struct file_entry *entry; +struct relocation_info *r; +{ +#ifdef DEBUG +printf("alloc_rrs_segment_reloc at %#x in %s\n", + r->r_address, get_file_name(entry)); +#endif + reserved_rrs_relocs++; +} + +void +alloc_rrs_jmpslot(entry, sp) +struct file_entry *entry; +symbol *sp; +{ + if (sp->jmpslot_offset == -1) { + sp->jmpslot_offset = current_jmpslot_offset; + current_jmpslot_offset += sizeof(jmpslot_t); + number_of_jmpslots++; + if (!(link_mode & SYMBOLIC) || JMPSLOT_NEEDS_RELOC) { + reserved_rrs_relocs++; + } + } +} + +void +alloc_rrs_gotslot(entry, r, lsp) +struct file_entry *entry; +struct relocation_info *r; +struct localsymbol *lsp; +{ + symbol *sp = lsp->symbol; + + if (!RELOC_EXTERN_P(r)) { + + if (sp != NULL) { + error("%s: relocation for internal symbol expected at %#x", + get_file_name(entry), RELOC_ADDRESS(r)); + return; + } + + if (!RELOC_STATICS_THROUGH_GOT_P(r)) + /* No need for a GOT slot */ + return; + + if (lsp->gotslot_offset == -1) { + lsp->gotslot_offset = current_got_offset; + current_got_offset += sizeof(got_t); + number_of_gotslots++; + /* + * Now, see if slot needs run-time fixing + * If the load address is known (entry_symbol), this + * slot will have its final value set by `claim_got' + */ + if ((link_mode & SHAREABLE) || (link_mode & SYMBOLIC)) + reserved_rrs_relocs++; + } + + } else { + + if (sp == NULL) { + error("%s: relocation must refer to global symbol at %#x", + get_file_name(entry), RELOC_ADDRESS(r)); + return; + } + + if (sp->alias) + sp = sp->alias; + + if (sp->gotslot_offset != -1) + return; + + /* + * External symbols always get a relocation entry + */ + sp->gotslot_offset = current_got_offset; + reserved_rrs_relocs++; + current_got_offset += sizeof(got_t); + number_of_gotslots++; + } + +} + +void +alloc_rrs_cpy_reloc(entry, sp) +struct file_entry *entry; +symbol *sp; +{ + if (sp->flags & GS_CPYRELOCRESERVED) + return; +#ifdef DEBUG +printf("alloc_rrs_copy: %s in %s\n", sp->name, get_file_name(entry)); +#endif + sp->flags |= GS_CPYRELOCRESERVED; + reserved_rrs_relocs++; +} + +static struct relocation_info * +rrs_next_reloc() +{ + struct relocation_info *r; + + r = rrs_reloc + claimed_rrs_relocs++; + if (claimed_rrs_relocs > reserved_rrs_relocs) + fatal("internal error: RRS relocs exceed allocation %d", + reserved_rrs_relocs); + return r; +} + +/* + * Claim a RRS relocation as a result of a regular (ie. non-PIC) + * relocation record in a rel file. + * + * Return 1 if the output file needs no further updating. + * Return 0 if the relocation value pointed to by RELOCATION must + * written to a.out. + */ +int +claim_rrs_reloc(entry, rp, sp, relocation) +struct file_entry *entry; +struct relocation_info *rp; +symbol *sp; +long *relocation; +{ + struct relocation_info *r = rrs_next_reloc(); + + if (rp->r_address < text_start + text_size) + error("%s: RRS text relocation at %#x for \"%s\"", + get_file_name(entry), rp->r_address, sp->name); + +#ifdef DEBUG +printf("claim_rrs_reloc: %s in %s\n", sp->name, get_file_name(entry)); +#endif + r->r_address = rp->r_address; + r->r_symbolnum = sp->rrs_symbolnum; + + if (link_mode & SYMBOLIC) { + if (!sp->defined) + error("Cannot reduce symbol \"%s\" in %s", + sp->name, get_file_name(entry)); + RELOC_EXTERN_P(r) = 0; + *relocation += sp->value; + (void) md_make_reloc(rp, r, RELTYPE_RELATIVE); + return 0; + } else { + RELOC_EXTERN_P(r) = 1; + return md_make_reloc(rp, r, RELTYPE_EXTERN); + } +} + +/* + * Claim a jmpslot. Setup RRS relocation if claimed for the first time. + */ +long +claim_rrs_jmpslot(entry, rp, sp, addend) +struct file_entry *entry; +struct relocation_info *rp; +symbol *sp; +long addend; +{ + struct relocation_info *r; + + if (sp->flags & GS_JMPSLOTCLAIMED) + return rrs_sdt.sdt_plt + sp->jmpslot_offset; + +#ifdef DEBUG +printf("claim_rrs_jmpslot: %s: %s(%d) -> offset %x (textreloc %#x)\n", + get_file_name(entry), + sp->name, sp->rrs_symbolnum, sp->jmpslot_offset, text_relocation); +#endif + + if (sp->jmpslot_offset == -1) + fatal( + "internal error: %s: claim_rrs_jmpslot: %s: jmpslot_offset == -1\n", + get_file_name(entry), + sp->name); + + if ((link_mode & SYMBOLIC) || rrs_section_type == RRS_PARTIAL) { + if (!sp->defined) + error("Cannot reduce symbol \"%s\" in %s", + sp->name, get_file_name(entry)); + + md_fix_jmpslot( rrs_plt + sp->jmpslot_offset/sizeof(jmpslot_t), + rrs_sdt.sdt_plt + sp->jmpslot_offset, + sp->value); + if (!JMPSLOT_NEEDS_RELOC) { + return rrs_sdt.sdt_plt + sp->jmpslot_offset; + } + } else { + md_make_jmpslot(rrs_plt + sp->jmpslot_offset/sizeof(jmpslot_t), + sp->jmpslot_offset, + claimed_rrs_relocs); + } + + if (rrs_section_type == RRS_PARTIAL) + /* PLT is self-contained */ + return rrs_sdt.sdt_plt + sp->jmpslot_offset; + + /* + * Install a run-time relocation for this PLT entry. + */ + r = rrs_next_reloc(); + sp->flags |= GS_JMPSLOTCLAIMED; + + RELOC_SYMBOL(r) = sp->rrs_symbolnum; + + r->r_address = (long)rrs_sdt.sdt_plt + sp->jmpslot_offset; + + if (link_mode & SYMBOLIC) { + RELOC_EXTERN_P(r) = 0; + md_make_jmpreloc(rp, r, RELTYPE_RELATIVE); + } else { + RELOC_EXTERN_P(r) = 1; + md_make_jmpreloc(rp, r, 0); + } + + return rrs_sdt.sdt_plt + sp->jmpslot_offset; +} + +/* + * Claim GOT entry for a global symbol. If this is the first relocation + * claiming the entry, setup a RRS relocation for it. + * Return offset into the GOT allocated to this symbol. + */ +long +claim_rrs_gotslot(entry, rp, lsp, addend) +struct file_entry *entry; +struct relocation_info *rp; +struct localsymbol *lsp; +long addend; +{ + struct relocation_info *r; + symbol *sp = lsp->symbol; + int reloc_type = 0; + + if (sp == NULL) { + return 0; + } + + if (sp->alias) + sp = sp->alias; + +#ifdef DEBUG +printf("claim_rrs_gotslot: %s(%d) slot offset %#x, addend %#x\n", + sp->name, sp->rrs_symbolnum, sp->gotslot_offset, addend); +#endif + if (sp->gotslot_offset == -1) + fatal( + "internal error: %s: claim_rrs_gotslot: %s: gotslot_offset == -1\n", + get_file_name(entry), sp->name); + + if (sp->flags & GS_GOTSLOTCLAIMED) + /* This symbol already passed here before. */ + return sp->gotslot_offset; + + if (sp->defined && + (!(link_mode & SHAREABLE) || (link_mode & SYMBOLIC))) { + + /* + * Reduce to just a base-relative translation. + */ + + *(got_t *)((long)rrs_got + sp->gotslot_offset) = + sp->value + addend; + reloc_type = RELTYPE_RELATIVE; + + } else if ((link_mode & SYMBOLIC) || rrs_section_type == RRS_PARTIAL) { + /* + * SYMBOLIC: all symbols must be known. + * RRS_PARTIAL: we don't link against shared objects, + * so again all symbols must be known. + */ + error("Cannot reduce symbol \"%s\" in %s", + sp->name, get_file_name(entry)); + + } else { + + /* + * This gotslot will be updated with symbol value at run-rime. + */ + + *(got_t *)((long)rrs_got + sp->gotslot_offset) = addend; + } + + if (rrs_section_type == RRS_PARTIAL) { + /* + * Base address is known, gotslot should be fully + * relocated by now. + * NOTE: RRS_PARTIAL implies !SHAREABLE. + */ + if (!sp->defined) + error("Cannot reduce symbol \"%s\" in %s", + sp->name, get_file_name(entry)); + return sp->gotslot_offset; + } + + /* + * Claim a relocation entry. + * If symbol is defined and in "main" (!SHAREABLE) + * we still put out a relocation as we cannot easily + * undo the allocation. + * `RELTYPE_RELATIVE' relocations have the external bit off + * as no symbol need be looked up at run-time. + */ + r = rrs_next_reloc(); + sp->flags |= GS_GOTSLOTCLAIMED; + r->r_address = rrs_sdt.sdt_got + sp->gotslot_offset; + RELOC_SYMBOL(r) = sp->rrs_symbolnum; + RELOC_EXTERN_P(r) = !(reloc_type == RELTYPE_RELATIVE); + md_make_gotreloc(rp, r, reloc_type); + + return sp->gotslot_offset; +} + +/* + * Claim a GOT entry for a static symbol. Return offset of the + * allocated GOT entry. If RELOC_STATICS_THROUGH_GOT_P is in effect + * return the offset of the symbol with respect to the *location* of + * the GOT. + */ +long +claim_rrs_internal_gotslot(entry, rp, lsp, addend) +struct file_entry *entry; +struct relocation_info *rp; +struct localsymbol *lsp; +long addend; +{ + struct relocation_info *r; + + addend += lsp->nzlist.nz_value; + + if (!RELOC_STATICS_THROUGH_GOT_P(r)) + return addend - rrs_sdt.sdt_got; + +#ifdef DEBUG +printf("claim_rrs_internal_gotslot: %s: slot offset %#x, addend = %#x\n", + get_file_name(entry), lsp->gotslot_offset, addend); +#endif + + if (lsp->gotslot_offset == -1) + fatal( + "internal error: %s: claim_rrs_internal_gotslot at %#x: slot_offset == -1\n", + get_file_name(entry), RELOC_ADDRESS(rp)); + + if (lsp->flags & LS_GOTSLOTCLAIMED) + /* Already done */ + return lsp->gotslot_offset; + + *(long *)((long)rrs_got + lsp->gotslot_offset) = addend; + + if (!(link_mode & SHAREABLE)) + return lsp->gotslot_offset; + + /* + * Relocation entry needed for this static GOT entry. + */ + r = rrs_next_reloc(); + lsp->flags |= LS_GOTSLOTCLAIMED; + r->r_address = rrs_sdt.sdt_got + lsp->gotslot_offset; + RELOC_EXTERN_P(r) = 0; + md_make_gotreloc(rp, r, RELTYPE_RELATIVE); + return lsp->gotslot_offset; +} + +void +claim_rrs_cpy_reloc(entry, rp, sp) +struct file_entry *entry; +struct relocation_info *rp; +symbol *sp; +{ + struct relocation_info *r; + + if (sp->flags & GS_CPYRELOCCLAIMED) + return; + + if (!(sp->flags & GS_CPYRELOCRESERVED)) + fatal("internal error: %s: claim_cpy_reloc: %s: no reservation\n", + get_file_name(entry), sp->name); + +#ifdef DEBUG +printf("claim_rrs_copy: %s: %s -> %x\n", + get_file_name(entry), sp->name, sp->so_defined); +#endif + + r = rrs_next_reloc(); + sp->flags |= GS_CPYRELOCCLAIMED; + r->r_address = rp->r_address; + RELOC_SYMBOL(r) = sp->rrs_symbolnum; + RELOC_EXTERN_P(r) = RELOC_EXTERN_P(rp); + md_make_cpyreloc(rp, r); +} + +void +claim_rrs_segment_reloc(entry, rp) +struct file_entry *entry; +struct relocation_info *rp; +{ + struct relocation_info *r = rrs_next_reloc(); + +#ifdef DEBUG +printf("claim_rrs_segment_reloc: %s at %#x\n", + get_file_name(entry), rp->r_address); +#endif + r->r_address = rp->r_address; + RELOC_TYPE(r) = RELOC_TYPE(rp); + RELOC_EXTERN_P(r) = 0; + md_make_reloc(rp, r, RELTYPE_RELATIVE); + +} + +/* + * Fill the RRS hash table for the given symbol name. + * NOTE: the hash value computation must match the one in rtld. + */ +void +rrs_insert_hash(cp, index) +char *cp; +int index; +{ + int hashval = 0; + struct rrs_hash *hp; + + for (; *cp; cp++) + hashval = (hashval << 1) + *cp; + + hashval = (hashval & 0x7fffffff) % rrs_sdt.sdt_buckets; + + /* Get to the bucket */ + hp = rrs_hashtab + hashval; + if (hp->rh_symbolnum == -1) { + /* Empty bucket, use it */ + hp->rh_symbolnum = index; + hp->rh_next = 0; + return; + } + + while (hp->rh_next != 0) + hp = rrs_hashtab + hp->rh_next; + + hp->rh_next = current_hash_index++; + hp = rrs_hashtab + hp->rh_next; + hp->rh_symbolnum = index; + hp->rh_next = 0; +} + +/* + * There are two interesting cases to consider here. + * + * 1) No shared objects were loaded, but there were PIC input rel files. + * In this case we must output a _GLOBAL_OFFSET_TABLE_ but no other + * RRS data. Also, the entries in the GOT must be fully resolved. + * + * 2) It's a genuine dynamically linked program, so the whole RRS scoop + * goes into a.out. + */ +void +consider_rrs_section_lengths() +{ + int n; + struct shobj *shp, **shpp; + int symbolsize; + +#ifdef notyet +/* We run into trouble with this as long as shared object symbols + are not checked for definitions */ + /* + * First, determine the real number of shared objects we need. + */ + for (shpp = &rrs_shobjs; *shpp; shpp = &(*shpp)->next) { + while (*shpp && !((*shpp)->entry->flags & E_SYMBOLS_USED)) { + if (--number_of_shobjs < 0) + fatal("internal error: number_of_shobjs < 0"); + *shpp = (*shpp)->next; + } + if (*shpp == NULL) + break; + } +#endif + + /* First, determine what of the RRS we want */ + if (relocatable_output) + rrs_section_type = RRS_NONE; + else if (link_mode & SHAREABLE) + rrs_section_type = RRS_FULL; + else if (number_of_shobjs == 0 /*&& !(link_mode & DYNAMIC)*/) { + /* + * First slots in both tables are reserved + * hence the "> 1" condition + */ + if (number_of_gotslots > 1 || number_of_jmpslots > 1) + rrs_section_type = RRS_PARTIAL; + else + rrs_section_type = RRS_NONE; + } else + rrs_section_type = RRS_FULL; + + if (rrs_section_type == RRS_NONE) { + got_symbol->defined = 0; + return; + } + + rrs_symbol_size = LD_VERSION_NZLIST_P(soversion) ? + sizeof(struct nzlist) : sizeof(struct nlist); + + /* + * If there is an entry point, __DYNAMIC must be referenced (usually + * from crt0), as this is the method used to determine whether the + * run-time linker must be called. + */ + if (!(link_mode & SHAREABLE) && + !(dynamic_symbol->flags & GS_REFERENCED)) + fatal("No reference to __DYNAMIC"); + + dynamic_symbol->flags |= GS_REFERENCED; + + if (number_of_gotslots > 1) + got_symbol->flags |= GS_REFERENCED; + + + /* Next, allocate relocs, got and plt */ + n = reserved_rrs_relocs * sizeof(struct relocation_info); + rrs_reloc = (struct relocation_info *)xmalloc(n); + bzero(rrs_reloc, n); + + n = number_of_gotslots * sizeof(got_t); + rrs_got = (got_t *)xmalloc(n); + bzero(rrs_got, n); + + n = number_of_jmpslots * sizeof(jmpslot_t); + rrs_plt = (jmpslot_t *)xmalloc(n); + bzero(rrs_plt, n); + + /* Initialize first jmpslot */ + md_fix_jmpslot(rrs_plt, 0, 0); + + if (rrs_section_type == RRS_PARTIAL) { + rrs_data_size = number_of_gotslots * sizeof(got_t); + rrs_data_size += number_of_jmpslots * sizeof(jmpslot_t); + return; + } + + /* + * Walk the symbol table, assign RRS symbol numbers + * Assign number 0 to __DYNAMIC (!! Sun compatibility) + */ + dynamic_symbol->rrs_symbolnum = number_of_rrs_symbols++; + FOR_EACH_SYMBOL(i ,sp) { + if (sp->flags & GS_REFERENCED) { + rrs_strtab_size += 1 + strlen(sp->name); + if (sp != dynamic_symbol) + sp->rrs_symbolnum = number_of_rrs_symbols++; + if (sp->alias) { + /* + * (sigh) Always allocate space to hold the + * indirection. At this point there's not + * enough information to decide whether it's + * actually needed or not. + */ + number_of_rrs_symbols++; + rrs_strtab_size += 1 + strlen(sp->alias->name); + } + } + } END_EACH_SYMBOL; + + /* + * Now that we know how many RRS symbols there are going to be, + * allocate and initialize the RRS symbol hash table. + */ + rrs_sdt.sdt_buckets = number_of_rrs_symbols/4; + if (rrs_sdt.sdt_buckets < 4) + rrs_sdt.sdt_buckets = 4; + + number_of_rrs_hash_entries = rrs_sdt.sdt_buckets + number_of_rrs_symbols; + rrs_hashtab = (struct rrs_hash *)xmalloc( + number_of_rrs_hash_entries * sizeof(struct rrs_hash)); + for (n = 0; n < rrs_sdt.sdt_buckets; n++) + rrs_hashtab[n].rh_symbolnum = -1; + current_hash_index = rrs_sdt.sdt_buckets; + + /* + * Get symbols into hash table now, so we can fine tune the size + * of the latter. We adjust the value of `number_of_rrs_hash_entries' + * to the number of hash link slots actually used. + */ + FOR_EACH_SYMBOL(i ,sp) { + if (sp->flags & GS_REFERENCED) + rrs_insert_hash(sp->name, sp->rrs_symbolnum); + } END_EACH_SYMBOL; + number_of_rrs_hash_entries = current_hash_index; + + /* + * Calculate RRS section sizes. + */ + rrs_data_size = sizeof(struct _dynamic); + rrs_data_size += sizeof(struct so_debug); + rrs_data_size += sizeof(struct section_dispatch_table); + rrs_data_size += number_of_gotslots * sizeof(got_t); + rrs_data_size += number_of_jmpslots * sizeof(jmpslot_t); + rrs_data_size = MALIGN(rrs_data_size); + + rrs_text_size = reserved_rrs_relocs * sizeof(struct relocation_info); + rrs_text_size += number_of_rrs_hash_entries * sizeof(struct rrs_hash); + rrs_text_size += number_of_rrs_symbols * rrs_symbol_size; + + /* Align strings size */ + rrs_strtab_size = MALIGN(rrs_strtab_size); + rrs_text_size += rrs_strtab_size; + + /* Process needed shared objects */ + for (shp = rrs_shobjs; shp; shp = shp->next) { + char *name = shp->entry->local_sym_name; + + if (*name == '-' && *(name+1) == 'l') + name += 2; + + rrs_text_size += sizeof(struct sod); + rrs_text_size += 1 + strlen(name); + } + + /* Finally, align size */ + rrs_text_size = MALIGN(rrs_text_size); +} + +void +relocate_rrs_addresses() +{ + + dynamic_symbol->value = 0; + + if (rrs_section_type == RRS_NONE) + return; + + if (rrs_section_type == RRS_PARTIAL) { + got_symbol->value = rrs_sdt.sdt_got = rrs_data_start; + rrs_sdt.sdt_plt = rrs_sdt.sdt_got + + number_of_gotslots * sizeof(got_t); + return; + } + + /* + * RRS data relocations. + */ + rrs_dyn.d_version = soversion; + rrs_dyn.d_debug = (struct so_debug *) + (rrs_data_start + sizeof(struct _dynamic)); + rrs_dyn.d_un.d_sdt = (struct section_dispatch_table *) + ((long)rrs_dyn.d_debug + sizeof(struct so_debug)); + + rrs_sdt.sdt_got = (long)rrs_dyn.d_un.d_sdt + + sizeof(struct section_dispatch_table); + rrs_sdt.sdt_plt = rrs_sdt.sdt_got + number_of_gotslots*sizeof(got_t); + + /* + * RRS text relocations. + */ + rrs_sdt.sdt_rel = rrs_text_start; + /* + * Sun BUG compatibility alert. + * Main program's RRS text values are relative to TXTADDR? WHY?? + */ +#ifdef SUN_COMPAT + if (soversion == LD_VERSION_SUN && !(link_mode & SHAREABLE)) + rrs_sdt.sdt_rel -= N_TXTADDR(outheader); +#endif + + rrs_sdt.sdt_hash = rrs_sdt.sdt_rel + + reserved_rrs_relocs * sizeof(struct relocation_info); + rrs_sdt.sdt_nzlist = rrs_sdt.sdt_hash + + number_of_rrs_hash_entries * sizeof(struct rrs_hash); + rrs_sdt.sdt_strings = rrs_sdt.sdt_nzlist + + number_of_rrs_symbols * rrs_symbol_size; + rrs_sdt.sdt_str_sz = rrs_strtab_size; + rrs_sdt.sdt_text_sz = text_size; + rrs_sdt.sdt_plt_sz = number_of_jmpslots * sizeof(jmpslot_t); + + rrs_sdt.sdt_sods = rrs_shobjs ? rrs_sdt.sdt_strings+rrs_strtab_size : 0; + rrs_sdt.sdt_filler1 = 0; + rrs_sdt.sdt_filler2 = 0; + + /* + * Assign addresses to _GLOBAL_OFFSET_TABLE_ and __DYNAMIC + * &__DYNAMIC is also in the first GOT entry. + */ + got_symbol->value = rrs_sdt.sdt_got; + + *rrs_got = dynamic_symbol->value = rrs_data_start; + +} + +void +write_rrs_data() +{ + long pos; + + if (rrs_section_type == RRS_NONE) + return; + + pos = rrs_data_start + (N_DATOFF(outheader) - DATA_START(outheader)); + if (lseek(outdesc, pos, L_SET) != pos) + fatal("write_rrs_data: cant position in output file"); + + if (rrs_section_type == RRS_PARTIAL) { + /* + * Only a GOT and PLT are needed. + */ + if (number_of_gotslots <= 1) + fatal("write_rrs_data: # gotslots <= 1"); + + md_swapout_got(rrs_got, number_of_gotslots); + mywrite(rrs_got, number_of_gotslots, + sizeof(got_t), outdesc); + + if (number_of_jmpslots <= 1) + fatal("write_rrs_data: # jmpslots <= 1"); + + md_swapout_jmpslot(rrs_plt, number_of_jmpslots); + mywrite(rrs_plt, number_of_jmpslots, + sizeof(jmpslot_t), outdesc); + return; + } + + md_swapout__dynamic(&rrs_dyn); + mywrite(&rrs_dyn, 1, sizeof(struct _dynamic), outdesc); + + md_swapout_so_debug(&rrs_so_debug); + mywrite(&rrs_so_debug, 1, sizeof(struct so_debug), outdesc); + + md_swapout_section_dispatch_table(&rrs_sdt); + mywrite(&rrs_sdt, 1, sizeof(struct section_dispatch_table), outdesc); + + md_swapout_got(rrs_got, number_of_gotslots); + mywrite(rrs_got, number_of_gotslots, sizeof(got_t), outdesc); + + md_swapout_jmpslot(rrs_plt, number_of_jmpslots); + mywrite(rrs_plt, number_of_jmpslots, sizeof(jmpslot_t), outdesc); +} + +void +write_rrs_text() +{ + long pos; + int i; + int symsize; + struct nzlist *nlp; + int offset = 0; + struct shobj *shp; + struct sod *sodp; + + if (rrs_section_type == RRS_PARTIAL) + return; + + pos = rrs_text_start + (N_TXTOFF(outheader) - TEXT_START(outheader)); + if (lseek(outdesc, pos, L_SET) != pos) + fatal("write_rrs_text: cant position in output file"); + + /* Write relocation records */ + md_swapout_reloc(rrs_reloc, reserved_rrs_relocs); + mywrite(rrs_reloc, reserved_rrs_relocs, + sizeof(struct relocation_info), outdesc); + + /* Write the RRS symbol hash tables */ + md_swapout_rrs_hash(rrs_hashtab, number_of_rrs_hash_entries); + mywrite(rrs_hashtab, number_of_rrs_hash_entries, sizeof(struct rrs_hash), outdesc); + + /* + * Determine size of an RRS symbol entry, allocate space + * to collect them in. + */ + symsize = number_of_rrs_symbols * rrs_symbol_size; + nlp = rrs_symbols = (struct nzlist *)alloca(symsize); + rrs_strtab = (char *)alloca(rrs_strtab_size); + +#define INCR_NLP(p) ((p) = (struct nzlist *)((long)(p) + rrs_symbol_size)) + + /* __DYNAMIC symbol *must* be first for Sun compatibility */ + nlp->nz_desc = nlp->nz_other = 0; + if (LD_VERSION_NZLIST_P(soversion)) + nlp->nz_size = 0; + nlp->nz_type = dynamic_symbol->defined; + nlp->nz_value = dynamic_symbol->value; + nlp->nz_value = dynamic_symbol->value; + nlp->nz_strx = offset; + strcpy(rrs_strtab + offset, dynamic_symbol->name); + offset += 1 + strlen(dynamic_symbol->name); + INCR_NLP(nlp); + + /* + * Now, for each global symbol, construct a nzlist element + * for inclusion in the RRS symbol table. + */ + FOR_EACH_SYMBOL(i, sp) { + + if (!(sp->flags & GS_REFERENCED) || sp == dynamic_symbol) + continue; + + if ((long)nlp - (long)rrs_symbols >= + number_of_rrs_symbols * rrs_symbol_size) + fatal( + "internal error: rrs symbols exceed allocation %d ", + number_of_rrs_symbols); + + nlp->nz_desc = 0; + nlp->nz_other = 0; + if (LD_VERSION_NZLIST_P(soversion)) + nlp->nz_size = 0; + + if (sp->defined > 1) { + /* defined with known type */ + if (!(link_mode & SHAREABLE) && + sp->alias && sp->alias->defined > 1) { + /* + * If the target of an indirect symbol has + * been defined and we are outputting an + * executable, resolve the indirection; it's + * no longer needed. + */ + nlp->nz_type = sp->alias->defined; + nlp->nz_value = sp->alias->value; + nlp->nz_other = N_OTHER(0, sp->alias->aux); + } else if (sp->defined == N_SIZE) { + /* + * Make sure this symbol isn't going + * to define anything. + */ + nlp->nz_type = N_UNDF; + nlp->nz_value = 0; + } else { + nlp->nz_type = sp->defined; + nlp->nz_value = sp->value; + nlp->nz_other = N_OTHER(0, sp->aux); + } + if (LD_VERSION_NZLIST_P(soversion)) + nlp->nz_size = sp->size; + } else if (sp->common_size) { + /* + * a common definition + */ + nlp->nz_type = N_UNDF | N_EXT; + nlp->nz_value = sp->common_size; + } else if (!sp->defined) { + /* undefined */ + nlp->nz_type = N_UNDF | N_EXT; + nlp->nz_value = 0; + if (sp->so_defined && sp->jmpslot_offset != -1) { + /* + * Define a "weak" function symbol. + */ + if (sp->aux != AUX_FUNC) + fatal("%s: non-function jmpslot", + sp->name); + nlp->nz_other = N_OTHER(0, sp->aux); + nlp->nz_value = + rrs_sdt.sdt_plt + sp->jmpslot_offset; + } + } else + fatal( + "internal error: %s defined in mysterious way", + sp->name); + + /* Set symbol's name */ + nlp->nz_strx = offset; + strcpy(rrs_strtab + offset, sp->name); + offset += 1 + strlen(sp->name); + + if (sp->alias) { + /* + * Write an extra symbol for indirections (possibly + * just a dummy). + */ + int t = (nlp->nz_type == N_INDR + N_EXT); + + INCR_NLP(nlp); + nlp->nz_type = N_UNDF + t?N_EXT:0; + nlp->nz_un.n_strx = offset; + nlp->nz_value = 0; + nlp->nz_other = 0; + nlp->nz_desc = 0; + nlp->nz_size = 0; + strcpy(rrs_strtab + offset, sp->alias->name); + offset += 1 + strlen(sp->alias->name); + } + + INCR_NLP(nlp); + + } END_EACH_SYMBOL; + + if (MALIGN(offset) != rrs_strtab_size) + fatal( + "internal error: inconsistent RRS string table length: %d, expected %d", + offset, rrs_strtab_size); + + /* Write the symbol table */ + if (rrs_symbol_size == sizeof(struct nlist)) + md_swapout_symbols(rrs_symbols, number_of_rrs_symbols); + else + md_swapout_zsymbols(rrs_symbols, number_of_rrs_symbols); + mywrite(rrs_symbols, symsize, 1, outdesc); + + /* Write the strings */ + mywrite(rrs_strtab, rrs_strtab_size, 1, outdesc); + + /* + * Write the names of the shared objects needed at run-time + */ + pos = rrs_sdt.sdt_sods + number_of_shobjs * sizeof(struct sod); + sodp = (struct sod *)alloca( number_of_shobjs * sizeof(struct sod)); + + for (i = 0, shp = rrs_shobjs; shp; i++, shp = shp->next) { + char *name = shp->entry->local_sym_name; + + if (i >= number_of_shobjs) + fatal("internal error: # of link objects exceeds %d", + number_of_shobjs); + + sodp[i].sod_name = pos; + sodp[i].sod_major = shp->entry->lib_major; + sodp[i].sod_minor = shp->entry->lib_minor; + + if (*name == '-' && *(name+1) == 'l') { + name += 2; + sodp[i].sod_library = 1; + } else + sodp[i].sod_library = 0; + + pos += 1 + strlen(name); + sodp[i].sod_next = (i == number_of_shobjs - 1) ? 0 : + (rrs_sdt.sdt_sods + (i+1)*sizeof(struct sod)); + } + + if (i < number_of_shobjs) + fatal("internal error: # of link objects less then expected %d", + number_of_shobjs); + + md_swapout_sod(sodp, number_of_shobjs); + mywrite(sodp, number_of_shobjs, sizeof(struct sod), outdesc); + + for (i = 0, shp = rrs_shobjs; shp; i++, shp = shp->next) { + char *name = shp->entry->local_sym_name; + + if (*name == '-' && *(name+1) == 'l') { + name += 2; + } + + mywrite(name, strlen(name) + 1, 1, outdesc); + } +} + +void +write_rrs() +{ + + /* + * First, do some consistency checks on the RRS segment. + */ + if (rrs_section_type == RRS_NONE) { + if (reserved_rrs_relocs > 1) + fatal( + "internal error: RRS relocs in static program: %d", + reserved_rrs_relocs-1); + return; + } + +#ifdef DEBUG +printf("rrs_relocs %d, gotslots %d, jmpslots %d\n", + reserved_rrs_relocs, number_of_gotslots-1, number_of_jmpslots-1); +#endif + + if (claimed_rrs_relocs != reserved_rrs_relocs) { +/* + fatal("internal error: reserved relocs(%d) != claimed(%d)", + reserved_rrs_relocs, claimed_rrs_relocs); +*/ + printf("FIX:internal error: reserved relocs(%d) != claimed(%d)\n", + reserved_rrs_relocs, claimed_rrs_relocs); + } + + /* Write the RRS segments. */ + write_rrs_text (); + write_rrs_data (); +} diff --git a/gnu/usr.bin/ld/rtld/Makefile b/gnu/usr.bin/ld/rtld/Makefile new file mode 100644 index 000000000000..02a4437c2645 --- /dev/null +++ b/gnu/usr.bin/ld/rtld/Makefile @@ -0,0 +1,25 @@ +# $Id: Makefile,v 1.9 1994/02/13 20:42:48 jkh Exp $ + +PROG= ld.so +SRCS= mdprologue.S rtld.c malloc.c shlib.c etc.c md.c +NOMAN= noman +LDDIR?= $(.CURDIR)/.. +#PICFLAG=-pic +PICFLAG=-fpic +CFLAGS+=-I$(LDDIR) -I$(.CURDIR) -I$(LDDIR)/$(MACHINE) $(PICFLAG) -DRTLD +LDFLAGS+=-Bshareable -Bsymbolic -assert nosymbolic +ASFLAGS+=-k +LDADD+= -lc_pic +BINDIR= /usr/libexec + +.SUFFIXES: .S + +.PATH: $(LDDIR) $(LDDIR)/$(MACHINE) + +$(PROG): + $(LD) -o $(PROG) $(LDFLAGS) $(OBJS) $(LDADD) + +.S.o: + ${CPP} ${.IMPSRC} | ${AS} ${ASFLAGS} -o ${.TARGET} - + +.include <bsd.prog.mk> diff --git a/gnu/usr.bin/ld/rtld/malloc.c b/gnu/usr.bin/ld/rtld/malloc.c new file mode 100644 index 000000000000..4a9e7e65e9b3 --- /dev/null +++ b/gnu/usr.bin/ld/rtld/malloc.c @@ -0,0 +1,481 @@ +/* + * Copyright (c) 1983 Regents of the University of California. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +/*static char *sccsid = "from: @(#)malloc.c 5.11 (Berkeley) 2/23/91";*/ +static char *rcsid = "$Id: malloc.c,v 1.1 1994/02/13 20:44:09 jkh Exp $"; +#endif /* LIBC_SCCS and not lint */ + +/* + * malloc.c (Caltech) 2/21/82 + * Chris Kingsley, kingsley@cit-20. + * + * This is a very fast storage allocator. It allocates blocks of a small + * number of different sizes, and keeps free lists of each size. Blocks that + * don't exactly fit are passed up to the next larger size. In this + * implementation, the available sizes are 2^n-4 (or 2^n-10) bytes long. + * This is designed for use in a virtual memory environment. + */ + +#include <sys/types.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> +#include <sys/param.h> +#include <sys/mman.h> +#ifndef BSD +#define MAP_COPY MAP_PRIVATE +#define MAP_FILE 0 +#define MAP_ANON 0 +#endif + +#ifndef BSD /* Need do better than this */ +#define NEED_DEV_ZERO 1 +#endif + +#define NULL 0 + +static void morecore(); +static int findbucket(); + +/* + * Pre-allocate mmap'ed pages + */ +#define getpagesize() NBPG +#define NPOOLPAGES (32*1024/NBPG) +static caddr_t pagepool_start, pagepool_end; +static int morepages(); + +/* + * The overhead on a block is at least 4 bytes. When free, this space + * contains a pointer to the next free block, and the bottom two bits must + * be zero. When in use, the first byte is set to MAGIC, and the second + * byte is the size index. The remaining bytes are for alignment. + * If range checking is enabled then a second word holds the size of the + * requested block, less 1, rounded up to a multiple of sizeof(RMAGIC). + * The order of elements is critical: ov_magic must overlay the low order + * bits of ov_next, and ov_magic can not be a valid ov_next bit pattern. + */ +union overhead { + union overhead *ov_next; /* when free */ + struct { + u_char ovu_magic; /* magic number */ + u_char ovu_index; /* bucket # */ +#ifdef RCHECK + u_short ovu_rmagic; /* range magic number */ + u_int ovu_size; /* actual block size */ +#endif + } ovu; +#define ov_magic ovu.ovu_magic +#define ov_index ovu.ovu_index +#define ov_rmagic ovu.ovu_rmagic +#define ov_size ovu.ovu_size +}; + +#define MAGIC 0xef /* magic # on accounting info */ +#define RMAGIC 0x5555 /* magic # on range info */ + +#ifdef RCHECK +#define RSLOP sizeof (u_short) +#else +#define RSLOP 0 +#endif + +/* + * nextf[i] is the pointer to the next free block of size 2^(i+3). The + * smallest allocatable block is 8 bytes. The overhead information + * precedes the data area returned to the user. + */ +#define NBUCKETS 30 +static union overhead *nextf[NBUCKETS]; +extern char *sbrk(); + +static int pagesz; /* page size */ +static int pagebucket; /* page size bucket */ + +#ifdef MSTATS +/* + * nmalloc[i] is the difference between the number of mallocs and frees + * for a given block size. + */ +static u_int nmalloc[NBUCKETS]; +#include <stdio.h> +#endif + +#if defined(DEBUG) || defined(RCHECK) +#define ASSERT(p) if (!(p)) botch("p") +#include <stdio.h> +static +botch(s) + char *s; +{ + fprintf(stderr, "\r\nassertion botched: %s\r\n", s); + (void) fflush(stderr); /* just in case user buffered it */ + abort(); +} +#else +#define ASSERT(p) +#endif + +void * +malloc(nbytes) + size_t nbytes; +{ + register union overhead *op; + register int bucket, n; + register unsigned amt; + + /* + * First time malloc is called, setup page size and + * align break pointer so all data will be page aligned. + */ + if (pagesz == 0) { + pagesz = n = getpagesize(); + if (morepages(NPOOLPAGES) == 0) + return NULL; + op = (union overhead *)(pagepool_start); + n = n - sizeof (*op) - ((int)op & (n - 1)); + if (n < 0) + n += pagesz; + if (n) { + pagepool_start += n; + } + bucket = 0; + amt = 8; + while (pagesz > amt) { + amt <<= 1; + bucket++; + } + pagebucket = bucket; + } + /* + * Convert amount of memory requested into closest block size + * stored in hash buckets which satisfies request. + * Account for space used per block for accounting. + */ + if (nbytes <= (n = pagesz - sizeof (*op) - RSLOP)) { +#ifndef RCHECK + amt = 8; /* size of first bucket */ + bucket = 0; +#else + amt = 16; /* size of first bucket */ + bucket = 1; +#endif + n = -(sizeof (*op) + RSLOP); + } else { + amt = pagesz; + bucket = pagebucket; + } + while (nbytes > amt + n) { + amt <<= 1; + if (amt == 0) + return (NULL); + bucket++; + } + /* + * If nothing in hash bucket right now, + * request more memory from the system. + */ + if ((op = nextf[bucket]) == NULL) { + morecore(bucket); + if ((op = nextf[bucket]) == NULL) + return (NULL); + } + /* remove from linked list */ + nextf[bucket] = op->ov_next; + op->ov_magic = MAGIC; + op->ov_index = bucket; +#ifdef MSTATS + nmalloc[bucket]++; +#endif +#ifdef RCHECK + /* + * Record allocated size of block and + * bound space with magic numbers. + */ + op->ov_size = (nbytes + RSLOP - 1) & ~(RSLOP - 1); + op->ov_rmagic = RMAGIC; + *(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC; +#endif + return ((char *)(op + 1)); +} + +/* + * Allocate more memory to the indicated bucket. + */ +static void +morecore(bucket) + int bucket; +{ + register union overhead *op; + register int sz; /* size of desired block */ + int amt; /* amount to allocate */ + int nblks; /* how many blocks we get */ + + /* + * sbrk_size <= 0 only for big, FLUFFY, requests (about + * 2^30 bytes on a VAX, I think) or for a negative arg. + */ + sz = 1 << (bucket + 3); +#ifdef DEBUG + ASSERT(sz > 0); +#else + if (sz <= 0) + return; +#endif + if (sz < pagesz) { + amt = pagesz; + nblks = amt / sz; + } else { + amt = sz + pagesz; + nblks = 1; + } + if (amt > pagepool_end - pagepool_start) + if (morepages(amt/pagesz + NPOOLPAGES) == 0) + return; + op = (union overhead *)pagepool_start; + pagepool_start += amt; + + /* + * Add new memory allocated to that on + * free list for this hash bucket. + */ + nextf[bucket] = op; + while (--nblks > 0) { + op->ov_next = (union overhead *)((caddr_t)op + sz); + op = (union overhead *)((caddr_t)op + sz); + } +} + +void +free(cp) + void *cp; +{ + register int size; + register union overhead *op; + + if (cp == NULL) + return; + op = (union overhead *)((caddr_t)cp - sizeof (union overhead)); +#ifdef DEBUG + ASSERT(op->ov_magic == MAGIC); /* make sure it was in use */ +#else + if (op->ov_magic != MAGIC) + return; /* sanity */ +#endif +#ifdef RCHECK + ASSERT(op->ov_rmagic == RMAGIC); + ASSERT(*(u_short *)((caddr_t)(op + 1) + op->ov_size) == RMAGIC); +#endif + size = op->ov_index; + ASSERT(size < NBUCKETS); + op->ov_next = nextf[size]; /* also clobbers ov_magic */ + nextf[size] = op; +#ifdef MSTATS + nmalloc[size]--; +#endif +} + +/* + * When a program attempts "storage compaction" as mentioned in the + * old malloc man page, it realloc's an already freed block. Usually + * this is the last block it freed; occasionally it might be farther + * back. We have to search all the free lists for the block in order + * to determine its bucket: 1st we make one pass thru the lists + * checking only the first block in each; if that fails we search + * ``realloc_srchlen'' blocks in each list for a match (the variable + * is extern so the caller can modify it). If that fails we just copy + * however many bytes was given to realloc() and hope it's not huge. + */ +int realloc_srchlen = 4; /* 4 should be plenty, -1 =>'s whole list */ + +void * +realloc(cp, nbytes) + void *cp; + size_t nbytes; +{ + register u_int onb; + register int i; + union overhead *op; + char *res; + int was_alloced = 0; + + if (cp == NULL) + return (malloc(nbytes)); + op = (union overhead *)((caddr_t)cp - sizeof (union overhead)); + if (op->ov_magic == MAGIC) { + was_alloced++; + i = op->ov_index; + } else { + /* + * Already free, doing "compaction". + * + * Search for the old block of memory on the + * free list. First, check the most common + * case (last element free'd), then (this failing) + * the last ``realloc_srchlen'' items free'd. + * If all lookups fail, then assume the size of + * the memory block being realloc'd is the + * largest possible (so that all "nbytes" of new + * memory are copied into). Note that this could cause + * a memory fault if the old area was tiny, and the moon + * is gibbous. However, that is very unlikely. + */ + if ((i = findbucket(op, 1)) < 0 && + (i = findbucket(op, realloc_srchlen)) < 0) + i = NBUCKETS; + } + onb = 1 << (i + 3); + if (onb < pagesz) + onb -= sizeof (*op) + RSLOP; + else + onb += pagesz - sizeof (*op) - RSLOP; + /* avoid the copy if same size block */ + if (was_alloced) { + if (i) { + i = 1 << (i + 2); + if (i < pagesz) + i -= sizeof (*op) + RSLOP; + else + i += pagesz - sizeof (*op) - RSLOP; + } + if (nbytes <= onb && nbytes > i) { +#ifdef RCHECK + op->ov_size = (nbytes + RSLOP - 1) & ~(RSLOP - 1); + *(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC; +#endif + return(cp); + } else + free(cp); + } + if ((res = malloc(nbytes)) == NULL) + return (NULL); + if (cp != res) /* common optimization if "compacting" */ + bcopy(cp, res, (nbytes < onb) ? nbytes : onb); + return (res); +} + +/* + * Search ``srchlen'' elements of each free list for a block whose + * header starts at ``freep''. If srchlen is -1 search the whole list. + * Return bucket number, or -1 if not found. + */ +static +findbucket(freep, srchlen) + union overhead *freep; + int srchlen; +{ + register union overhead *p; + register int i, j; + + for (i = 0; i < NBUCKETS; i++) { + j = 0; + for (p = nextf[i]; p && j != srchlen; p = p->ov_next) { + if (p == freep) + return (i); + j++; + } + } + return (-1); +} + +#ifdef MSTATS +/* + * mstats - print out statistics about malloc + * + * Prints two lines of numbers, one showing the length of the free list + * for each size category, the second showing the number of mallocs - + * frees for each size category. + */ +mstats(s) + char *s; +{ + register int i, j; + register union overhead *p; + int totfree = 0, + totused = 0; + + fprintf(stderr, "Memory allocation statistics %s\nfree:\t", s); + for (i = 0; i < NBUCKETS; i++) { + for (j = 0, p = nextf[i]; p; p = p->ov_next, j++) + ; + fprintf(stderr, " %d", j); + totfree += j * (1 << (i + 3)); + } + fprintf(stderr, "\nused:\t"); + for (i = 0; i < NBUCKETS; i++) { + fprintf(stderr, " %d", nmalloc[i]); + totused += nmalloc[i] * (1 << (i + 3)); + } + fprintf(stderr, "\n\tTotal in use: %d, total free: %d\n", + totused, totfree); +} +#endif + + +static int +morepages(n) +int n; +{ + int fd = -1; + int offset; + +#ifdef NEED_DEV_ZERO + fd = open("/dev/zero", O_RDWR, 0); + if (fd == -1) + perror("/dev/zero"); +#endif + + if (pagepool_end - pagepool_start > pagesz) { + caddr_t addr = (caddr_t) + (((int)pagepool_start + pagesz - 1) & ~(pagesz - 1)); + if (munmap(addr, pagepool_end - addr) != 0) + perror("munmap"); + } + + offset = (int)pagepool_start - ((int)pagepool_start & ~(pagesz - 1)); + + if ((pagepool_start = mmap(0, n * pagesz, + PROT_READ|PROT_WRITE, + MAP_ANON|MAP_COPY, fd, 0)) == (caddr_t)-1) { + xprintf("Cannot map anonymous memory"); + return 0; + } + pagepool_end = pagepool_start + n * pagesz; + pagepool_start += offset; + +#ifdef NEED_DEV_ZERO + close(fd); +#endif + return n; +} diff --git a/gnu/usr.bin/ld/rtld/md-prologue.c b/gnu/usr.bin/ld/rtld/md-prologue.c new file mode 100644 index 000000000000..dae455e02375 --- /dev/null +++ b/gnu/usr.bin/ld/rtld/md-prologue.c @@ -0,0 +1,39 @@ +/* + * rtld entry pseudo code - turn into assembler and tweak it + */ + +#include <sys/types.h> +#include <sys/types.h> +#include <a.out.h> +#include "link.h" +#include "md.h" + +extern long _GOT_[]; +extern void (*rtld)(); +extern void (*binder())(); + +void +rtld_entry(version, crtp) +int version; +struct crt *crtp; +{ + register struct link_dynamic *dp; + register void (*f)(); + + /* __DYNAMIC is first entry in GOT */ + dp = (struct link_dynamic *) (_GOT_[0]+crtp->crt_ba); + + f = (void (*)())((long)rtld + crtp->crt_ba); + (*f)(version, crtp, dp); +} + +void +binder_entry() +{ + extern int PC; + struct jmpslot *sp; + void (*func)(); + + func = binder(PC, sp->reloc_index & 0x003fffff); + (*func)(); +} diff --git a/gnu/usr.bin/ld/rtld/rtld.c b/gnu/usr.bin/ld/rtld/rtld.c new file mode 100644 index 000000000000..8ed0f0683ce3 --- /dev/null +++ b/gnu/usr.bin/ld/rtld/rtld.c @@ -0,0 +1,1237 @@ +/* + * Copyright (c) 1993 Paul Kranenburg + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Paul Kranenburg. + * 4. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * $Id: rtld.c,v 1.15 1994/02/13 20:42:53 jkh Exp $ + */ + +#include <machine/vmparam.h> +#include <sys/param.h> +#include <stdio.h> +#include <stdlib.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <sys/file.h> +#include <sys/time.h> +#include <sys/resource.h> +#include <sys/errno.h> +#include <sys/mman.h> +#ifndef BSD +#define MAP_COPY MAP_PRIVATE +#define MAP_FILE 0 +#define MAP_ANON 0 +#endif +#include <fcntl.h> +#include <a.out.h> +#include <stab.h> +#include <string.h> +#if __STDC__ +#include <stdarg.h> +#else +#include <varargs.h> +#endif + +#include "ld.h" + +#ifndef BSD /* Need do better than this */ +#define NEED_DEV_ZERO 1 +#endif + +/* + * Loader private data, hung off <so_map>->som_spd + */ +struct somap_private { + int spd_version; + struct so_map *spd_parent; + int spd_refcount; + int spd_flags; +#define RTLD_MAIN 1 +#define RTLD_RTLD 2 +#define RTLD_DL 4 + +#ifdef SUN_COMPAT + long spd_offset; /* Correction for Sun main programs */ +#endif +}; + +#define LM_PRIVATE(smp) ((struct somap_private *)(smp)->som_spd) + +#ifdef SUN_COMPAT +#define LM_OFFSET(smp) (LM_PRIVATE(smp)->spd_offset) +#else +#define LM_OFFSET(smp) (0) +#endif + +/* Base address for section_dispatch_table entries */ +#define LM_LDBASE(smp) (smp->som_addr + LM_OFFSET(smp)) + +/* Start of text segment */ +#define LM_TXTADDR(smp) (smp->som_addr == (caddr_t)0 ? PAGSIZ : 0) + +/* Start of run-time relocation_info */ +#define LM_REL(smp) ((struct relocation_info *) \ + (smp->som_addr + LM_OFFSET(smp) + LD_REL((smp)->som_dynamic))) + +/* Start of symbols */ +#define LM_SYMBOL(smp, i) ((struct nzlist *) \ + (smp->som_addr + LM_OFFSET(smp) + LD_SYMBOL((smp)->som_dynamic) + \ + i * (LD_VERSION_NZLIST_P(smp->som_dynamic->d_version) ? \ + sizeof(struct nzlist) : sizeof(struct nlist)))) + +/* Start of hash table */ +#define LM_HASH(smp) ((struct rrs_hash *) \ + ((smp)->som_addr + LM_OFFSET(smp) + LD_HASH((smp)->som_dynamic))) + +/* Start of strings */ +#define LM_STRINGS(smp) ((char *) \ + ((smp)->som_addr + LM_OFFSET(smp) + LD_STRINGS((smp)->som_dynamic))) + +/* End of text */ +#define LM_ETEXT(smp) ((char *) \ + ((smp)->som_addr + LM_TXTADDR(smp) + LD_TEXTSZ((smp)->som_dynamic))) + +/* PLT is in data segment, so don't use LM_OFFSET here */ +#define LM_PLT(smp) ((jmpslot_t *) \ + ((smp)->som_addr + LD_PLT((smp)->som_dynamic))) + +/* Parent of link map */ +#define LM_PARENT(smp) (LM_PRIVATE(smp)->spd_parent) + +char **environ; +int errno; +static uid_t uid, euid; +static gid_t gid, egid; +static int careful; +static char *main_progname = "main"; + +struct so_map *link_map_head, *main_map; +struct so_map **link_map_tail = &link_map_head; +struct rt_symbol *rt_symbol_head; + +static void *dlopen __P((char *, int)); +static int dlclose __P((void *)); +static void *dlsym __P((void *, char *)); +static int dlctl __P((void *, int, void *)); + +static struct ld_entry ld_entry = { + dlopen, dlclose, dlsym, dlctl +}; + + void xprintf __P((char *, ...)); +static void init_brk __P((void)); +static void load_objects __P(( struct crt_ldso *, + struct _dynamic *)); +static struct so_map *map_object __P((struct sod *, struct so_map *)); +static struct so_map *alloc_link_map __P(( char *, struct sod *, + struct so_map *, caddr_t, + struct _dynamic *)); +static void inline check_text_reloc __P(( struct relocation_info *, + struct so_map *, + caddr_t)); +static void reloc_map __P((struct so_map *)); +static void reloc_copy __P((struct so_map *)); +static void init_map __P((struct so_map *, char *)); +static char *rtfindlib __P((char *, int, int, int *)); +void binder_entry __P((void)); +long binder __P((jmpslot_t *)); +static struct nzlist *lookup __P((char *, struct so_map **, int)); +static inline struct rt_symbol *lookup_rts __P((char *)); +static struct rt_symbol *enter_rts __P((char *, long, int, caddr_t, + long, struct so_map *)); + +static inline int +strcmp (register const char *s1, register const char *s2) +{ + while (*s1 == *s2++) + if (*s1++ == 0) + return (0); + return (*(unsigned char *)s1 - *(unsigned char *)--s2); +} + +#include "md-static-funcs.c" + +/* + * Called from assembler stub that has set up crtp (passed from crt0) + * and dp (our __DYNAMIC). + */ +int +rtld(version, crtp, dp) +int version; +struct crt_ldso *crtp; +struct _dynamic *dp; +{ + int n; + int nreloc; /* # of ld.so relocations */ + struct relocation_info *reloc; + char **envp; + struct so_debug *ddp; + struct so_map *smp; + + /* Check version */ + if ( version != CRT_VERSION_BSD_2 && + version != CRT_VERSION_BSD_3 && + version != CRT_VERSION_SUN) + return -1; + + /* Fixup __DYNAMIC structure */ + (long)dp->d_un.d_sdt += crtp->crt_ba; + + /* Divide by hand to avoid possible use of library division routine */ + for ( nreloc = 0, n = LD_RELSZ(dp); + n > 0; + n -= sizeof(struct relocation_info) ) nreloc++; + + + /* Relocate ourselves */ + for ( reloc = (struct relocation_info *)(LD_REL(dp) + crtp->crt_ba); + nreloc; + nreloc--, reloc++) { + + register long addr = reloc->r_address + crtp->crt_ba; + + md_relocate_simple(reloc, crtp->crt_ba, addr); + } + + progname = "ld.so"; + if (version >= CRT_VERSION_BSD_3) + main_progname = crtp->crt_prog; + + /* Setup out (private) environ variable */ + environ = crtp->crt_ep; + + /* Get user and group identifiers */ + uid = getuid(); euid = geteuid(); + gid = getgid(); egid = getegid(); + + careful = (uid != euid) || (gid != egid); + + if (careful) { + unsetenv("LD_LIBRARY_PATH"); + unsetenv("LD_PRELOAD"); + unsetenv("LD_RUN_PATH"); /* In case we ever implement this */ + } + + /* Setup directory search */ + std_search_dirs(getenv("LD_LIBRARY_PATH")); + + /* Load required objects into the process address space */ + load_objects(crtp, dp); + + /* Relocate all loaded objects according to their RRS segments */ + for (smp = link_map_head; smp; smp = smp->som_next) { + if (LM_PRIVATE(smp)->spd_flags & RTLD_RTLD) + continue; + reloc_map(smp); + } + + /* Copy any relocated initialized data. */ + for (smp = link_map_head; smp; smp = smp->som_next) { + if (LM_PRIVATE(smp)->spd_flags & RTLD_RTLD) + continue; + reloc_copy(smp); + } + + /* Call any object initialization routines. */ + for (smp = link_map_head; smp; smp = smp->som_next) { + if (LM_PRIVATE(smp)->spd_flags & RTLD_RTLD) + continue; + init_map(smp, ".init"); + } + + /* Fill in some field in main's __DYNAMIC structure */ + crtp->crt_dp->d_entry = &ld_entry; + crtp->crt_dp->d_un.d_sdt->sdt_loaded = link_map_head->som_next; + + ddp = crtp->crt_dp->d_debug; + ddp->dd_cc = rt_symbol_head; + if (ddp->dd_in_debugger) { + caddr_t addr = (caddr_t)((long)crtp->crt_bp & (~(PAGSIZ - 1))); + + /* Set breakpoint for the benefit of debuggers */ + if (mprotect(addr, PAGSIZ, + PROT_READ|PROT_WRITE|PROT_EXEC) == -1) { + perror("mprotect"), + fatal("Cannot set breakpoint (%s)\n", main_progname); + } + md_set_breakpoint(crtp->crt_bp, &ddp->dd_bpt_shadow); + if (mprotect(addr, PAGSIZ, PROT_READ|PROT_EXEC) == -1) { + perror("mprotect"); + } + + ddp->dd_bpt_addr = crtp->crt_bp; + if (link_map_head) + ddp->dd_sym_loaded = 1; + } + + /* Close our file descriptor */ + (void)close(crtp->crt_ldfd); + return 0; +} + + +static void +load_objects(crtp, dp) +struct crt_ldso *crtp; +struct _dynamic *dp; +{ + struct so_map *smp; + int tracing = (int)getenv("LD_TRACE_LOADED_OBJECTS"); + + /* Handle LD_PRELOAD's here */ + + /* Make an entry for the main program */ + smp = alloc_link_map(main_progname, (struct sod *)0, (struct so_map *)0, + (caddr_t)0, crtp->crt_dp); + LM_PRIVATE(smp)->spd_refcount++; + LM_PRIVATE(smp)->spd_flags |= RTLD_MAIN; + + /* Make an entry for ourselves */ + smp = alloc_link_map("/usr/libexec/ld.so", (struct sod *)0, (struct so_map *)0, + (caddr_t)crtp->crt_ba, dp); + LM_PRIVATE(smp)->spd_refcount++; + LM_PRIVATE(smp)->spd_flags |= RTLD_RTLD; + + for (smp = link_map_head; smp; smp = smp->som_next) { + struct sod *sodp; + long next = 0; + + if (LM_PRIVATE(smp)->spd_flags & RTLD_RTLD) + continue; + + if (smp->som_dynamic) + next = LD_NEED(smp->som_dynamic); + + while (next) { + struct so_map *newmap; + + sodp = (struct sod *)(LM_LDBASE(smp) + next); + if ((newmap = map_object(sodp, smp)) == NULL) { + if (!tracing) { + char *name = (char *) + (sodp->sod_name + LM_LDBASE(smp)); + char *fmt = sodp->sod_library ? + "%s: lib%s.so.%d.%d: %s\n" : + "%s: %s: %s\n"; + fatal(fmt, main_progname, name, + sodp->sod_major, + sodp->sod_minor, + strerror(errno)); + } + newmap = alloc_link_map(NULL, sodp, smp, 0, 0); + } + LM_PRIVATE(newmap)->spd_refcount++; + next = sodp->sod_next; + } + } + + if (! tracing) + return; + + for (smp = link_map_head; smp; smp = smp->som_next) { + struct sod *sodp; + char *name, *path; + + if ((sodp = smp->som_sod) == NULL) + continue; + name = sodp->sod_name + LM_LDBASE(LM_PARENT(smp)); + + if ((path = smp->som_path) == NULL) + path = "not found"; + + if (sodp->sod_library) + printf("\t-l%s.%d => %s (%#x)\n", name, + sodp->sod_major, path, smp->som_addr); + else + printf("\t%s => %s (%#x)\n", name, path, smp->som_addr); + } + + exit(0); +} + +/* + * Allocate a new link map for an shared object NAME loaded at ADDR as a + * result of the presence of link object LOP in the link map PARENT. + */ + static struct so_map * +alloc_link_map(path, sodp, parent, addr, dp) + char *path; + struct sod *sodp; + struct so_map *parent; + caddr_t addr; + struct _dynamic *dp; +{ + struct so_map *smp; + struct somap_private *smpp; + + smpp = (struct somap_private *)xmalloc(sizeof(struct somap_private)); + smp = (struct so_map *)xmalloc(sizeof(struct so_map)); + smp->som_next = NULL; + *link_map_tail = smp; + link_map_tail = &smp->som_next; + + smp->som_addr = addr; + smp->som_path = path; + smp->som_sod = sodp; + smp->som_dynamic = dp; + smp->som_spd = (caddr_t)smpp; + +/*XXX*/ if (addr == 0) main_map = smp; + + smpp->spd_refcount = 0; + smpp->spd_flags = 0; + smpp->spd_parent = parent; + +#ifdef SUN_COMPAT + smpp->spd_offset = + (addr==0 && dp && dp->d_version==LD_VERSION_SUN) ? PAGSIZ : 0; +#endif + return smp; +} + +/* + * Map object identified by link object LOP which was found + * in link map LMP. + */ + static struct so_map * +map_object(sodp, smp) + struct sod *sodp; + struct so_map *smp; +{ + struct _dynamic *dp; + char *path, *name = (char *)(sodp->sod_name + LM_LDBASE(smp)); + int fd; + caddr_t addr; + struct exec hdr; + int usehints = 0; + struct so_map *p; + + if (sodp->sod_library) { + usehints = 1; +again: + path = rtfindlib(name, sodp->sod_major, + sodp->sod_minor, &usehints); + if (path == NULL) { + errno = ENOENT; + return NULL; + } + } else { + if (careful && *name != '/') { + errno = EACCES; + return NULL; + } + path = name; + } + + /* Check if already loaded */ + for (p = link_map_head; p; p = p->som_next) + if (p->som_path && strcmp(p->som_path, path) == 0) + break; + + if (p != NULL) + return p; + + if ((fd = open(path, O_RDONLY, 0)) == -1) { + if (usehints) { + usehints = 0; + goto again; + } + return NULL; + } + + if (read(fd, &hdr, sizeof(hdr)) != sizeof(hdr)) { + (void)close(fd); + /*errno = x;*/ + return NULL; + } + + if (N_BADMAG(hdr)) { + (void)close(fd); + errno = EFTYPE; + return NULL; + } + + if ((addr = mmap(0, hdr.a_text + hdr.a_data, + PROT_READ|PROT_EXEC, + MAP_FILE|MAP_COPY, fd, 0)) == (caddr_t)-1) { + (void)close(fd); + return NULL; + } + + if (mmap(addr + hdr.a_text, hdr.a_data, + PROT_READ|PROT_WRITE|PROT_EXEC, + MAP_FILE|MAP_FIXED|MAP_COPY, + fd, hdr.a_text) == (caddr_t)-1) { + (void)close(fd); + return NULL; + } + + (void)close(fd); + + fd = -1; +#ifdef NEED_DEV_ZERO + if ((fd = open("/dev/zero", O_RDWR, 0)) == -1) + perror("/dev/zero"); +#endif + if (hdr.a_bss && mmap(addr + hdr.a_text + hdr.a_data, hdr.a_bss, + PROT_READ|PROT_WRITE|PROT_EXEC, + MAP_ANON|MAP_FIXED|MAP_COPY, + fd, hdr.a_text + hdr.a_data) == (caddr_t)-1) + return NULL; + +#ifdef NEED_DEV_ZERO + close(fd); +#endif + + /* Assume _DYNAMIC is the first data item */ + dp = (struct _dynamic *)(addr+hdr.a_text); + + /* Fixup __DYNAMIC structure */ + (long)dp->d_un.d_sdt += (long)addr; + + return alloc_link_map(path, sodp, smp, addr, dp); +} + +static void inline +check_text_reloc(r, smp, addr) +struct relocation_info *r; +struct so_map *smp; +caddr_t addr; +{ + char *sym; + + if (addr >= LM_ETEXT(smp)) + return; + + if (RELOC_EXTERN_P(r)) + sym = LM_STRINGS(smp) + + LM_SYMBOL(smp, RELOC_SYMBOL(r))->nz_strx; + else + sym = ""; + + if (getenv("LD_WARN_NON_PURE_CODE") != NULL) + fprintf(stderr, + "ld.so: warning: non pure code in %s at %x (%s)\n", + smp->som_path, r->r_address, sym); + + if (smp->som_write == 0 && + mprotect(smp->som_addr + LM_TXTADDR(smp), + LD_TEXTSZ(smp->som_dynamic), + PROT_READ|PROT_WRITE|PROT_EXEC) == -1) { + + perror("mprotect"), + fatal("Cannot enable writes to %s:%s\n", + main_progname, smp->som_path); + } + + smp->som_write = 1; +} + +static void +reloc_map(smp) + struct so_map *smp; +{ + struct _dynamic *dp = smp->som_dynamic; + struct relocation_info *r = LM_REL(smp); + struct relocation_info *rend = r + LD_RELSZ(dp)/sizeof(*r); + long symbolbase = (long)LM_SYMBOL(smp, 0); + char *stringbase = LM_STRINGS(smp); + int symsize = LD_VERSION_NZLIST_P(dp->d_version) ? + sizeof(struct nzlist) : + sizeof(struct nlist); + + if (LD_PLTSZ(dp)) + md_fix_jmpslot(LM_PLT(smp), + (long)LM_PLT(smp), (long)binder_entry); + + for (; r < rend; r++) { + char *sym; + caddr_t addr = smp->som_addr + r->r_address; + + check_text_reloc(r, smp, addr); + + if (RELOC_EXTERN_P(r)) { + struct so_map *src_map = NULL; + struct nzlist *p, *np; + long relocation = md_get_addend(r, addr); + + if (RELOC_LAZY_P(r)) + continue; + + p = (struct nzlist *) + (symbolbase + symsize * RELOC_SYMBOL(r)); + + if (p->nz_type == (N_SETV + N_EXT)) + src_map = smp; + + sym = stringbase + p->nz_strx; + + np = lookup(sym, &src_map, 0/*XXX-jumpslots!*/); + if (np == NULL) + fatal("Undefined symbol \"%s\" in %s:%s\n", + sym, main_progname, smp->som_path); + + /* + * Found symbol definition. + * If it's in a link map, adjust value + * according to the load address of that map. + * Otherwise it's a run-time allocated common + * whose value is already up-to-date. + */ + relocation += np->nz_value; + if (src_map) + relocation += (long)src_map->som_addr; + + if (RELOC_PCREL_P(r)) + relocation -= (long)smp->som_addr; + + if (RELOC_COPY_P(r) && src_map) { + (void)enter_rts(sym, + (long)addr, + N_DATA + N_EXT, + src_map->som_addr + np->nz_value, + np->nz_size, src_map); + continue; + } + md_relocate(r, relocation, addr, 0); + + } else { + md_relocate(r, +#ifdef SUN_COMPAT + md_get_rt_segment_addend(r, addr) +#else + md_get_addend(r, addr) +#endif + + (long)smp->som_addr, addr, 0); + } + + } + + if (smp->som_write) { + if (mprotect(smp->som_addr + LM_TXTADDR(smp), + LD_TEXTSZ(smp->som_dynamic), + PROT_READ|PROT_EXEC) == -1) { + + perror("mprotect"), + fatal("Cannot disable writes to %s:%s\n", + main_progname, smp->som_path); + } + smp->som_write = 0; + } +} + +static void +reloc_copy(smp) + struct so_map *smp; +{ + struct rt_symbol *rtsp; + + for (rtsp = rt_symbol_head; rtsp; rtsp = rtsp->rt_next) + if ((rtsp->rt_smp == NULL || rtsp->rt_smp == smp) && + rtsp->rt_sp->nz_type == N_DATA + N_EXT) { + bcopy(rtsp->rt_srcaddr, (caddr_t)rtsp->rt_sp->nz_value, + rtsp->rt_sp->nz_size); + } +} + +static void +init_map(smp, sym) + struct so_map *smp; + char *sym; +{ + struct so_map *src_map = smp; + struct nzlist *np; + + np = lookup(sym, &src_map, 1); + if (np) + (*(void (*)())(src_map->som_addr + np->nz_value))(); +} + +/* + * Run-time common symbol table. + */ + +#define RTC_TABSIZE 57 +static struct rt_symbol *rt_symtab[RTC_TABSIZE]; + +/* + * Compute hash value for run-time symbol table + */ + static int inline +hash_string(key) + char *key; +{ + register char *cp; + register int k; + + cp = key; + k = 0; + while (*cp) + k = (((k << 1) + (k >> 14)) ^ (*cp++)) & 0x3fff; + + return k; +} + +/* + * Lookup KEY in the run-time common symbol table. + */ + + static inline struct rt_symbol * +lookup_rts(key) + char *key; +{ + register int hashval; + register struct rt_symbol *rtsp; + + /* Determine which bucket. */ + + hashval = hash_string(key) % RTC_TABSIZE; + + /* Search the bucket. */ + + for (rtsp = rt_symtab[hashval]; rtsp; rtsp = rtsp->rt_link) + if (strcmp(key, rtsp->rt_sp->nz_name) == 0) + return rtsp; + + return NULL; +} + + static struct rt_symbol * +enter_rts(name, value, type, srcaddr, size, smp) + char *name; + long value; + int type; + caddr_t srcaddr; + long size; + struct so_map *smp; +{ + register int hashval; + register struct rt_symbol *rtsp, **rpp; + + /* Determine which bucket */ + hashval = hash_string(name) % RTC_TABSIZE; + + /* Find end of bucket */ + for (rpp = &rt_symtab[hashval]; *rpp; rpp = &(*rpp)->rt_link) + ; + + /* Allocate new common symbol */ + rtsp = (struct rt_symbol *)malloc(sizeof(struct rt_symbol)); + rtsp->rt_sp = (struct nzlist *)malloc(sizeof(struct nzlist)); + rtsp->rt_sp->nz_name = strdup(name); + rtsp->rt_sp->nz_value = value; + rtsp->rt_sp->nz_type = type; + rtsp->rt_sp->nz_size = size; + rtsp->rt_srcaddr = srcaddr; + rtsp->rt_smp = smp; + rtsp->rt_link = NULL; + + /* Link onto linear list as well */ + rtsp->rt_next = rt_symbol_head; + rt_symbol_head = rtsp; + + *rpp = rtsp; + + return rtsp; +} + + +/* + * Lookup NAME in the link maps. The link map producing a definition + * is returned in SRC_MAP. If SRC_MAP is not NULL on entry the search is + * confined to that map. If STRONG is set, the symbol returned must + * have a proper type (used by binder()). + */ + static struct nzlist * +lookup(name, src_map, strong) + char *name; + struct so_map **src_map; /* IN/OUT */ + int strong; +{ + long common_size = 0; + struct so_map *smp; + struct rt_symbol *rtsp; + + if ((rtsp = lookup_rts(name)) != NULL) + return rtsp->rt_sp; + + /* + * Search all maps for a definition of NAME + */ + for (smp = link_map_head; smp; smp = smp->som_next) { + int buckets = LD_BUCKETS(smp->som_dynamic); + long hashval = 0; + struct rrs_hash *hp; + char *cp; + struct nzlist *np; + + /* Some local caching */ + long symbolbase; + struct rrs_hash *hashbase; + char *stringbase; + int symsize; + + if (LM_PRIVATE(smp)->spd_flags & RTLD_RTLD) + continue; + + if (*src_map && smp != *src_map) + continue; + + /* + * Compute bucket in which the symbol might be found. + */ + for (cp = name; *cp; cp++) + hashval = (hashval << 1) + *cp; + + hashval = (hashval & 0x7fffffff) % buckets; + + hashbase = LM_HASH(smp); + hp = hashbase + hashval; + if (hp->rh_symbolnum == -1) + /* Nothing in this bucket */ + continue; + + symbolbase = (long)LM_SYMBOL(smp, 0); + stringbase = LM_STRINGS(smp); + symsize = LD_VERSION_NZLIST_P(smp->som_dynamic->d_version)? + sizeof(struct nzlist) : + sizeof(struct nlist); + while (hp) { + np = (struct nzlist *) + (symbolbase + hp->rh_symbolnum * symsize); + cp = stringbase + np->nz_strx; + if (strcmp(cp, name) == 0) + break; + if (hp->rh_next == 0) + hp = NULL; + else + hp = hashbase + hp->rh_next; + } + if (hp == NULL) + /* Nothing in this bucket */ + continue; + + /* + * We have a symbol with the name we're looking for. + */ + + if (np->nz_value == 0) + /* It's not a definition */ + continue; + + if (np->nz_type == N_UNDF+N_EXT && np->nz_value != 0) { + if (np->nz_other == AUX_FUNC) { + /* It's a weak function definition */ + if (strong) + continue; + } else { + /* It's a common, note value and continue search */ + if (common_size < np->nz_value) + common_size = np->nz_value; + continue; + } + } + + *src_map = smp; + return np; + } + + if (common_size == 0) + /* Not found */ + return NULL; + + /* + * It's a common, enter into run-time common symbol table. + */ + rtsp = enter_rts(name, (long)calloc(1, common_size), + N_UNDF + N_EXT, 0, common_size, NULL); + +#if DEBUG +xprintf("Allocating common: %s size %d at %#x\n", name, common_size, rtsp->rt_sp->nz_value); +#endif + + return rtsp->rt_sp; +} + + +/* + * This routine is called from the jumptable to resolve + * procedure calls to shared objects. + */ + long +binder(jsp) + jmpslot_t *jsp; +{ + struct so_map *smp, *src_map = NULL; + long addr; + char *sym; + struct nzlist *np; + int index; + + /* + * Find the PLT map that contains JSP. + */ + for (smp = link_map_head; smp; smp = smp->som_next) { + if (LM_PLT(smp) < jsp && + jsp < LM_PLT(smp) + LD_PLTSZ(smp->som_dynamic)/sizeof(*jsp)) + break; + } + + if (smp == NULL) + fatal("Call to binder from unknown location: %#x\n", jsp); + + index = jsp->reloc_index & JMPSLOT_RELOC_MASK; + + /* Get the local symbol this jmpslot refers to */ + sym = LM_STRINGS(smp) + + LM_SYMBOL(smp,RELOC_SYMBOL(&LM_REL(smp)[index]))->nz_strx; + + np = lookup(sym, &src_map, 1); + if (np == NULL) + fatal("Undefined symbol \"%s\" called from %s:%s at %#x", + sym, main_progname, smp->som_path, jsp); + + /* Fixup jmpslot so future calls transfer directly to target */ + addr = np->nz_value; + if (src_map) + addr += (long)src_map->som_addr; + + md_fix_jmpslot(jsp, (long)jsp, addr); + +#if DEBUG +xprintf(" BINDER: %s located at = %#x in %s\n", sym, addr, src_map->som_path); +#endif + return addr; +} + + +static struct hints_header *hheader; +static struct hints_bucket *hbuckets; +static char *hstrtab; + +#define HINTS_VALID (hheader != NULL && hheader != (struct hints_header *)-1) + + static void +maphints() +{ + caddr_t addr; + long msize; + int fd; + + if ((fd = open(_PATH_LD_HINTS, O_RDONLY, 0)) == -1) { + hheader = (struct hints_header *)-1; + return; + } + + msize = PAGSIZ; + addr = mmap(0, msize, PROT_READ, MAP_FILE|MAP_COPY, fd, 0); + + if (addr == (caddr_t)-1) { + hheader = (struct hints_header *)-1; + return; + } + + hheader = (struct hints_header *)addr; + if (HH_BADMAG(*hheader)) { + munmap(addr, msize); + hheader = (struct hints_header *)-1; + return; + } + + if (hheader->hh_version != LD_HINTS_VERSION_1) { + munmap(addr, msize); + hheader = (struct hints_header *)-1; + return; + } + + if (hheader->hh_ehints > msize) { + if (mmap(addr+msize, hheader->hh_ehints - msize, + PROT_READ, MAP_FILE|MAP_COPY|MAP_FIXED, + fd, msize) != (caddr_t)(addr+msize)) { + + munmap((caddr_t)hheader, msize); + hheader = (struct hints_header *)-1; + return; + } + } + close(fd); + + hbuckets = (struct hints_bucket *)(addr + hheader->hh_hashtab); + hstrtab = (char *)(addr + hheader->hh_strtab); +} + + int +hinthash(cp, vmajor, vminor) + char *cp; + int vmajor, vminor; +{ + int k = 0; + + while (*cp) + k = (((k << 1) + (k >> 14)) ^ (*cp++)) & 0x3fff; + + k = (((k << 1) + (k >> 14)) ^ (vmajor*257)) & 0x3fff; + k = (((k << 1) + (k >> 14)) ^ (vminor*167)) & 0x3fff; + + return k; +} + +#undef major +#undef minor + + static char * +findhint(name, major, minor, preferred_path) + char *name; + int major, minor; + char *preferred_path; +{ + struct hints_bucket *bp; + + bp = hbuckets + (hinthash(name, major, minor) % hheader->hh_nbucket); + + while (1) { + /* Sanity check */ + if (bp->hi_namex >= hheader->hh_strtab_sz) { + fprintf(stderr, "Bad name index: %#x\n", bp->hi_namex); + break; + } + if (bp->hi_pathx >= hheader->hh_strtab_sz) { + fprintf(stderr, "Bad path index: %#x\n", bp->hi_pathx); + break; + } + + if (strcmp(name, hstrtab + bp->hi_namex) == 0) { + /* It's `name', check version numbers */ + if (bp->hi_major == major && + (bp->hi_ndewey < 2 || bp->hi_minor == minor)) { + if (preferred_path == NULL || + strcmp(preferred_path, + hstrtab + bp->hi_pathx) == 0) { + return hstrtab + bp->hi_pathx; + } + } + } + + if (bp->hi_next == -1) + break; + + /* Move on to next in bucket */ + bp = &hbuckets[bp->hi_next]; + } + + /* No hints available for name */ + return NULL; +} + + static char * +rtfindlib(name, major, minor, usehints) + char *name; + int major, minor; + int *usehints; +{ + char *hint; + char *cp, *ld_path = getenv("LD_LIBRARY_PATH"); + + if (hheader == NULL) + maphints(); + + if (!HINTS_VALID || !(*usehints)) { + *usehints = 0; + return (char *)findshlib(name, &major, &minor, 0); + } + + if (ld_path != NULL) { + /* Prefer paths from LD_LIBRARY_PATH */ + while ((cp = strsep(&ld_path, ":")) != NULL) { + + hint = findhint(name, major, minor, cp); + if (ld_path) + *(ld_path-1) = ':'; + if (hint) + return hint; + } + } else { + /* No LD_LIBRARY_PATH, check default */ + hint = findhint(name, major, minor, NULL); + if (hint) + return hint; + } + + /* No hints available for name */ + *usehints = 0; + return (char *)findshlib(name, &major, &minor, 0); +} + +static struct somap_private dlmap_private = { + 0, + (struct so_map *)0, + 0, +#ifdef SUN_COMPAT + 0, +#endif +}; + +static struct so_map dlmap = { + (caddr_t)0, + "internal", + (struct so_map *)0, + (struct sod *)0, + (caddr_t)0, + (u_int)0, + (struct _dynamic *)0, + (caddr_t)&dlmap_private +}; +static int dlerrno; + + static void * +dlopen(name, mode) + char *name; + int mode; +{ + struct sod *sodp; + struct so_map *smp; + + /* + * A NULL argument returns the current set of mapped objects. + */ + if (name == NULL) + return link_map_head; + + if ((sodp = (struct sod *)malloc(sizeof(struct sod))) == NULL) { + dlerrno = ENOMEM; + return NULL; + } + + sodp->sod_name = (long)name; + sodp->sod_library = 0; + sodp->sod_major = sodp->sod_minor = 0; + + if ((smp = map_object(sodp, &dlmap)) == NULL) { +#ifdef DEBUG +xprintf("%s: %s\n", name, strerror(errno)); +#endif + dlerrno = errno; + return NULL; + } + if (LM_PRIVATE(smp)->spd_refcount++ == 0) { + LM_PRIVATE(smp)->spd_flags |= RTLD_DL; + reloc_map(smp); + reloc_copy(smp); + init_map(smp, ".init"); + init_map(smp, "_init"); + } + + return smp; +} + + static int +dlclose(fd) + void *fd; +{ + struct so_map *smp = (struct so_map *)fd; + +#ifdef DEBUG +xprintf("dlclose(%s): refcount = %d\n", smp->som_path, LM_PRIVATE(smp)->spd_refcount); +#endif + if (--LM_PRIVATE(smp)->spd_refcount != 0) + return 0; + + /* Dismantle shared object map and descriptor */ + init_map(smp, "_fini"); +#if 0 + unmap_object(smp); + free(smp->som_sod); + free(smp); +#endif + + return 0; +} + + static void * +dlsym(fd, sym) + void *fd; + char *sym; +{ + struct so_map *smp = (struct so_map *)fd, *src_map = NULL; + struct nzlist *np; + long addr; + + /* + * Restrict search to passed map if dlopen()ed. + */ + if (LM_PRIVATE(smp)->spd_flags & RTLD_DL) + src_map = smp; + + np = lookup(sym, &src_map, 1); + if (np == NULL) + return NULL; + + /* Fixup jmpslot so future calls transfer directly to target */ + addr = np->nz_value; + if (src_map) + addr += (long)src_map->som_addr; + + return (void *)addr; +} + + static int +dlctl(fd, cmd, arg) + void *fd, *arg; + int cmd; +{ + switch (cmd) { + case DL_GETERRNO: + *(int *)arg = dlerrno; + return 0; + default: + dlerrno = EOPNOTSUPP; + return -1; + } + return 0; +} + +void +#if __STDC__ +xprintf(char *fmt, ...) +#else +xprintf(fmt, va_alist) +char *fmt; +#endif +{ + char buf[256]; + va_list ap; +#if __STDC__ + va_start(ap, fmt); +#else + va_start(ap); +#endif + + vsprintf(buf, fmt, ap); + (void)write(1, buf, strlen(buf)); + va_end(ap); +} + diff --git a/gnu/usr.bin/ld/rtld/sbrk.c b/gnu/usr.bin/ld/rtld/sbrk.c new file mode 100644 index 000000000000..aee02e065e02 --- /dev/null +++ b/gnu/usr.bin/ld/rtld/sbrk.c @@ -0,0 +1,101 @@ +/* + * Copyright (c) 1993 Paul Kranenburg + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Paul Kranenburg. + * 4. The name of the author may not be used to endorse or promote products + * derived from this software withough specific prior written permission + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * $Id: sbrk.c,v 1.1 1993/12/11 21:06:36 jkh Exp $ + */ + +#include <machine/vmparam.h> +#include <sys/param.h> +#include <stdio.h> +#include <stdlib.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <sys/file.h> +#include <sys/time.h> +#include <sys/resource.h> +#include <sys/mman.h> +#ifndef BSD +#define MAP_COPY MAP_PRIVATE +#define MAP_FILE 0 +#define MAP_ANON 0 +#endif +#include <fcntl.h> +#include <a.out.h> +#include <stab.h> +#include <string.h> +#if __STDC__ +#include <stdarg.h> +#else +#include <varargs.h> +#endif + +#include "ld.h" + +#ifndef BSD /* Need do better than this */ +#define NEED_DEV_ZERO 1 +#endif + +caddr_t +sbrk(incr) +int incr; +{ + int fd = -1; + caddr_t curbrk; + + /* Round-up increment to page size */ + incr = ((incr + PAGSIZ - 1) & ~(PAGSIZ - 1)); + +#if DEBUG +xprintf("sbrk: incr = %#x\n", incr); +#endif + +#ifdef NEED_DEV_ZERO + fd = open("/dev/zero", O_RDWR, 0); + if (fd == -1) + perror("/dev/zero"); +#endif + + if ((curbrk = mmap(0, incr, + PROT_READ|PROT_WRITE, + MAP_ANON|MAP_COPY, fd, 0)) == (caddr_t)-1) { + xprintf("Cannot map anonymous memory"); + _exit(1); + } + +#ifdef DEBUG +xprintf("sbrk: curbrk = %#x\n", curbrk); +#endif + +#ifdef NEED_DEV_ZERO + close(fd); +#endif + + return(curbrk); +} + diff --git a/gnu/usr.bin/ld/shlib.c b/gnu/usr.bin/ld/shlib.c new file mode 100644 index 000000000000..a50d498dd6d5 --- /dev/null +++ b/gnu/usr.bin/ld/shlib.c @@ -0,0 +1,268 @@ +/* + * Copyright (c) 1993 Paul Kranenburg + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Paul Kranenburg. + * 4. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * $Id: shlib.c,v 1.8 1994/02/13 20:41:43 jkh Exp $ + */ + +#include <sys/param.h> +#include <stdio.h> +#include <stdlib.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <sys/file.h> +#include <sys/time.h> +#include <fcntl.h> +#include <string.h> +#include <ctype.h> +#include <dirent.h> +#include <a.out.h> + +#include "ld.h" + +#ifdef SUNOS4 +char *strsep(); +#endif + +/* + * Standard directories to search for files specified by -l. + */ +#ifndef STANDARD_SEARCH_DIRS +#define STANDARD_SEARCH_DIRS "/usr/lib", "/usr/X386/lib", "/usr/local/lib" +#endif + +/* + * Actual vector of library search directories, + * including `-L'ed and LD_LIBARAY_PATH spec'd ones. + */ +char **search_dirs; +int n_search_dirs; + +char *standard_search_dirs[] = { + STANDARD_SEARCH_DIRS +}; + + +void +add_search_dir(name) + char *name; +{ + n_search_dirs++; + search_dirs = (char **)xrealloc(search_dirs, + n_search_dirs * sizeof(char *)); + search_dirs[n_search_dirs - 1] = strdup(name); +} + +void +std_search_dirs(paths) +char *paths; +{ + char *cp; + int i, n; + + if (paths != NULL) + /* Add search directories from `paths' */ + while ((cp = strsep(&paths, ":")) != NULL) { + add_search_dir(cp); + if (paths) + *(paths-1) = ':'; + } + + /* Append standard search directories */ + n = sizeof standard_search_dirs / sizeof standard_search_dirs[0]; + for (i = 0; i < n; i++) + add_search_dir(standard_search_dirs[i]); +} + +/* + * Return true if CP points to a valid dewey number. + * Decode and leave the result in the array DEWEY. + * Return the number of decoded entries in DEWEY. + */ + +int +getdewey(dewey, cp) +int dewey[]; +char *cp; +{ + int i, n; + + for (n = 0, i = 0; i < MAXDEWEY; i++) { + if (*cp == '\0') + break; + + if (*cp == '.') cp++; + if (!isdigit(*cp)) + return 0; + + dewey[n++] = strtol(cp, &cp, 10); + } + + return n; +} + +/* + * Compare two dewey arrays. + * Return -1 if `d1' represents a smaller value than `d2'. + * Return 1 if `d1' represents a greater value than `d2'. + * Return 0 if equal. + */ +int +cmpndewey(d1, n1, d2, n2) +int d1[], d2[]; +int n1, n2; +{ + int i; + + for (i = 0; i < n1 && i < n2; i++) { + if (d1[i] < d2[i]) + return -1; + if (d1[i] > d2[i]) + return 1; + } + + if (n1 == n2) + return 0; + + if (i == n1) + return -1; + + if (i == n2) + return 1; +} + +/* + * Search directories for a shared library matching the given + * major and minor version numbers. + * + * MAJOR == -1 && MINOR == -1 --> find highest version + * MAJOR != -1 && MINOR == -1 --> find highest minor version + * MAJOR == -1 && MINOR != -1 --> invalid + * MAJOR != -1 && MINOR != -1 --> find highest micro version + */ + +/* Not interested in devices right now... */ +#undef major +#undef minor + +char * +findshlib(name, majorp, minorp, do_dot_a) +char *name; +int *majorp, *minorp; +int do_dot_a; +{ + int dewey[MAXDEWEY]; + int ndewey; + int tmp[MAXDEWEY]; + int i; + int len; + char *lname, *path = NULL; + int major = *majorp, minor = *minorp; + + len = strlen(name); + lname = (char *)alloca(len + sizeof("lib")); + sprintf(lname, "lib%s", name); + len += 3; + + ndewey = 0; + + for (i = 0; i < n_search_dirs; i++) { + DIR *dd = opendir(search_dirs[i]); + struct dirent *dp; + int found_dot_a = 0; + + if (dd == NULL) + continue; + + while ((dp = readdir(dd)) != NULL) { + int n, j, might_take_it = 0; + + if (do_dot_a && path == NULL && + dp->d_namlen == len + 2 && + strncmp(dp->d_name, lname, len) == 0 && + (dp->d_name+len)[0] == '.' && + (dp->d_name+len)[1] == 'a') { + + path = concat(search_dirs[i], "/", dp->d_name); + found_dot_a = 1; + } + + if (dp->d_namlen < len + 4) + continue; + if (strncmp(dp->d_name, lname, len) != 0) + continue; + if (strncmp(dp->d_name+len, ".so.", 4) != 0) + continue; + + if ((n = getdewey(tmp, dp->d_name+len+4)) == 0) + continue; + + if (major != -1 && found_dot_a) { /* XXX */ + free(path); + path = NULL; + found_dot_a = 0; + } + + if (major == -1 && minor == -1) { + might_take_it = 1; + } else if (major != -1 && minor == -1) { + if (tmp[0] == major) + might_take_it = 1; + } else if (major != -1 && minor != -1) { + if (tmp[0] == major) + if (n == 1 || tmp[1] >= minor) + might_take_it = 1; + } + + if (!might_take_it) + continue; + + if (cmpndewey(tmp, n, dewey, ndewey) <= 0) + continue; + + /* We have a better version */ + if (path) + free(path); + path = concat(search_dirs[i], "/", dp->d_name); + found_dot_a = 0; + bcopy(tmp, dewey, sizeof(dewey)); + ndewey = n; + *majorp = dewey[0]; + *minorp = dewey[1]; + } + closedir(dd); + + if (found_dot_a) + /* + * There's a .a archive here. + */ + return path; + } + + return path; +} diff --git a/gnu/usr.bin/ld/sparc/md-static-funcs.c b/gnu/usr.bin/ld/sparc/md-static-funcs.c new file mode 100644 index 000000000000..8446daa5256c --- /dev/null +++ b/gnu/usr.bin/ld/sparc/md-static-funcs.c @@ -0,0 +1,37 @@ + +/* + * $Id: md-static-funcs.c,v 1.2 1993/12/11 12:02:08 jkh Exp $ + * + * Simple SPARC relocations for the benefit of self-relocation of ld.so + * avoiding the use of global variables (ie. reloc_bitshift[] et. al.). + * Only types supported are RELOC_32 and RELOC_RELATIVE. + * + * This *must* be a static function, so it is not called through a jmpslot. + */ +static void +md_relocate_simple(r, relocation, addr) +struct relocation_info *r; +long relocation; +char *addr; +{ + register unsigned long mask; + register unsigned long shift; + + switch (r->r_type) { + case RELOC_32: + mask = 0xffffffff; + shift = 0; + break; + case RELOC_RELATIVE: + mask = 0x003fffff; + shift = 10; + break; + } + relocation += (*(long *)addr & mask) << shift; + relocation >>= shift; + relocation &= mask; + + *(long *) (addr) &= ~mask; + *(long *) (addr) |= relocation; +} + diff --git a/gnu/usr.bin/ld/sparc/md.c b/gnu/usr.bin/ld/sparc/md.c new file mode 100644 index 000000000000..07de1c2df109 --- /dev/null +++ b/gnu/usr.bin/ld/sparc/md.c @@ -0,0 +1,349 @@ +/* + * Copyright (c) 1993 Paul Kranenburg + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Paul Kranenburg. + * 4. The name of the author may not be used to endorse or promote products + * derived from this software withough specific prior written permission + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * $Id: md.c,v 1.7 1994/02/13 20:43:03 jkh Exp $ + */ + +#include <sys/param.h> +#include <stdio.h> +#include <stdlib.h> +#include <sys/types.h> +#include <fcntl.h> +#include <a.out.h> +#include <stab.h> +#include <string.h> + +#include "ld.h" + +/* + * Relocation masks and sizes for the Sparc architecture. + * + * Note that these are very dependent on the order of the enums in + * enum reloc_type (in a.out.h); if they change the following must be + * changed. + * Also, note that RELOC_RELATIVE is handled as if it were a RELOC_HI22. + * This should work provided that relocations values have zeroes in their + * least significant 10 bits. As RELOC_RELATIVE is used only to relocate + * with load address values - which are page aligned - this condition is + * fulfilled as long as the system's page size is > 1024 (and a power of 2). + */ +static int reloc_target_rightshift[] = { + 0, 0, 0, /* RELOC_8, _16, _32 */ + 0, 0, 0, 2, 2, /* DISP8, DISP16, DISP32, WDISP30, WDISP22 */ + 10, 0, /* HI22, _22 */ + 0, 0, /* RELOC_13, _LO10 */ + 0, 0, /* _SFA_BASE, _SFA_OFF13 */ + 0, 0, 10, /* _BASE10, _BASE13, _BASE22 */ + 0, 10, /* _PC10, _PC22 */ + 2, 0, /* _JMP_TBL, _SEGOFF16 */ + 0, 0, 0 /* _GLOB_DAT, JMP_SLOT, _RELATIVE */ +}; +static int reloc_target_size[] = { + 0, 1, 2, /* RELOC_8, _16, _32 */ + 0, 1, 2, 2, 2, /* DISP8, DISP16, DISP32, WDISP30, WDISP22 */ + 2, 2, /* HI22, _22 */ + 2, 2, /* RELOC_13, _LO10 */ + 2, 2, /* _SFA_BASE, _SFA_OFF13 */ + 2, 2, 2, /* _BASE10, _BASE13, _BASE22 */ + 2, 2, /* _PC10, _PC22 */ + 2, 0, /* _JMP_TBL, _SEGOFF16 */ + 2, 0, 2 /* _GLOB_DAT, JMP_SLOT, _RELATIVE */ +}; +static int reloc_target_bitsize[] = { + 8, 16, 32, /* RELOC_8, _16, _32 */ + 8, 16, 32, 30, 22, /* DISP8, DISP16, DISP32, WDISP30, WDISP22 */ + 22, 22, /* HI22, _22 */ + 13, 10, /* RELOC_13, _LO10 */ + 32, 32, /* _SFA_BASE, _SFA_OFF13 */ + 10, 13, 22, /* _BASE10, _BASE13, _BASE22 */ + 10, 22, /* _PC10, _PC22 */ + 30, 0, /* _JMP_TBL, _SEGOFF16 */ + 32, 0, 22 /* _GLOB_DAT, JMP_SLOT, _RELATIVE */ +}; + + +/* + * Get relocation addend corresponding to relocation record RP + * ADDR unused by SPARC impl. + */ +long +md_get_addend(r, addr) +struct relocation_info *r; +unsigned char *addr; +{ + return r->r_addend; +} + +void +md_relocate(r, relocation, addr, relocatable_output) +struct relocation_info *r; +long relocation; +unsigned char *addr; +int relocatable_output; +{ + register unsigned long mask; + +#ifndef RTLD + if (relocatable_output) { + /* + * Non-PC relative relocations which are absolute or + * which have become non-external now have fixed + * relocations. Set the ADD_EXTRA of this relocation + * to be the relocation we have now determined. + */ + if (!RELOC_PCREL_P(r)) { + if ((int) r->r_type <= RELOC_32 + || RELOC_EXTERN_P(r) == 0) + RELOC_ADD_EXTRA(r) = relocation; + } else if (RELOC_EXTERN_P(r)) + /* + * External PC-relative relocations continue + * to move around; update their relocations + * by the amount they have moved so far. + */ + RELOC_ADD_EXTRA(r) -= pc_relocation; + return; + } +#endif + + relocation >>= RELOC_VALUE_RIGHTSHIFT(r); + + /* Unshifted mask for relocation */ + mask = 1 << RELOC_TARGET_BITSIZE(r) - 1; + mask |= mask - 1; + relocation &= mask; + + /* Shift everything up to where it's going to be used */ + relocation <<= RELOC_TARGET_BITPOS(r); + mask <<= RELOC_TARGET_BITPOS(r); + + switch (RELOC_TARGET_SIZE(r)) { + case 0: + if (RELOC_MEMORY_ADD_P(r)) + relocation += (mask & *(u_char *) (addr)); + *(u_char *) (addr) &= ~mask; + *(u_char *) (addr) |= relocation; + break; + + case 1: + if (RELOC_MEMORY_ADD_P(r)) + relocation += (mask & *(u_short *) (addr)); + *(u_short *) (addr) &= ~mask; + *(u_short *) (addr) |= relocation; + break; + + case 2: + if (RELOC_MEMORY_ADD_P(r)) + relocation += (mask & *(u_long *) (addr)); + *(u_long *) (addr) &= ~mask; + *(u_long *) (addr) |= relocation; + break; + default: + fatal( "Unimplemented relocation field length in"); + } +} + +#ifndef RTLD +/* + * Machine dependent part of claim_rrs_reloc(). + * On the Sparc the relocation offsets are stored in the r_addend member. + */ +int +md_make_reloc(rp, r, type) +struct relocation_info *rp, *r; +int type; +{ + r->r_type = rp->r_type; + r->r_addend = rp->r_addend; + +#if 1 + /* + * This wouldn't be strictly necessary - we could record the + * relocation value "in situ" in stead of in the r_addend field - + * but we are being Sun compatible here. Besides, Sun's ld.so + * has a bug that prevents it from handling this alternate method. + * + * IT WOULD BE REALLY NICE TO HAVE CONSISTENCY THROUGHOUT THE ENTIRE + * RELOCATION PROCESS, ie. using `r_addend' for storing all partially + * completed relocations, in stead of mixing them in both relocation + * records and in the segment data. + */ + if (RELOC_PCREL_P(rp)) + r->r_addend -= pc_relocation; +#endif + + return 1; +} +#endif + +/* + * Set up a transfer from jmpslot at OFFSET (relative to the PLT table) + * to the binder slot (which is at offset 0 of the PLT). + */ +void +md_make_jmpslot(sp, offset, index) +jmpslot_t *sp; +long offset; +long index; +{ + u_long fudge = (u_long) -(sizeof(sp->opcode1) + offset); + sp->opcode1 = SAVE; + /* The following is a RELOC_WDISP30 relocation */ + sp->opcode2 = CALL | ((fudge >> 2) & 0x3fffffff); + sp->reloc_index = NOP | index; +} + +/* + * Set up a "direct" transfer (ie. not through the run-time binder) from + * jmpslot at OFFSET to ADDR. Used by `ld' when the SYMBOLIC flag is on, + * and by `ld.so' after resolving the symbol. + * On the i386, we use the JMP instruction which is PC relative, so no + * further RRS relocations will be necessary for such a jmpslot. + * + * OFFSET unused on Sparc. + */ +void +md_fix_jmpslot(sp, offset, addr) +jmpslot_t *sp; +long offset; +u_long addr; +{ + /* + * Here comes a RELOC_{LO10,HI22} relocation pair + * The resulting code is: + * sethi %hi(addr), %g1 + * jmp %g1+%lo(addr) + * nop ! delay slot + */ + sp->opcode1 = SETHI | ((addr >> 10) & 0x003fffff); + sp->opcode2 = JMP | (addr & 0x000003ff); + sp->reloc_index = NOP; +} + +/* + * Update the relocation record for a jmpslot. + */ +void +md_make_jmpreloc(rp, r, type) +struct relocation_info *rp, *r; +int type; +{ + if (type & RELTYPE_RELATIVE) + r->r_type = RELOC_RELATIVE; + else + r->r_type = RELOC_JMP_SLOT; + + r->r_addend = rp->r_addend; +} + +/* + * Set relocation type for a GOT RRS relocation. + */ +void +md_make_gotreloc(rp, r, type) +struct relocation_info *rp, *r; +int type; +{ + /* + * GOT value resolved (symbolic or entry point): R_32 + * GOT not resolved: GLOB_DAT + * + * NOTE: I don't think it makes a difference. + */ + if (type & RELTYPE_RELATIVE) + r->r_type = RELOC_32; + else + r->r_type = RELOC_GLOB_DAT; + + r->r_addend = 0; +} + +/* + * Set relocation type for a RRS copy operation. + */ +void +md_make_cpyreloc(rp, r) +struct relocation_info *rp, *r; +{ + r->r_type = RELOC_COPY_DAT; + r->r_addend = 0; +} + +void +md_set_breakpoint(where, savep) +long where; +long *savep; +{ + *savep = *(long *)where; + *(long *)where = TRAP; +} + +#ifndef RTLD +/* + * Initialize (output) exec header such that useful values are + * obtained from subsequent N_*() macro evaluations. + */ +void +md_init_header(hp, magic, flags) +struct exec *hp; +int magic, flags; +{ +#ifdef NetBSD + N_SETMAGIC((*hp), magic, MID_MACHINE, flags); + + /* TEXT_START depends on the value of outheader.a_entry. */ + if (!(link_mode & SHAREABLE)) /*WAS: if (entry_symbol) */ + hp->a_entry = PAGSIZ; +#else + hp->a_magic = magic; + hp->a_machtype = M_SPARC; + hp->a_toolversion = 1; + hp->a_dynamic = ((flags) & EX_DYNAMIC); + + /* SunOS 4.1 N_TXTADDR depends on the value of outheader.a_entry. */ + if (!(link_mode & SHAREABLE)) /*WAS: if (entry_symbol) */ + hp->a_entry = N_PAGSIZ(*hp); +#endif +} + +/* + * Check for acceptable foreign machine Ids + */ +int +md_midcompat(hp) +struct exec *hp; +{ +#ifdef NetBSD +#define SUN_M_SPARC 3 + return (((md_swap_long(hp->a_midmag)&0x00ff0000) >> 16) == SUN_M_SPARC); +#else + return hp->a_machtype == M_SPARC; +#endif +} +#endif /* RTLD */ diff --git a/gnu/usr.bin/ld/sparc/md.h b/gnu/usr.bin/ld/sparc/md.h new file mode 100644 index 000000000000..138b3691c28a --- /dev/null +++ b/gnu/usr.bin/ld/sparc/md.h @@ -0,0 +1,282 @@ +/* + * Copyright (c) 1993 Paul Kranenburg + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Paul Kranenburg. + * 4. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * $Id: md.h,v 1.6 1994/02/13 20:43:07 jkh Exp $ + */ + +/* + * SPARC machine dependent definitions + */ + + +#define MAX_ALIGNMENT (sizeof (double)) + +#ifdef NetBSD +#define PAGSIZ __LDPGSZ + +#define N_SET_FLAG(ex,f) N_SETMAGIC(ex,N_GETMAGIC(ex), \ + MID_MACHINE, N_GETFLAG(ex)|(f)) +#define N_IS_DYNAMIC(ex) ((N_GETFLAG(ex) & EX_DYNAMIC)) + +/* + * Should be handled by a.out.h ? + */ +#define N_ADJUST(ex) (((ex).a_entry < PAGSIZ) ? -PAGSIZ : 0) +#define TEXT_START(ex) (N_TXTADDR(ex) + N_ADJUST(ex)) +#define DATA_START(ex) (N_DATADDR(ex) + N_ADJUST(ex)) + +#else + +/* Get the SunOS a.out and relocation nomenclature */ +#define EX_DYNAMIC 1 + +#define N_IS_DYNAMIC(ex) ((ex).a_dynamic) + +#define N_SET_FLAG(ex, f) { \ + (ex).a_dynamic = ((f) & EX_DYNAMIC); \ +} + +#undef relocation_info +#define relocation_info reloc_info_sparc +#define r_symbolnum r_index +#endif /* NetBSD */ + +#define N_BADMID(ex) \ + (N_GETMID(ex) != 0 && N_GETMID(ex) != MID_MACHINE && \ + !md_midcompat(&(ex))) + +/* Sparc (Sun 4) macros */ +#define RELOC_ADDRESS(r) ((r)->r_address) +#define RELOC_EXTERN_P(r) ((r)->r_extern) +#define RELOC_TYPE(r) ((r)->r_symbolnum) +#define RELOC_SYMBOL(r) ((r)->r_symbolnum) +#define RELOC_MEMORY_SUB_P(r) 0 +#ifdef RTLD +/* XXX - consider this making SUN_COMPAT --> repercussions on rrs.c */ +#define RELOC_MEMORY_ADD_P(r) 1 +#else +#define RELOC_MEMORY_ADD_P(r) 0 +#endif +#define RELOC_ADD_EXTRA(r) ((r)->r_addend) +#define RELOC_PCREL_P(r) \ + (((r)->r_type >= RELOC_DISP8 && (r)->r_type <= RELOC_WDISP22) \ + || ((r)->r_type == RELOC_PC10 || (r)->r_type == RELOC_PC22) \ + || (r)->r_type == RELOC_JMP_TBL) +#define RELOC_VALUE_RIGHTSHIFT(r) (reloc_target_rightshift[(r)->r_type]) +#define RELOC_TARGET_SIZE(r) (reloc_target_size[(r)->r_type]) +#define RELOC_TARGET_BITPOS(r) 0 +#define RELOC_TARGET_BITSIZE(r) (reloc_target_bitsize[(r)->r_type]) + +#define RELOC_JMPTAB_P(r) ((r)->r_type == RELOC_JMP_TBL) + +#define RELOC_BASEREL_P(r) \ + ((r)->r_type >= RELOC_BASE10 && (r)->r_type <= RELOC_BASE22) + +#define RELOC_RELATIVE_P(r) ((r)->r_type == RELOC_RELATIVE) +#define RELOC_COPY_DAT (RELOC_RELATIVE+1) /*XXX*/ +#define RELOC_COPY_P(r) ((r)->r_type == RELOC_COPY_DAT) +#define RELOC_LAZY_P(r) ((r)->r_type == RELOC_JMP_SLOT) + +#define RELOC_STATICS_THROUGH_GOT_P(r) (1) +#define JMPSLOT_NEEDS_RELOC (1) + +#define CHECK_GOT_RELOC(r) \ + ((r)->r_type == RELOC_PC10 || (r)->r_type == RELOC_PC22) + +#define md_got_reloc(r) (-(r)->r_address) + +#ifdef SUN_COMPAT +/* + * Sun plays games with `r_addend' + */ +#define md_get_rt_segment_addend(r,a) (0) +#endif + +/* Width of a Global Offset Table entry */ +typedef long got_t; + +typedef struct jmpslot { + u_long opcode1; + u_long opcode2; + u_long reloc_index; +#define JMPSLOT_RELOC_MASK (0x003fffff) /* 22 bits */ +} jmpslot_t; + +#define SAVE 0x9de3bfa0 /* Build stack frame (opcode1) */ +#define SETHI 0x03000000 /* %hi(addr) -> %g1 (opcode1) */ +#define CALL 0x40000000 /* Call instruction (opcode2) */ +#define JMP 0x81c06000 /* Jump %g1 instruction (opcode2) */ +#define NOP 0x01000000 /* Delay slot NOP for (reloc_index) */ +#define TRAP 0x91d02001 /* ta 0x1 */ + + +/* + * Byte swap defs for cross linking + */ + +#if !defined(NEED_SWAP) + +#define md_swapin_exec_hdr(h) +#define md_swapout_exec_hdr(h) +#define md_swapin_symbols(s,n) +#define md_swapout_symbols(s,n) +#define md_swapin_zsymbols(s,n) +#define md_swapout_zsymbols(s,n) +#define md_swapin_reloc(r,n) +#define md_swapout_reloc(r,n) +#define md_swapin__dynamic(l) +#define md_swapout__dynamic(l) +#define md_swapin_section_dispatch_table(l) +#define md_swapout_section_dispatch_table(l) +#define md_swapin_so_debug(d) +#define md_swapout_so_debug(d) +#define md_swapin_rrs_hash(f,n) +#define md_swapout_rrs_hash(f,n) +#define md_swapin_sod(l,n) +#define md_swapout_sod(l,n) +#define md_swapout_jmpslot(j,n) +#define md_swapout_got(g,n) +#define md_swapin_ranlib_hdr(h,n) +#define md_swapout_ranlib_hdr(h,n) + +#endif /* NEED_SWAP */ + +#ifdef CROSS_LINKER + +#ifdef NEED_SWAP + +/* Define IO byte swapping routines */ + +void md_swapin_exec_hdr __P((struct exec *)); +void md_swapout_exec_hdr __P((struct exec *)); +void md_swapin_reloc __P((struct relocation_info *, int)); +void md_swapout_reloc __P((struct relocation_info *, int)); +void md_swapout_jmpslot __P((jmpslot_t *, int)); + +#define md_swapin_symbols(s,n) swap_symbols(s,n) +#define md_swapout_symbols(s,n) swap_symbols(s,n) +#define md_swapin_zsymbols(s,n) swap_zsymbols(s,n) +#define md_swapout_zsymbols(s,n) swap_zsymbols(s,n) +#define md_swapin__dynamic(l) swap__dynamic(l) +#define md_swapout__dynamic(l) swap__dynamic(l) +#define md_swapin_section_dispatch_table(l) swap_section_dispatch_table(l) +#define md_swapout_section_dispatch_table(l) swap_section_dispatch_table(l) +#define md_swapin_so_debug(d) swap_so_debug(d) +#define md_swapout_so_debug(d) swap_so_debug(d) +#define md_swapin_rrs_hash(f,n) swap_rrs_hash(f,n) +#define md_swapout_rrs_hash(f,n) swap_rrs_hash(f,n) +#define md_swapin_sod(l,n) swapin_sod(l,n) +#define md_swapout_sod(l,n) swapout_sod(l,n) +#define md_swapout_got(g,n) swap_longs((long*)(g),n) +#define md_swapin_ranlib_hdr(h,n) swap_ranlib_hdr(h,n) +#define md_swapout_ranlib_hdr(h,n) swap_ranlib_hdr(h,n) + +#define md_swap_short(x) ( (((x) >> 8) & 0xff) | (((x) & 0xff) << 8) ) + +#define md_swap_long(x) ( (((x) >> 24) & 0xff ) | (((x) >> 8 ) & 0xff00 ) | \ + (((x) << 8 ) & 0xff0000) | (((x) << 24) & 0xff000000)) + +#define get_byte(p) ( ((unsigned char *)(p))[0] ) + +#define get_short(p) ( ( ((unsigned char *)(p))[1] << 8) | \ + ( ((unsigned char *)(p))[0] ) \ + ) +#define get_long(p) ( ( ((unsigned char *)(p))[3] << 24) | \ + ( ((unsigned char *)(p))[2] << 16) | \ + ( ((unsigned char *)(p))[1] << 8 ) | \ + ( ((unsigned char *)(p))[0] ) \ + ) + +#define put_byte(p, v) { ((unsigned char *)(p))[0] = ((unsigned long)(v)); } + +#define put_short(p, v) { ((unsigned char *)(p))[1] = \ + ((((unsigned long)(v)) >> 8) & 0xff); \ + ((unsigned char *)(p))[0] = \ + ((((unsigned long)(v)) ) & 0xff); } + +#define put_long(p, v) { ((unsigned char *)(p))[3] = \ + ((((unsigned long)(v)) >> 24) & 0xff); \ + ((unsigned char *)(p))[2] = \ + ((((unsigned long)(v)) >> 16) & 0xff); \ + ((unsigned char *)(p))[1] = \ + ((((unsigned long)(v)) >> 8) & 0xff); \ + ((unsigned char *)(p))[0] = \ + ((((unsigned long)(v)) ) & 0xff); } + +#else /* We need not swap, but must pay attention to alignment: */ + +#define md_swap_short(x) (x) +#define md_swap_long(x) (x) + +#define get_byte(p) ( ((unsigned char *)(p))[0] ) + +#define get_short(p) ( ( ((unsigned char *)(p))[0] << 8) | \ + ( ((unsigned char *)(p))[1] ) \ + ) + +#define get_long(p) ( ( ((unsigned char *)(p))[0] << 24) | \ + ( ((unsigned char *)(p))[1] << 16) | \ + ( ((unsigned char *)(p))[2] << 8 ) | \ + ( ((unsigned char *)(p))[3] ) \ + ) + + +#define put_byte(p, v) { ((unsigned char *)(p))[0] = ((unsigned long)(v)); } + +#define put_short(p, v) { ((unsigned char *)(p))[0] = \ + ((((unsigned long)(v)) >> 8) & 0xff); \ + ((unsigned char *)(p))[1] = \ + ((((unsigned long)(v)) ) & 0xff); } + +#define put_long(p, v) { ((unsigned char *)(p))[0] = \ + ((((unsigned long)(v)) >> 24) & 0xff); \ + ((unsigned char *)(p))[1] = \ + ((((unsigned long)(v)) >> 16) & 0xff); \ + ((unsigned char *)(p))[2] = \ + ((((unsigned long)(v)) >> 8) & 0xff); \ + ((unsigned char *)(p))[3] = \ + ((((unsigned long)(v)) ) & 0xff); } + +#endif /* NEED_SWAP */ + +#else /* Not a cross linker: use native */ + +#define md_swap_short(x) (x) +#define md_swap_long(x) (x) + +#define get_byte(where) (*(char *)(where)) +#define get_short(where) (*(short *)(where)) +#define get_long(where) (*(long *)(where)) + +#define put_byte(where,what) (*(char *)(where) = (what)) +#define put_short(where,what) (*(short *)(where) = (what)) +#define put_long(where,what) (*(long *)(where) = (what)) + +#endif /* CROSS_LINKER */ + diff --git a/gnu/usr.bin/ld/sparc/mdprologue.S b/gnu/usr.bin/ld/sparc/mdprologue.S new file mode 100644 index 000000000000..cf4873260c2e --- /dev/null +++ b/gnu/usr.bin/ld/sparc/mdprologue.S @@ -0,0 +1,101 @@ +/* + * Copyright (c) 1993 Paul Kranenburg + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Paul Kranenburg. + * 4. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * $Id: mdprologue.S,v 1.3 1994/02/13 20:43:13 jkh Exp $ + */ + +/* + * SPARC run-time link editor entry points. + */ + +#define CRT_VERSION_SUN 1 + + .seg "text" ! [internal] + .proc 16 + .global _rtld_entry +_rtld_entry: +!#PROLOGUE# 0 + save %sp,-96,%sp +L.1B: + call L.2B + sethi %hi((__GLOBAL_OFFSET_TABLE_-(L.1B-.))),%l7 +L.2B: +!#PROLOGUE# 1 + or %l7,%lo((__GLOBAL_OFFSET_TABLE_-(L.1B-.))),%l7 + add %l7,%o7,%l7 + + cmp %i0, CRT_VERSION_SUN ! is crtp passed in Sun style, + bne 1f ! ie. relative to stack frame ? + nop + add %i1, %fp, %i1 ! if so, adjust to absolute address +1: + ld [%i1], %o3 ! load base address (crtp->crt_ba) + ld [%l7], %o2 ! get rtld's __DYNAMIC address + ! from 1st GOT entry + add %o2, %o3, %o2 ! relocate and make it 3rd arg. + + ld [%l7 + _rtld], %g1 ! get address of rtld() + add %g1, %o3, %g1 ! relocate + + mov %i1, %o1 ! set up args, #2: crtp + call %g1 ! rtld(version, crtp, dp) + mov %i0, %o0 ! arg #1: version + + ret + restore + .seg "data" ! [internal] + + .seg "text" + .global _binder_entry +_binder_entry: +!#PROLOGUE# 0 + save %sp,-96,%sp +!L.1C: +! call L.2C +! sethi %hi((__GLOBAL_OFFSET_TABLE_-(L.1C-.))),%l7 +!L.2C: +! or %l7,%lo((__GLOBAL_OFFSET_TABLE_-(L.1C-.))),%l7 +!#PROLOGUE# 1 + + sub %i7, 4, %o0 ! get to jmpslot through pc + ld [%i7+4], %o1 ! get relocation index + sethi %hi(0x3fffff), %o2 ! -> reloc_index & 0x003fffff + or %o2, %lo(0x3fffff), %o2 ! [internal] + call _binder ! and call binder(jsp, reloc_index) + and %o1, %o2, %o1 + + mov %o0, %g1 ! return value == function address + + restore ! get rid of our context + jmp %g1 ! and go. + restore ! and the jmpslot's + nop + + .seg "data" ! [internal] + diff --git a/gnu/usr.bin/ld/symbol.c b/gnu/usr.bin/ld/symbol.c new file mode 100644 index 000000000000..495726565e58 --- /dev/null +++ b/gnu/usr.bin/ld/symbol.c @@ -0,0 +1,159 @@ +/* + * $Id: symbol.c,v 1.4 1994/02/13 20:41:46 jkh Exp $ - symbol table routines + */ + +/* Create the symbol table entries for `etext', `edata' and `end'. */ + +#include <sys/param.h> +#include <stdio.h> +#include <stdlib.h> +#include <sys/types.h> +#include <fcntl.h> +#include <a.out.h> +#include <stab.h> +#include <string.h> + +#include "ld.h" + +symbol *symtab[SYMTABSIZE]; /* The symbol table. */ +int num_hash_tab_syms; /* Number of symbols in symbol hash table. */ + +symbol *edata_symbol; /* the symbol _edata */ +symbol *etext_symbol; /* the symbol _etext */ +symbol *end_symbol; /* the symbol _end */ +symbol *got_symbol; /* the symbol __GLOBAL_OFFSET_TABLE_ */ +symbol *dynamic_symbol; /* the symbol __DYNAMIC */ + +void +symtab_init (relocatable_output) +int relocatable_output; +{ + /* + * Put linker reserved symbols into symbol table. + */ +#ifndef nounderscore +#define ETEXT_SYM "_etext" +#define EDATA_SYM "_edata" +#define END_SYM "_end" +#define DYN_SYM "__DYNAMIC" +#define GOT_SYM "__GLOBAL_OFFSET_TABLE_" +#else +#define ETEXT_SYM "etext" +#define EDATA_SYM "edata" +#define END_SYM "end" +#define DYN_SYM "_DYNAMIC" +#define GOT_SYM "_GLOBAL_OFFSET_TABLE_" +#endif + + dynamic_symbol = getsym (DYN_SYM); + dynamic_symbol->defined = relocatable_output?N_UNDF:(N_DATA | N_EXT); + + got_symbol = getsym (GOT_SYM); + got_symbol->defined = N_DATA | N_EXT; + + if (relocatable_output) + return; + + etext_symbol = getsym (ETEXT_SYM); + edata_symbol = getsym (EDATA_SYM); + end_symbol = getsym (END_SYM); + + etext_symbol->defined = N_TEXT | N_EXT; + edata_symbol->defined = N_DATA | N_EXT; + end_symbol->defined = N_BSS | N_EXT; + + etext_symbol->flags |= GS_REFERENCED; + edata_symbol->flags |= GS_REFERENCED; + end_symbol->flags |= GS_REFERENCED; +} + +/* Compute the hash code for symbol name KEY. */ + +int +hash_string (key) + char *key; +{ + register char *cp; + register int k; + + cp = key; + k = 0; + while (*cp) + k = (((k << 1) + (k >> 14)) ^ (*cp++)) & 0x3fff; + + return k; +} + +/* Get the symbol table entry for the global symbol named KEY. + Create one if there is none. */ + +symbol * +getsym(key) + char *key; +{ + register int hashval; + register symbol *bp; + + /* Determine the proper bucket. */ + hashval = hash_string (key) % SYMTABSIZE; + + /* Search the bucket. */ + for (bp = symtab[hashval]; bp; bp = bp->link) + if (! strcmp (key, bp->name)) + return bp; + + /* Nothing was found; create a new symbol table entry. */ + bp = (symbol *) xmalloc (sizeof (symbol)); + bp->name = (char *) xmalloc (strlen (key) + 1); + strcpy (bp->name, key); + bp->refs = 0; + bp->defined = 0; + bp->value = 0; + bp->common_size = 0; + bp->warning = 0; + bp->undef_refs = 0; + bp->mult_defs = 0; + bp->alias = 0; + bp->setv_count = 0; + bp->symbolnum = 0; + bp->rrs_symbolnum = 0; + + bp->size = 0; + bp->aux = 0; + bp->sorefs = 0; + bp->so_defined = 0; + bp->def_nlist = 0; + bp->jmpslot_offset = -1; + bp->gotslot_offset = -1; + bp->flags = 0; + + /* Add the entry to the bucket. */ + bp->link = symtab[hashval]; + symtab[hashval] = bp; + + ++num_hash_tab_syms; + + return bp; +} + +/* Like `getsym' but return 0 if the symbol is not already known. */ + +symbol * +getsym_soft (key) + char *key; +{ + register int hashval; + register symbol *bp; + + /* Determine which bucket. */ + + hashval = hash_string (key) % SYMTABSIZE; + + /* Search the bucket. */ + + for (bp = symtab[hashval]; bp; bp = bp->link) + if (! strcmp (key, bp->name)) + return bp; + + return 0; +} diff --git a/gnu/usr.bin/ld/symseg.h b/gnu/usr.bin/ld/symseg.h new file mode 100644 index 000000000000..b07bc2455d5c --- /dev/null +++ b/gnu/usr.bin/ld/symseg.h @@ -0,0 +1,359 @@ +/*- + * + * This code is derived from software copyrighted by the Free Software + * Foundation. + * + * from: @(#)symseg.h 5.4 (Berkeley) 4/30/91 + * $Id: symseg.h,v 1.3 1993/11/09 04:19:05 paul Exp $ + */ + +/* GDB symbol table format definitions. + Copyright (C) 1987, 1988 Free Software Foundation, Inc. + +This file is part of GNU CC. + +GNU CC is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 1, or (at your option) +any later version. + +GNU CC is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU CC; see the file COPYING. If not, write to +the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */ + +/* Format of GDB symbol table data. + There is one symbol segment for each source file or + independant compilation. These segments are simply concatenated + to form the GDB symbol table. A zero word where the beginning + of a segment is expected indicates there are no more segments. + +Format of a symbol segment: + + The symbol segment begins with a word containing 1 + if it is in the format described here. Other formats may + be designed, with other code numbers. + + The segment contains many objects which point at each other. + The pointers are offsets in bytes from the beginning of the segment. + Thus, each segment can be loaded into core and its pointers relocated + to make valid in-core pointers. + + All the data objects in the segment can be found indirectly from + one of them, the root object, of type `struct symbol_root'. + It appears at the beginning of the segment. + + The total size of the segment, in bytes, appears as the `length' + field of this object. This size includes the size of the + root object. + + All the object data types are defined here to contain pointer types + appropriate for in-core use on a relocated symbol segment. + Casts to and from type int are required for working with + unrelocated symbol segments such as are found in the file. + + The ldsymaddr word is filled in by the loader to contain + the offset (in bytes) within the ld symbol table + of the first nonglobal symbol from this compilation. + This makes it possible to match those symbols + (which contain line number information) reliably with + the segment they go with. + + Core addresses within the program that appear in the symbol segment + are not relocated by the loader. They are inserted by the assembler + and apply to addresses as output by the assembler, so GDB must + relocate them when it loads the symbol segment. It gets the information + on how to relocate from the textrel, datarel, bssrel, databeg and bssbeg + words of the root object. + + The words textrel, datarel and bssrel + are filled in by ld with the amounts to relocate within-the-file + text, data and bss addresses by; databeg and bssbeg can be + used to tell which kind of relocation an address needs. */ + +enum language {language_c}; + +struct symbol_root +{ + int format; /* Data format version */ + int length; /* # bytes in this symbol segment */ + int ldsymoff; /* Offset in ld symtab of this file's syms */ + int textrel; /* Relocation for text addresses */ + int datarel; /* Relocation for data addresses */ + int bssrel; /* Relocation for bss addresses */ + char *filename; /* Name of main source file compiled */ + char *filedir; /* Name of directory it was reached from */ + struct blockvector *blockvector; /* Vector of all symbol-naming blocks */ + struct typevector *typevector; /* Vector of all data types */ + enum language language; /* Code identifying the language used */ + char *version; /* Version info. Not fully specified */ + char *compilation; /* Compilation info. Not fully specified */ + int databeg; /* Address within the file of data start */ + int bssbeg; /* Address within the file of bss start */ + struct sourcevector *sourcevector; /* Vector of line-number info */ +}; + +/* All data types of symbols in the compiled program + are represented by `struct type' objects. + All of these objects are pointed to by the typevector. + The type vector may have empty slots that contain zero. */ + +struct typevector +{ + int length; /* Number of types described */ + struct type *type[1]; +}; + +/* Different kinds of data types are distinguished by the `code' field. */ + +enum type_code +{ + TYPE_CODE_UNDEF, /* Not used; catches errors */ + TYPE_CODE_PTR, /* Pointer type */ + TYPE_CODE_ARRAY, /* Array type, lower bound zero */ + TYPE_CODE_STRUCT, /* C struct or Pascal record */ + TYPE_CODE_UNION, /* C union or Pascal variant part */ + TYPE_CODE_ENUM, /* Enumeration type */ + TYPE_CODE_FUNC, /* Function type */ + TYPE_CODE_INT, /* Integer type */ + TYPE_CODE_FLT, /* Floating type */ + TYPE_CODE_VOID, /* Void type (values zero length) */ + TYPE_CODE_SET, /* Pascal sets */ + TYPE_CODE_RANGE, /* Range (integers within spec'd bounds) */ + TYPE_CODE_PASCAL_ARRAY, /* Array with explicit type of index */ +}; + +/* This appears in a type's flags word for an unsigned integer type. */ +#define TYPE_FLAG_UNSIGNED 1 + +/* Other flag bits are used with GDB. */ + +struct type +{ + /* Code for kind of type */ + enum type_code code; + /* Name of this type, or zero if none. + This is used for printing only. + Type names specified as input are defined by symbols. */ + char *name; + /* Length in bytes of storage for a value of this type */ + int length; + /* For a pointer type, describes the type of object pointed to. + For an array type, describes the type of the elements. + For a function type, describes the type of the value. + Unused otherwise. */ + struct type *target_type; + /* Type that is a pointer to this type. + Zero if no such pointer-to type is known yet. + The debugger may add the address of such a type + if it has to construct one later. */ + struct type *pointer_type; + /* Type that is a function returning this type. + Zero if no such function type is known here. + The debugger may add the address of such a type + if it has to construct one later. */ + struct type *function_type; + /* Flags about this type. */ + short flags; + /* Number of fields described for this type */ + short nfields; + /* For structure and union types, a description of each field. + For set and pascal array types, there is one "field", + whose type is the domain type of the set or array. + For range types, there are two "fields", + the minimum and maximum values (both inclusive). + For enum types, each possible value is described by one "field". + For range types, there are two "fields", that record constant values + (inclusive) for the minimum and maximum. + + Using a pointer to a separate array of fields + allows all types to have the same size, which is useful + because we can allocate the space for a type before + we know what to put in it. */ + struct field + { + /* Position of this field, counting in bits from start of + containing structure. For a function type, this is the + position in the argument list of this argument. + For a range bound or enum value, this is the value itself. */ + int bitpos; + /* Size of this field, in bits, or zero if not packed. + For an unpacked field, the field's type's length + says how many bytes the field occupies. */ + int bitsize; + /* In a struct or enum type, type of this field. + In a function type, type of this argument. + In an array type, the domain-type of the array. */ + struct type *type; + /* Name of field, value or argument. + Zero for range bounds and array domains. */ + char *name; + } *fields; +}; + +/* All of the name-scope contours of the program + are represented by `struct block' objects. + All of these objects are pointed to by the blockvector. + + Each block represents one name scope. + Each lexical context has its own block. + + The first two blocks in the blockvector are special. + The first one contains all the symbols defined in this compilation + whose scope is the entire program linked together. + The second one contains all the symbols whose scope is the + entire compilation excluding other separate compilations. + In C, these correspond to global symbols and static symbols. + + Each block records a range of core addresses for the code that + is in the scope of the block. The first two special blocks + give, for the range of code, the entire range of code produced + by the compilation that the symbol segment belongs to. + + The blocks appear in the blockvector + in order of increasing starting-address, + and, within that, in order of decreasing ending-address. + + This implies that within the body of one function + the blocks appear in the order of a depth-first tree walk. */ + +struct blockvector +{ + /* Number of blocks in the list. */ + int nblocks; + /* The blocks themselves. */ + struct block *block[1]; +}; + +struct block +{ + /* Addresses in the executable code that are in this block. + Note: in an unrelocated symbol segment in a file, + these are always zero. They can be filled in from the + N_LBRAC and N_RBRAC symbols in the loader symbol table. */ + int startaddr, endaddr; + /* The symbol that names this block, + if the block is the body of a function; + otherwise, zero. + Note: In an unrelocated symbol segment in an object file, + this field may be zero even when the block has a name. + That is because the block is output before the name + (since the name resides in a higher block). + Since the symbol does point to the block (as its value), + it is possible to find the block and set its name properly. */ + struct symbol *function; + /* The `struct block' for the containing block, or 0 if none. */ + /* Note that in an unrelocated symbol segment in an object file + this pointer may be zero when the correct value should be + the second special block (for symbols whose scope is one compilation). + This is because the compiler ouptuts the special blocks at the + very end, after the other blocks. */ + struct block *superblock; + /* Number of local symbols. */ + int nsyms; + /* The symbols. */ + struct symbol *sym[1]; +}; + +/* Represent one symbol name; a variable, constant, function or typedef. */ + +/* Different name spaces for symbols. Looking up a symbol specifies + a namespace and ignores symbol definitions in other name spaces. + + VAR_NAMESPACE is the usual namespace. + In C, this contains variables, function names, typedef names + and enum type values. + + STRUCT_NAMESPACE is used in C to hold struct, union and enum type names. + Thus, if `struct foo' is used in a C program, + it produces a symbol named `foo' in the STRUCT_NAMESPACE. + + LABEL_NAMESPACE may be used for names of labels (for gotos); + currently it is not used and labels are not recorded at all. */ + +/* For a non-global symbol allocated statically, + the correct core address cannot be determined by the compiler. + The compiler puts an index number into the symbol's value field. + This index number can be matched with the "desc" field of + an entry in the loader symbol table. */ + +enum namespace +{ + UNDEF_NAMESPACE, VAR_NAMESPACE, STRUCT_NAMESPACE, LABEL_NAMESPACE, +}; + +/* An address-class says where to find the value of the symbol in core. */ + +enum address_class +{ + LOC_UNDEF, /* Not used; catches errors */ + LOC_CONST, /* Value is constant int */ + LOC_STATIC, /* Value is at fixed address */ + LOC_REGISTER, /* Value is in register */ + LOC_ARG, /* Value is at spec'd position in arglist */ + LOC_LOCAL, /* Value is at spec'd pos in stack frame */ + LOC_TYPEDEF, /* Value not used; definition in SYMBOL_TYPE + Symbols in the namespace STRUCT_NAMESPACE + all have this class. */ + LOC_LABEL, /* Value is address in the code */ + LOC_BLOCK, /* Value is address of a `struct block'. + Function names have this class. */ + LOC_EXTERNAL, /* Value is at address not in this compilation. + This is used for .comm symbols + and for extern symbols within functions. + Inside GDB, this is changed to LOC_STATIC once the + real address is obtained from a loader symbol. */ + LOC_CONST_BYTES /* Value is a constant byte-sequence. */ +}; + +struct symbol +{ + /* Symbol name */ + char *name; + /* Name space code. */ + enum namespace namespace; + /* Address class */ + enum address_class class; + /* Data type of value */ + struct type *type; + /* constant value, or address if static, or register number, + or offset in arguments, or offset in stack frame. */ + union + { + long value; + struct block *block; /* for LOC_BLOCK */ + char *bytes; /* for LOC_CONST_BYTES */ + } + value; +}; + +/* Source-file information. + This describes the relation between source files and line numbers + and addresses in the program text. */ + +struct sourcevector +{ + int length; /* Number of source files described */ + struct source *source[1]; /* Descriptions of the files */ +}; + +/* Line number and address of one line. */ + +struct line +{ + int linenum; + int address; +}; + +/* All the information on one source file. */ + +struct source +{ + char *name; /* Name of file */ + int nlines; /* Number of lines that follow */ + struct line lines[1]; /* Information on each line */ +}; diff --git a/gnu/usr.bin/ld/warnings.c b/gnu/usr.bin/ld/warnings.c new file mode 100644 index 000000000000..9d2634f35f52 --- /dev/null +++ b/gnu/usr.bin/ld/warnings.c @@ -0,0 +1,750 @@ +/* + * $Id: warnings.c,v 1.6 1994/02/13 20:41:48 jkh Exp $ + */ + +#include <sys/param.h> +#include <stdio.h> +#include <stdlib.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <sys/file.h> +#include <sys/time.h> +#include <sys/errno.h> +#include <fcntl.h> +#include <ar.h> +#include <ranlib.h> +#include <a.out.h> +#include <stab.h> +#include <string.h> +#if __STDC__ +#include <stdarg.h> +#else +#include <varargs.h> +#endif + +#include "ld.h" + +/* + * Print the filename of ENTRY on OUTFILE (a stdio stream), + * and then a newline. + */ + +void +prline_file_name (entry, outfile) + struct file_entry *entry; + FILE *outfile; +{ + print_file_name (entry, outfile); + fprintf (outfile, "\n"); +} + +/* + * Print the filename of ENTRY on OUTFILE (a stdio stream). + */ + +void +print_file_name (entry, outfile) + struct file_entry *entry; + FILE *outfile; +{ + if (entry == NULL) { + fprintf (outfile, "NULL"); + } + + if (entry->superfile) { + print_file_name (entry->superfile, outfile); + fprintf (outfile, "(%s)", entry->filename); + } else + fprintf (outfile, "%s", entry->filename); +} + +/* + * Return the filename of entry as a string (malloc'd for the purpose) + */ + +char * +get_file_name (entry) + struct file_entry *entry; +{ + char *result, *supfile; + + if (entry == NULL) { + return (char *)strdup("NULL"); + } + + if (entry->superfile) { + supfile = get_file_name (entry->superfile); + result = (char *) xmalloc (strlen(supfile) + + strlen(entry->filename) + 3); + sprintf (result, "%s(%s)", supfile, entry->filename); + free (supfile); + + } else { + result = (char *) xmalloc (strlen (entry->filename) + 1); + strcpy (result, entry->filename); + } + return result; +} + +/* + * Report a fatal error. The error message is STRING followed by the + * filename of ENTRY. + */ +void +#if __STDC__ +fatal_with_file (char *fmt, struct file_entry *entry, ...) +#else +fatal_with_file (fmt, entry, va_alist) + char *fmt; + struct file_entry *entry; + va_dcl +#endif +{ + va_list ap; +#if __STDC__ + va_start(ap, fmt); +#else + va_start(ap); +#endif + (void)fprintf(stderr, "%s: ", progname); + (void)vfprintf(stderr, fmt, ap); + print_file_name (entry, stderr); + (void)fprintf(stderr, "\n"); + + va_end(ap); + exit (1); +} + +/* + * Report a fatal error using the message for the last failed system call, + * followed by the string NAME. + */ +void +perror_name (name) + char *name; +{ + char *s; + + if (errno < sys_nerr) + s = concat ("", sys_errlist[errno], " for %s"); + else + s = "cannot open %s"; + fatal (s, name); +} + +/* + * Report a fatal error using the message for the last failed system call, + * followed by the name of file ENTRY. + */ +void +perror_file (entry) + struct file_entry *entry; +{ + char *s; + + if (errno < sys_nerr) + s = concat ("", sys_errlist[errno], " for "); + else + s = "cannot open "; + fatal_with_file (s, entry); +} + + +/* Print a complete or partial map of the output file. */ + +static void describe_file_sections __P((struct file_entry *, FILE *)); +static void list_file_locals __P((struct file_entry *, FILE *)); + +void +print_symbols(outfile) + FILE *outfile; +{ + fprintf(outfile, "\nFiles:\n\n"); + each_file(describe_file_sections, outfile); + + fprintf(outfile, "\nGlobal symbols:\n\n"); + FOR_EACH_SYMBOL(i, sp) { + if (sp->defined == (N_UNDF|N_EXT)) + fprintf(outfile, " %s: common, length %#x\n", + sp->name, sp->common_size); + if (!(sp->flags & GS_REFERENCED)) + fprintf(outfile, " %s: unreferenced\n", sp->name); + else if (sp->so_defined) + fprintf(outfile, " %s: sodefined\n", sp->name); + else if (!sp->defined) + fprintf(outfile, " %s: undefined\n", sp->name); + else + fprintf(outfile, " %s: %#x, size %#x\n", + sp->name, sp->value, sp->size); + } END_EACH_SYMBOL; + + each_file(list_file_locals, outfile); +} + +static void +describe_file_sections(entry, outfile) + struct file_entry *entry; + FILE *outfile; +{ + fprintf(outfile, " "); + print_file_name(entry, outfile); + if (entry->flags & (E_JUST_SYMS | E_DYNAMIC)) + fprintf(outfile, " symbols only\n", 0); + else + fprintf(outfile, " text %x(%x), data %x(%x), bss %x(%x) hex\n", + entry->text_start_address, entry->header.a_text, + entry->data_start_address, entry->header.a_data, + entry->bss_start_address, entry->header.a_bss); +} + +static void +list_file_locals (entry, outfile) + struct file_entry *entry; + FILE *outfile; +{ + struct localsymbol *lsp, *lspend; + + entry->strings = (char *) alloca (entry->string_size); + read_entry_strings (file_open (entry), entry); + + fprintf (outfile, "\nLocal symbols of "); + print_file_name (entry, outfile); + fprintf (outfile, ":\n\n"); + + lspend = entry->symbols + entry->nsymbols; + for (lsp = entry->symbols; lsp < lspend; lsp++) { + register struct nlist *p = &lsp->nzlist.nlist; + /* + * If this is a definition, + * update it if necessary by this file's start address. + */ + if (!(p->n_type & (N_STAB | N_EXT))) + fprintf(outfile, " %s: 0x%x\n", + entry->strings + p->n_un.n_strx, p->n_value); + } + + entry->strings = 0; /* All done with them. */ +} + + +/* Static vars for do_warnings and subroutines of it */ +static int list_unresolved_refs; /* List unresolved refs */ +static int list_warning_symbols; /* List warning syms */ +static int list_multiple_defs; /* List multiple definitions */ + +static struct line_debug_entry *init_debug_scan __P((int, struct file_entry *)); +static int next_debug_entry __P((int, struct line_debug_entry *)); + +/* + * Structure for communication between do_file_warnings and it's + * helper routines. Will in practice be an array of three of these: + * 0) Current line, 1) Next line, 2) Source file info. + */ +struct line_debug_entry +{ + int line; + char *filename; + struct localsymbol *sym; +}; + +/* + * Helper routines for do_file_warnings. + */ + +/* Return an integer less than, equal to, or greater than 0 as per the + relation between the two relocation entries. Used by qsort. */ + +static int +relocation_entries_relation (rel1, rel2) + struct relocation_info *rel1, *rel2; +{ + return RELOC_ADDRESS(rel1) - RELOC_ADDRESS(rel2); +} + +/* Moves to the next debugging symbol in the file. USE_DATA_SYMBOLS + determines the type of the debugging symbol to look for (DSLINE or + SLINE). STATE_POINTER keeps track of the old and new locatiosn in + the file. It assumes that state_pointer[1] is valid; ie + that it.sym points into some entry in the symbol table. If + state_pointer[1].sym == 0, this routine should not be called. */ + +static int +next_debug_entry (use_data_symbols, state_pointer) + register int use_data_symbols; + /* Next must be passed by reference! */ + struct line_debug_entry state_pointer[3]; +{ + register struct line_debug_entry + *current = state_pointer, + *next = state_pointer + 1, + /* Used to store source file */ + *source = state_pointer + 2; + + struct file_entry *entry = (struct file_entry *) source->sym; + struct localsymbol *endp = entry->symbols + entry->nsymbols; + + + current->sym = next->sym; + current->line = next->line; + current->filename = next->filename; + + while (++(next->sym) < endp) { + + struct nlist *np = &next->sym->nzlist.nlist; + + /* + * n_type is a char, and N_SOL, N_EINCL and N_BINCL are > 0x80, + * so may look negative...therefore, must mask to low bits + */ + switch (np->n_type & 0xff) { + case N_SLINE: + if (use_data_symbols) continue; + next->line = np->n_desc; + return 1; + case N_DSLINE: + if (!use_data_symbols) continue; + next->line = np->n_desc; + return 1; +#ifdef HAVE_SUN_STABS + case N_EINCL: + next->filename = source->filename; + continue; +#endif + case N_SO: + source->filename = np->n_un.n_strx + entry->strings; + source->line++; +#ifdef HAVE_SUN_STABS + case N_BINCL: +#endif + case N_SOL: + next->filename = np->n_un.n_strx + entry->strings; + default: + continue; + } + } + next->sym = (struct localsymbol *)0; + return 0; +} + +/* + * Create a structure to save the state of a scan through the debug symbols. + * USE_DATA_SYMBOLS is set if we should be scanning for DSLINE's instead of + * SLINE's. entry is the file entry which points at the symbols to use. + */ + +static struct line_debug_entry * +init_debug_scan(use_data_symbols, entry) + int use_data_symbols; + struct file_entry *entry; +{ + struct localsymbol *lsp; + struct line_debug_entry *state_pointer = (struct line_debug_entry *) + xmalloc(3 * sizeof(struct line_debug_entry)); + + register struct line_debug_entry + *current = state_pointer, + *next = state_pointer + 1, + *source = state_pointer + 2; /* Used to store source file */ + + + for (lsp = entry->symbols; lsp < entry->symbols+entry->nsymbols; lsp++) + if (lsp->nzlist.nlist.n_type == N_SO) + break; + + if (lsp >= entry->symbols + entry->nsymbols) { + /* I believe this translates to "We lose" */ + current->filename = next->filename = entry->filename; + current->line = next->line = -1; + current->sym = next->sym = (struct localsymbol *) 0; + return state_pointer; + } + next->line = source->line = 0; + next->filename = source->filename + = (lsp->nzlist.nlist.n_un.n_strx + entry->strings); + source->sym = (struct localsymbol *) entry; + next->sym = lsp; + + /* To setup next */ + next_debug_entry(use_data_symbols, state_pointer); + + if (!next->sym) { /* No line numbers for this section; */ + /* setup output results as appropriate */ + if (source->line) { + current->filename = source->filename = entry->filename; + current->line = -1; /* Don't print lineno */ + } else { + current->filename = source->filename; + current->line = 0; + } + return state_pointer; + } + /* To setup current */ + next_debug_entry(use_data_symbols, state_pointer); + + return state_pointer; +} + +/* + * Takes an ADDRESS (in either text or data space) and a STATE_POINTER which + * describes the current location in the implied scan through the debug + * symbols within the file which ADDRESS is within, and returns the source + * line number which corresponds to ADDRESS. + */ + +static int +address_to_line(address, state_pointer) + unsigned long address; +/* Next must be passed by reference! */ + struct line_debug_entry state_pointer[3]; +{ + struct line_debug_entry + *current = state_pointer, *next = state_pointer + 1; + struct line_debug_entry *tmp_pointer; + + int use_data_symbols; + + if (next->sym) + use_data_symbols = + (next->sym->nzlist.nlist.n_type & N_TYPE) == N_DATA; + else + return current->line; + + /* Go back to the beginning if we've already passed it. */ + if (current->sym->nzlist.nlist.n_value > address) { + tmp_pointer = init_debug_scan(use_data_symbols, + (struct file_entry *) + ((state_pointer + 2)->sym)); + state_pointer[0] = tmp_pointer[0]; + state_pointer[1] = tmp_pointer[1]; + state_pointer[2] = tmp_pointer[2]; + free(tmp_pointer); + } + /* If we're still in a bad way, return -1, meaning invalid line. */ + if (current->sym->nzlist.nlist.n_value > address) + return -1; + + while (next->sym + && next->sym->nzlist.nlist.n_value <= address + && next_debug_entry(use_data_symbols, state_pointer)); + return current->line; +} + + +/* Macros for manipulating bitvectors. */ +#define BIT_SET_P(bv, index) ((bv)[(index) >> 3] & 1 << ((index) & 0x7)) +#define SET_BIT(bv, index) ((bv)[(index) >> 3] |= 1 << ((index) & 0x7)) + +/* + * This routine will scan through the relocation data of file ENTRY, printing + * out references to undefined symbols and references to symbols defined in + * files with N_WARNING symbols. If DATA_SEGMENT is non-zero, it will scan + * the data relocation segment (and use N_DSLINE symbols to track line + * number); otherwise it will scan the text relocation segment. Warnings + * will be printed on the output stream OUTFILE. Eventually, every nlist + * symbol mapped through will be marked in the NLIST_BITVECTOR, so we don't + * repeat ourselves when we scan the nlists themselves. + */ + +static void +do_relocation_warnings(entry, data_segment, outfile, nlist_bitvector) + struct file_entry *entry; + int data_segment; + FILE *outfile; + unsigned char *nlist_bitvector; +{ + struct relocation_info *reloc, *reloc_start = + data_segment ? entry->datarel : entry->textrel; + + int reloc_size = (data_segment ? entry->ndatarel : entry->ntextrel); + int start_of_segment = (data_segment ? + entry->data_start_address : + entry->text_start_address); + struct localsymbol *start_of_syms = entry->symbols; + struct line_debug_entry *state_pointer = + init_debug_scan(data_segment != 0, entry); + + register struct line_debug_entry *current = state_pointer; + + /* Assigned to generally static values; should not be written into. */ + char *errfmt; + + /* + * Assigned to alloca'd values cand copied into; should be freed when + * done. + */ + char *errmsg; + int invalidate_line_number; + + /* + * We need to sort the relocation info here. Sheesh, so much effort + * for one lousy error optimization. + */ + + qsort(reloc_start, reloc_size, sizeof(struct relocation_info), + relocation_entries_relation); + + for (reloc = reloc_start; + reloc < (reloc_start + reloc_size); + reloc++) { + register struct localsymbol *s; + register symbol *g; + + /* + * If the relocation isn't resolved through a symbol, + * continue + */ + if (!RELOC_EXTERN_P(reloc)) + continue; + + s = &entry->symbols[RELOC_SYMBOL(reloc)]; + + /* + * Local symbols shouldn't ever be used by relocation info, + * so the next should be safe. This is, of course, wrong. + * References to local BSS symbols can be the targets of + * relocation info, and they can (must) be resolved through + * symbols. However, these must be defined properly, (the + * assembler would have caught it otherwise), so we can + * ignore these cases. + */ + if (!(s->nzlist.nz_type & N_EXT)) + continue; + + g = s->symbol; + errmsg = 0; + + if (!g->defined && !g->so_defined && list_unresolved_refs) { /* Reference */ + /* Mark as being noted by relocation warning pass. */ + SET_BIT(nlist_bitvector, s - start_of_syms); + + if (g->undef_refs >= MAX_UREFS_PRINTED) /* Listed too many */ + continue; + + /* Undefined symbol which we should mention */ + + if (++(g->undef_refs) == MAX_UREFS_PRINTED) { + errfmt = "More undefined symbol %s refs follow"; + invalidate_line_number = 1; + } else { + errfmt = "Undefined symbol %s referenced from %s segment"; + invalidate_line_number = 0; + } + } else { /* Defined */ + /* Potential symbol warning here */ + if (!g->warning) + continue; + + /* Mark as being noted by relocation warning pass. */ + SET_BIT(nlist_bitvector, s - start_of_syms); + + errfmt = 0; + errmsg = g->warning; + invalidate_line_number = 0; + } + + + /* If errfmt == 0, errmsg has already been defined. */ + if (errfmt != 0) { + char *nm; + + nm = g->name; + errmsg = (char *) xmalloc(strlen(errfmt) + strlen(nm) + 1); + sprintf(errmsg, errfmt, nm, data_segment ? "data" : "text"); + if (nm != g->name) + free(nm); + } + address_to_line(RELOC_ADDRESS(reloc) + start_of_segment, + state_pointer); + + if (current->line >= 0) + fprintf(outfile, "%s:%d: %s\n", current->filename, + invalidate_line_number ? 0 : current->line, errmsg); + else + fprintf(outfile, "%s: %s\n", current->filename, errmsg); + + if (errfmt != 0) + free(errmsg); + } + + free(state_pointer); +} + +/* + * Print on OUTFILE a list of all warnings generated by references and/or + * definitions in the file ENTRY. List source file and line number if + * possible, just the .o file if not. + */ + +void +do_file_warnings (entry, outfile) + struct file_entry *entry; + FILE *outfile; +{ + int number_of_syms = entry->nsymbols; + unsigned char *nlist_bitvector = (unsigned char *) + alloca ((number_of_syms >> 3) + 1); + struct line_debug_entry *text_scan, *data_scan; + int i; + char *errfmt, *file_name; + int line_number; + int dont_allow_symbol_name; + + bzero (nlist_bitvector, (number_of_syms >> 3) + 1); + + /* Read in the files strings if they aren't available */ + if (!entry->strings) { + int desc; + + entry->strings = (char *) alloca (entry->string_size); + desc = file_open (entry); + read_entry_strings (desc, entry); + } + + if (!(entry->flags & E_DYNAMIC)) { + /* Do text warnings based on a scan through the relocation info. */ + do_relocation_warnings (entry, 0, outfile, nlist_bitvector); + + /* Do data warnings based on a scan through the relocation info. */ + do_relocation_warnings (entry, 1, outfile, nlist_bitvector); + } + + /* Scan through all of the nlist entries in this file and pick up + anything that the scan through the relocation stuff didn't. */ + + text_scan = init_debug_scan (0, entry); + data_scan = init_debug_scan (1, entry); + + for (i = 0; i < number_of_syms; i++) { + struct nlist *s; + symbol *g; + + g = entry->symbols[i].symbol; + s = &entry->symbols[i].nzlist.nlist; + + if (!(s->n_type & N_EXT)) + continue; + + if (!(g->flags & GS_REFERENCED)) { +#if 0 + /* Check for undefined shobj symbols */ + struct localsymbol *lsp; + register int type; + + for (lsp = g->sorefs; lsp; lsp = lsp->next) { + type = lsp->nzlist.nz_type; + if ((type & N_EXT) && + type != (N_UNDF | N_EXT)) { + break; + } + } + if (type == (N_UNDF | N_EXT)) { + fprintf(stderr, + "Undefined symbol %s referenced from %s\n", + g->name, + get_file_name(entry)); + } +#endif + continue; + } + + dont_allow_symbol_name = 0; + + if (list_multiple_defs && g->mult_defs) { + errfmt = "Definition of symbol %s (multiply defined)"; + switch (s->n_type) { + + case N_TEXT | N_EXT: + line_number = address_to_line (s->n_value, text_scan); + file_name = text_scan[0].filename; + break; + + case N_DATA | N_EXT: + line_number = address_to_line (s->n_value, data_scan); + file_name = data_scan[0].filename; + break; + + case N_SETA | N_EXT: + case N_SETT | N_EXT: + case N_SETD | N_EXT: + case N_SETB | N_EXT: + if (g->mult_defs == 2) + continue; + errfmt = "First set element definition of symbol %s (multiply defined)"; + break; + + default: +printf("multiply defined: %s, type %#x\n", g->name, s->n_type); + /* Don't print out multiple defs at references.*/ + continue; + } + + } else if (BIT_SET_P (nlist_bitvector, i)) { + continue; + } else if (list_unresolved_refs && !g->defined && !g->so_defined) { + if (g->undef_refs >= MAX_UREFS_PRINTED) + continue; + + if (++(g->undef_refs) == MAX_UREFS_PRINTED) + errfmt = "More undefined \"%s\" refs follow"; + else + errfmt = "Undefined symbol \"%s\" referenced"; + line_number = -1; + } else if (g->warning) { + /* + * There are two cases in which we don't want to do + * this. The first is if this is a definition instead + * do a reference. The second is if it's the reference + * used by the warning stabs itself. + */ + if (s->n_type != (N_EXT | N_UNDF) + || (i && (s-1)->n_type == N_WARNING)) + continue; + + errfmt = g->warning; + line_number = -1; + dont_allow_symbol_name = 1; + } else + continue; + + if (line_number == -1) + fprintf (outfile, "%s: ", entry->filename); + else + fprintf (outfile, "%s:%d: ", file_name, line_number); + + if (dont_allow_symbol_name) + fprintf (outfile, "%s", errfmt); + else + fprintf (outfile, errfmt, g->name); + + fputc ('\n', outfile); + } + free (text_scan); + free (data_scan); + entry->strings = 0; /* Since it will dissapear anyway. */ +} + +int +do_warnings(outfile) + FILE *outfile; +{ + list_unresolved_refs = !relocatable_output && + (undefined_global_sym_count || undefined_shobj_sym_count); + list_warning_symbols = warning_count; + list_multiple_defs = multiple_def_count != 0; + + if (!(list_unresolved_refs || + list_warning_symbols || list_multiple_defs)) + /* No need to run this routine */ + return 1; + + if (entry_symbol && !entry_symbol->defined) + fprintf (outfile, "Undefined entry symbol %s\n", + entry_symbol->name); + each_file (do_file_warnings, outfile); + + if (list_unresolved_refs || list_multiple_defs) + return 0; + + return 1; +} + diff --git a/gnu/usr.bin/ld/xbits.c b/gnu/usr.bin/ld/xbits.c new file mode 100644 index 000000000000..ef25234db9a5 --- /dev/null +++ b/gnu/usr.bin/ld/xbits.c @@ -0,0 +1,167 @@ +/* + * Copyright (c) 1993 Paul Kranenburg + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Paul Kranenburg. + * 4. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * $Id: xbits.c,v 1.3 1994/02/13 20:41:50 jkh Exp $ + */ + +/* + * "Generic" byte-swap routines. + */ + +#include <sys/param.h> +#include <stdio.h> +#include <stdlib.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <sys/file.h> +#include <fcntl.h> +#include <ar.h> +#include <ranlib.h> +#include <a.out.h> +#include <stab.h> +#include <string.h> + +#include "ld.h" + +void +swap_longs(lp, n) +int n; +long *lp; +{ + for (; n > 0; n--, lp++) + *lp = md_swap_long(*lp); +} + +void +swap_symbols(s, n) +struct nlist *s; +int n; +{ + for (; n; n--, s++) { + s->n_un.n_strx = md_swap_long(s->n_un.n_strx); + s->n_desc = md_swap_short(s->n_desc); + s->n_value = md_swap_long(s->n_value); + } +} + +void +swap_zsymbols(s, n) +struct nzlist *s; +int n; +{ + for (; n; n--, s++) { + s->nz_strx = md_swap_long(s->nz_strx); + s->nz_desc = md_swap_short(s->nz_desc); + s->nz_value = md_swap_long(s->nz_value); + s->nz_size = md_swap_long(s->nz_size); + } +} + + +void +swap_ranlib_hdr(rlp, n) +struct ranlib *rlp; +int n; +{ + for (; n; n--, rlp++) { + rlp->ran_un.ran_strx = md_swap_long(rlp->ran_un.ran_strx); + rlp->ran_off = md_swap_long(rlp->ran_off); + } +} + +void +swap__dynamic(dp) +struct _dynamic *dp; +{ + dp->d_version = md_swap_long(dp->d_version); + dp->d_debug = (struct so_debug *)md_swap_long((long)dp->d_debug); + dp->d_un.d_sdt = (struct section_dispatch_table *) + md_swap_long((long)dp->d_un.d_sdt); + dp->d_entry = (struct ld_entry *)md_swap_long((long)dp->d_entry); +} + +void +swap_section_dispatch_table(sdp) +struct section_dispatch_table *sdp; +{ + swap_longs((long *)sdp, sizeof(*sdp)/sizeof(long)); +} + +void +swap_so_debug(ddp) +struct so_debug *ddp; +{ + swap_longs((long *)ddp, sizeof(*ddp)/sizeof(long)); +} + +void +swapin_sod(sodp, n) +struct sod *sodp; +int n; +{ + unsigned long bits; + + for (; n; n--, sodp++) { + sodp->sod_name = md_swap_long(sodp->sod_name); + sodp->sod_major = md_swap_short(sodp->sod_major); + sodp->sod_minor = md_swap_short(sodp->sod_minor); + sodp->sod_next = md_swap_long(sodp->sod_next); + bits = ((unsigned long *)sodp)[1]; + sodp->sod_library = ((bits >> 24) & 1); + } +} + +void +swapout_sod(sodp, n) +struct sod *sodp; +int n; +{ + unsigned long bits; + + for (; n; n--, sodp++) { + sodp->sod_name = md_swap_long(sodp->sod_name); + sodp->sod_major = md_swap_short(sodp->sod_major); + sodp->sod_minor = md_swap_short(sodp->sod_minor); + sodp->sod_next = md_swap_long(sodp->sod_next); + bits = (unsigned long)(sodp->sod_library) << 24; + ((unsigned long *)sodp)[1] = bits; + } +} + +void +swap_rrs_hash(fsp, n) +struct rrs_hash *fsp; +int n; +{ + for (; n; n--, fsp++) { + fsp->rh_symbolnum = md_swap_long(fsp->rh_symbolnum); + fsp->rh_next = md_swap_long(fsp->rh_next); + } +} + |
