Version 1.7.16.
[libguestfs.git] / relink-static.sh
1 #!/bin/bash -
2 # Copyright (C) 2010 Red Hat Inc.
3 #
4 # This program is free software; you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation; either version 2 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17 #
18 # Written by Richard W.M. Jones <rjones@redhat.com>
19 #
20 # Take a dynamically linked ELF binary and relink it, maximizing the
21 # use of static libraries.
22 #
23 # Example:
24 #   binary foo
25 #            ---> dynamically links to libbar.so.0
26 #            ---> dynamically links to libzab.so.3
27 # If libbar.a is available, but there is no libzab.a, then we would
28 # end up with:
29 #   binary foo.static with libbar.a statically inside it
30 #            ---> still dynamically linking with libzab.so.3
31 #
32 # We need to have access to the original link command.  This script
33 # works by post-processing it to find the '-lbar' arguments, which are
34 # replaced sometimes by direct static library names.
35 #
36 # Therefore to use this, you have to add this rule to your
37 # Makefile.am:
38 #
39 # foo.static$(EXEEXT): $(foo_OBJECTS) $(foo_DEPENDENCIES)
40 #   relink-static.sh \
41 #   $(foo_LINK) $(foo_OBJECTS) -static $(foo_LDADD) $(foo_LIBS)
42
43 declare -a args
44
45 i=0
46 for arg; do
47     case "$arg" in
48     -l*)    # get just the library name (eg. "xml2")
49             lib=${arg:2}
50             # does a static version exist?
51             for d in /usr/local/lib{64,} /usr/lib{64,} /lib{64,}; do
52                 path="$d/lib$lib.a"
53                 if [ -f "$path" ]; then
54                     arg="$path"
55                     break
56                 fi
57             done
58             ;;
59     *.la)   # hack around libtool mess
60             d=$(dirname "$arg")
61             b=$(basename "$arg")
62             b=${b:0:${#b}-3}
63             if [ -f "$d/.libs/$b.a" ]; then
64                 arg="$d/.libs/$b.a"
65             fi
66             ;;
67     *) ;;
68     esac
69     args[$i]="$arg"
70     i=$(($i+1))
71 done
72
73 # Run the final command.
74 echo "${args[@]}"
75 "${args[@]}"