4
# Copyright 2004-2005 Mike Hearn <mike@plan99.net>
5
# Copyright 2005 Vincent Béron <vberon@mecano.gme.usherb.ca>
6
# Copyright 2006 Psyche <psyche@ruidoabsurdo.com>
7
# Copyright 2007 Taj Morton <tajmorton@gmail.com>
9
#############################################################################
11
# Permission is hereby granted, free of charge, to any person obtaining a copy
12
# of this software and associated documentation files (the "Software"), to deal
13
# in the Software without restriction, including without limitation the rights
14
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
# copies of the Software, and to permit persons to whom the Software is
16
# furnished to do so, subject to the following conditions:
18
# The above copyright notice and this permission notice shall be included in
19
# all copies or substantial portions of the Software.
21
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
25
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
26
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28
#############################################################################
31
# - Figure out how to grab the GOT addr on PowerPC
32
# - Port to more archs
33
# - Figure out a way to check if we're on an ELF platform or not,
34
# maybe check for _GLOBAL_OFFSET_TABLE_ ?
36
using_partial_map=false
37
using_minimal_list=false
41
if [[ "$1" == "--version" ]]; then
43
echo "Copyright 2004 Mike Hearn"
44
echo "Copyright 2005 Vincent Béron"
46
echo "See $0 for license details."
50
if [[ "$@" == "" ]] || [[ "$1" == "--help" ]] || [[ "$1" == "-h" ]]; then
51
echo "Relaytool will generate a file that can be used instead of linking"
52
echo "directly against a library, which will dlopen the DSO at init time"
54
echo "Usage: relaytool [OPTION]... [LINKER COMMAND]..."
57
echo " --relay LIB If a matching -lLIB is found, generate a file"
58
echo " that can be used instead of linking directly to"
59
echo " LIB. The name of the file is echoed on stdout."
60
echo " Multiple --relay can be used together, a file will"
61
echo " be generated for each matching ones."
62
echo " --replace-all-libs Generate a file for every -lLIB parameter."
63
echo " --minimal-list OBJ_LIST Will look in OBJ_LIST for undefined symbols, and"
64
echo " generate a file creating only the needed symbols"
66
echo " --partial-map MAP_FILE Generate a file creating only the symbols contained"
67
echo " in MAP_FILE. Will apply to all further -lLIB"
68
echo " parameters, so in general is not suitable to"
69
echo " multiple libs in the same invocation of relaytool."
70
echo " --no-replace Echo -lLIB on stdout even if a --relay LIB is"
71
echo " found, so it'll be linked in normally."
72
echo " --multilink [SONAMES...] If a library has different SONAMES on different"
73
echo " Linux distributions you can specify the various"
74
echo " SONAMES that it's known by here. Relaytool will"
75
echo " attempt to load them (in the order provided) until"
76
echo " one if found. This cannot be used with multiple"
77
echo " --relay options. The first SONAME in the list will"
78
echo " be used as the name in the _is_present variable and"
79
echo " _symbol_is_present function."
80
echo " --out-dir DIRECTORY Write stub file to DIRECTORY instead of CWD."
81
echo "Linker commands:"
82
echo " -LPATH Add PATH to the list of paths to search for LIBs."
83
echo " -lLIB If a matching --relay LIB is found (or if"
84
echo " --replace-all-libs is specified), generate a file"
85
echo " that can be used instead of linking directly to"
86
echo " LIB. If there's no --relay LIB, echo -lLIB to"
88
echo " All other linker commands are passed as is to stdout."
89
echo "Other commands:"
90
echo " --help|-h Print this help."
91
echo " --version Print version information."
100
function readfinallink() {
102
while [ -L "$link_name" ]; do
103
new_name=$( readlink "$link_name" )
104
if [ "${new_name:0:1}" == "/" ]; then
105
link_name="$new_name"
107
link_name="`dirname "$link_name"`/$new_name"
110
if [ -f "$link_name" ]; then
120
if $using_multilink; then
121
libname=$( echo $( basename ${multilinklist[0]} ) | sed 's/\.so.*//' | tr '-' '_' | tr '.' '_' )
123
libname=$( echo $( basename "$lib" ) | sed 's/\.so.*//' | tr '-' '_' | tr '.' '_' )
125
soname=$( objdump -x "$lib" |grep SONAME | awk '{print $2}' )
126
outfile="$outdir/`basename "$soname"`.stub.c"
130
if $using_partial_map; then
131
functions=$( grep "^F " "$partial_map" | cut -d' ' -f2 )
132
variables=$( grep "^V " "$partial_map" | cut -d' ' -f2 )
134
functions=$( nm --extern-only -D "$lib" | awk '{ if (($2 == "T") || ($2 == "W")) print $3; }' | LC_ALL=C grep -v '\(\<_init\>\|\<_fini\>\)' | LC_ALL=C sort -u )
135
variables=$( nm --extern-only -D "$lib" | awk '{ if (($2 == "D") || ($2 == "G") || ($2 == "B") || ($2 == "V")) print $3; }' | LC_ALL=C sort -u )
137
if $using_minimal_list; then
138
functions="$functions
139
$( nm `echo "$object_list"` | awk '{ if ($1 == "U") print $2; }' | LC_ALL=C sort -u )"
140
functions=$( echo "$functions" | LC_ALL=C sort | LC_ALL=C uniq -d )
141
variables="$variables
142
$( nm `echo "$object_list"` | awk '{ if ($1 == "U") print $2; }' | LC_ALL=C sort -u )"
143
variables=$( echo "$variables" | LC_ALL=C sort | LC_ALL=C uniq -d )
146
if [ "$functions" == "" ] && [ "$variables" == "" ]; then
147
# Nothing will be used, so do nothing for that lib
151
cat <<EOF >"$outfile"
152
/* automatically generated: `date` by `id -un`@`uname -n`, do not edit
154
* Built by relaytool, a program for building delay-load jumptables
155
* relaytool is (C) 2004 Mike Hearn <mike@navi.cx>
156
* See http://autopackage.org/ for details.
164
#include <sys/mman.h>
171
static char *functions[] = {
174
for s in $functions; do
175
echo " \"$s\"," >>"$outfile"
177
echo " 0" >>"$outfile"
179
cat <<EOF >>"$outfile"
182
static char *variables[] = {
185
for s in $variables; do
186
echo " \"$s\"," >>"$outfile"
188
echo " 0" >>"$outfile"
190
cat <<EOF >>"$outfile"
193
/* 1 if present, 0 if not */
194
int ${libname}_is_present = 0;
196
static void *handle = 0;
198
/* 1 if present, 0 if not, 0 with warning to stderr if lib not present or symbol not found */
199
int ${libname}_symbol_is_present(char *s)
203
if( !${libname}_is_present ) {
204
fprintf(stderr, "%s: relaytool: `basename "$lib"` not present so cannot check for symbol %s.\n", getenv("_"), s);
205
fprintf(stderr, "%s: relaytool: This probably indicates a bug in the application, please report.\n", getenv("_"));
210
while (functions[i++]) if (!strcmp( functions[i - 1], s )) return ptrs[i - 1] > 0 ? 1 : 0;
212
while (variables[i++]) if (!strcmp( variables[i - 1], s )) return dlsym( handle, s ) > 0 ? 1 : 0;
214
fprintf( stderr, "%s: relaytool: %s is an unknown symbol in `basename "$lib"`.\n", getenv("_"), s );
215
fprintf( stderr, "%s: relaytool: If you are the developer of this program, please correct the symbol name or rerun relaytool.\n", getenv("_") );
219
__attribute__((noreturn)) void _relaytool_stubcall_${libname}(int offset)
221
fprintf( stderr, "%s: relaytool: stub call to `basename "${lib}"`:%s, aborting.\n", getenv("_"),
222
functions[offset / sizeof(void*)] );
226
#if defined( __i386__ )
227
#define FIXUP_GOT_RELOC(sym, addr) \\
228
asm("\tmovl %0, %%eax\n" \\
229
"\tmovl %%eax, " sym "@GOT(%%ebx)\n" : : "r" (addr));
230
#elif defined( __powerpc__ )
232
/* The PowerPC ELF ABI is a twisted nightmare. Until I figure it out,
233
for now we don't support GOT fixup on this architecture */
235
#error Variables are not currently supported on PowerPC
237
#elif defined( __x86_64__ )
238
#define FIXUP_GOT_RELOC(sym, addr) \\
239
asm("\tmovq %0, %%rax\n" \\
240
"\tmovq %%rax, " sym "@GOT(%%rbx)\n" : : "r" (addr));
242
#error Please define FIXUP_GOT_RELOC for your architecture
245
void __attribute__((constructor)) _relaytool_init_${libname}()
249
ptrs = malloc( sizeof(functions) );
250
memset( ptrs, 0, sizeof(functions) );
252
if $using_multilink; then
253
echo -n "char *multilink_libs[${#multilinklist[@]}] = {" | cat >> "$outfile"
254
for l in ${multilinklist[@]}; do
255
echo -n "\"$l\"" | cat >> "$outfile";
256
if [[ "$l" != "${multilinklist[${#multilinklist[@]}-1]}" ]]; then
257
echo -n ", " | cat >> "$outfile";
259
echo "};" | cat >> "$outfile"
262
echo 'int multilink_count=0;' | cat >> "$outfile"
264
echo 'while (!handle) {
265
handle = dlopen(multilink_libs[multilink_count++], RTLD_LAZY );' | cat >> "$outfile"
266
echo "if (multilink_count==${#multilinklist[@]}) break;}"| cat >> "$outfile"
268
echo "handle = dlopen( \"$soname\", RTLD_LAZY );" | cat >> "$outfile"
270
cat <<EOF >>"$outfile"
273
${libname}_is_present = 1;
275
/* build function jumptable */
276
while (functions[i++]) ptrs[i - 1] = dlsym( handle, functions[i - 1] );
280
if [ "$variables" != "" ]; then echo " /* now fixup the global offset table for variable imports */" >>"$outfile"; fi
281
for s in $variables; do
282
echo " FIXUP_GOT_RELOC( \"$s\", dlsym(handle, \"$s\") );" >>"$outfile"
285
cat <<EOF >>"$outfile"
288
#if defined( __i386__ )
290
#define JUMP_SLOT(name, index) \\
291
asm(".section .text." name ", \"ax\", @progbits\n" \\
292
".globl " name "\n" \\
293
".hidden " name "\n" \\
294
" .type " name ", @function\n" \\
296
" movl ptrs, %eax\n" \\
297
" movl " #index "(%eax), %eax\n" \\
298
" test %eax, %eax\n" \\
299
" jnz JS" #index "\n" \\
300
" push \$" #index "\n" \\
301
" call _relaytool_stubcall_${libname}\n" \\
302
"JS" #index ": jmp *%eax\n");
305
#elif defined( __x86_64__ )
307
#define JUMP_SLOT(name, index) \\
308
asm(".section .text." name ", \"ax\", @progbits\n" \\
309
".globl " name "\n" \\
310
".hidden " name "\n" \\
311
" .type " name ", @function\n" \\
313
" movq ptrs, %r11\n" \\
314
" movq " #index "(%r11), %r11\n" \\
315
" test %r11, %r11\n" \\
316
" jnz JS" #index "\n" \\
317
" push $" #index "\n" \\
318
" call _relaytool_stubcall_${libname}\n" \\
319
"JS" #index ": jmp *%r11\n");
320
#elif defined( __powerpc__ )
322
#define JUMP_SLOT(name, index) \ \
323
asm(".section .text." name ", \"ax\", @progbits\n" \\
324
".globl " name "\n" \\
325
".hidden " name "\n" \\
326
" .type " name ", @function\n" \\
328
" lis r11, ptrs@ha\n" \\
329
" lwz r11, " #index "(r11)\n" \\
330
" cmpi cr0,r11,0\n" \\
334
"1: li r3, " #index "\n" \\
335
" b _relaytool_stubcall_${libname}\n" \\
339
#error Please define JUMP_SLOT for your architecture
342
/* define placeholders for the variable imports: their type doesn't matter,
343
however we must restrict ELF symbol scope to prevent the definition in the imported
344
shared library being bound to this dummy symbol (not all libs are compiled -Bsymbolic)
348
for s in $variables; do
349
echo "int $s __attribute__(( visibility(\"hidden\") )) = -1;" >>"$outfile"
352
cat <<EOF >>"$outfile"
354
/* define each jump slot in its own section. this increases generated code
355
size, but it means unused slots can be deleted by the linker when
356
--gc-sections is used.
360
# now generate the stubs
362
for s in $functions; do
363
echo "JUMP_SLOT(\"$s\", $[c * $arch_ptr_size]);" >>"$outfile"
369
cat <<EOF >>"$outfile"
378
function fakerelay() {
380
libname=$( echo $( basename "$lib" ) | sed 's/\.so.*//' | tr '-' '_' | tr '.' '_' )
381
soname=$( objdump -x "$lib" |grep SONAME | awk '{print $2}' )
382
outfile="$outdir/`basename "$soname"`.stub.c"
386
cat <<EOF >"$outfile"
387
/* automatically generated: `date` by `id -un`@`uname -n`, do not edit
389
* Built by relaytool, a program for building delay-load jumptables
390
* relaytool is (C) 2004 Mike Hearn <mike@navi.cx>
391
* See http://autopackage.org/ for details.
398
/* 1 if present, 0 if not */
399
int ${libname}_is_present = 1;
401
/* 1 if present, 0 if not, 0 with warning to stderr if lib not present or symbol not found */
402
int ${libname}_symbol_is_present(char * s)
419
i386 | i486 | i586 | i686 )
429
searchpath=( "/usr/lib" "/usr/local/lib" "/lib" `pwd` )
435
while (( i <= $# )); do
438
if [ "${a:0:2}" == "-L" ]; then
439
searchpath[${#searchpath}]="${a:2}"
440
echo -n "$a " # copy to stdout
442
elif [ "$a" == "--replace-all-libs" ]; then
445
elif [ "$a" == "--partial-map" ]; then
446
using_partial_map=true
450
elif [ "$a" == "--minimal-list" ]; then
451
using_minimal_list=true
455
elif [ "$a" == "--no-replace" ]; then
458
elif [ "$a" == "--multilink" ]; then
461
while [[ $i -lt $# && ${!i:0:2} != "--" ]]; do
462
multilinklist[${#multilinklist[@]}]="${!i}"
465
continue # $i has already been incremented, just continue with the loop
467
elif [ "$a" == "--relay" ]; then
469
relaylist[${#relaylist[@]}]="${!i}"
471
elif [ "$a" == "--out-dir" ]; then
475
elif [ "$a" == "-ldl" ]; then
476
# libdl won't ever be supported by relaytool, so just pass it to stdout
479
elif [ "${a:0:2}" == "-l" ]; then
482
# is this lib meant to be relayed?
483
if $replace_all; then
487
for b in ${relaylist[@]}; do
488
if [ "$b" == "$lib" ]; then
494
if $found && $arch_ok; then
496
# yes, so let's find its absolute filename by checking in each search path directory
498
for d in ${searchpath[@]}; do
499
if [ -e "$d/lib$lib.so" ]; then
501
absname=$( readfinallink "$d/lib$lib.so" )
502
if [ $? != 0 ] || [ ! -f "$absname" ]; then
503
error broken symlink "$absname"
506
stubfile=$( relay "$absname" )
508
# now we have to compile the stub
510
stubobj=$( echo "$stubfile" | sed 's/\.c$/\.o/' )
511
# remove -include flags from CFLAGS, if any
512
CFLAGS=$( echo $CFLAGS | sed 's/-include .*\.h//g' )
513
if [ -e /dev/tty ]; then
514
${CC:-gcc} ${CFLAGS} -fPIC -c -o "$stubobj" "$stubfile" 2>/dev/tty
516
${CC:-gcc} ${CFLAGS} -fPIC -c -o "$stubobj" "$stubfile"
531
error could not find "$lib" in search path
533
elif $found && ! $arch_ok; then
534
# yes, so let's find its absolute filename by checking in each search path directory
536
for d in ${searchpath[@]}; do
537
if [ -e "$d/lib$lib.so" ]; then
539
absname=$( readfinallink "$d/lib$lib.so" )
540
if [ $? != 0 ] || [ ! -f "$absname" ]; then
541
error broken symlink "$absname"
544
# Create a stub C source that just contains dummy
545
# libwhatever_... support functions
546
stubfile=$( fakerelay "$absname" )
548
# now we have to compile the stub
550
stubobj=$( echo "$stubfile" | sed 's/\.c$/\.o/' )
551
# remove -include flags from CFLAGS, if any
552
CFLAGS=$( echo $CFLAGS | sed 's/-include .*\.h//g' )
553
if [ -e /dev/tty ]; then
554
${CC:-gcc} ${CFLAGS} -fPIC -c -o "$stubobj" "$stubfile" 2>/dev/tty
556
${CC:-gcc} ${CFLAGS} -fPIC -c -o "$stubobj" "$stubfile"
571
error could not find "$lib" in search path
578
# just copy whatever we don't recognise