74acb4cdd1811033e577a470337171c08fd47650
[oweals/busybox.git] / scripts / trylink
1 #!/bin/sh
2
3 debug=false
4
5 try() {
6     added="$1"
7     shift
8     $debug && echo "Trying: $* $added"
9     "$@" $added >busybox.map 2>busybox_ld.err
10 }
11
12 # Sanitize lib list (dups, extra spaces etc)
13 #echo "BBOX_LIB_LIST=$BBOX_LIB_LIST"
14 BBOX_LIB_LIST=`echo "$BBOX_LIB_LIST" | xargs -n1 | sort | uniq | xargs`
15
16 # First link with all libs. If it fails, bail out
17 l_list=`echo "$BBOX_LIB_LIST" | sed -e 's/ / -l/g' -e 's/^/-l/'`
18 echo "Trying libraries: $BBOX_LIB_LIST"
19 try "-Wl,--start-group $l_list -Wl,--end-group" "$@" \
20 || {
21     echo "Failed: $* -Wl,--start-group $l_list -Wl,--end-group"
22     cat busybox_ld.err
23     exit 1
24 }
25 # Hack: we are not supposed to know executable name,
26 # but this hack cuts down link time
27 mv busybox_unstripped busybox_unstripped.tmp
28 mv busybox.map        busybox.map.tmp
29
30 # Now try to remove each lib and build without it.
31 # Stop when no lib can be removed.
32 ever_discarded=false
33 while test "$BBOX_LIB_LIST"; do
34     $debug && echo "Trying libraries: $BBOX_LIB_LIST"
35     all_needed=true
36     for one in $BBOX_LIB_LIST; do
37         without_one=`echo " $BBOX_LIB_LIST " | sed "s/ $one / /g" | xargs`
38         l_list=`echo "$without_one" | sed -e 's/ / -l/g' -e 's/^/-l/'`
39         $debug && echo "Trying -l options: $l_list"
40         if try "-Wl,--start-group $l_list -Wl,--end-group" "$@"; then
41                 echo "Library $one is not needed"
42                 BBOX_LIB_LIST="$without_one"
43                 all_needed=false
44                 ever_discarded=true
45         else
46                 echo "Library $one is needed"
47         fi
48     done
49     # All libs were needed, can't remove any
50     $all_needed && break
51     # If there is no space char, the list has just one lib.
52     # I'm not sure that in this case lib really is 100% needed.
53     # Let's try linking without it anyway... thus commented out.
54     #{ echo "$BBOX_LIB_LIST" | grep -q ' '; } || break
55 done
56
57 mv busybox_unstripped.tmp busybox_unstripped
58 mv busybox.map.tmp        busybox.map
59 $ever_discarded && {
60     # Make the binary with final, minimal list of libs
61     echo "Final link with: $BBOX_LIB_LIST"
62     l_list=`echo "$BBOX_LIB_LIST" | sed -e 's/ / -l/g' -e 's/^/-l/'`
63     try "-Wl,--start-group $l_list -Wl,--end-group" "$@" || exit 1
64 }
65 rm busybox_ld.err
66 exit 0  # Ensure "success" exit code