c5bb4196f4e164a4f5ae1551c63531d5a9d8f951
[platform/upstream/rpm.git] / scripts / find-debuginfo.sh
1 #!/bin/bash
2 #find-debuginfo.sh - automagically generate debug info and file list
3 #for inclusion in an rpm spec file.
4 #
5 # Usage: find-debuginfo.sh [--strict-build-id] [--strip-disable] [--strip-option] [-g] [-r]
6 #                          [-o debugfiles.list]
7 #                          [[-l filelist]... [-p 'pattern'] -o debuginfo.list]
8 #                          [builddir]
9 #
10 # The -g flag says to use strip -g instead of full strip on DSOs.
11 # The --strict-build-id flag says to exit with failure status if
12 # any ELF binary processed fails to contain a build-id note.
13 # The -r flag says to use eu-strip --reloc-debug-sections.
14 #
15 # A single -o switch before any -l or -p switches simply renames
16 # the primary output file from debugfiles.list to something else.
17 # A -o switch that follows a -p switch or some -l switches produces
18 # an additional output file with the debuginfo for the files in
19 # the -l filelist file, or whose names match the -p pattern.
20 # The -p argument is an grep -E -style regexp matching the a file name,
21 # and must not use anchors (^ or $).
22 #
23 # All file names in switches are relative to builddir (. if not given).
24 #
25
26 # With -g arg, pass it to strip on libraries.
27 strip_g=false
28
29 # with -r arg, pass --reloc-debug-sections to eu-strip.
30 strip_r=false
31
32 # Barf on missing build IDs.
33 strict=false
34
35 # With --strip-disable arg, no strip
36 strip_disable=false
37
38 # With --strip-option arg, this will be used as arg. of eu-strip
39 strip_option=
40
41 # With --strip-option arg for ko file, this will be used as arg. of eu-strip
42 strip_ko_option=
43
44 BUILDDIR=.
45 out=debugfiles.list
46 nout=0
47 while [ $# -gt 0 ]; do
48   case "$1" in
49   --strict-build-id)
50     strict=true
51     ;;
52   --strip-disable)
53     strip_disable=true
54     ;;
55   *--strip-option*)
56     strip_option=$(echo $1 | sed 's/--strip-option=//')
57     ;;
58   *--strip-ko-option*)
59     strip_ko_option=$(echo $1 | sed 's/--strip-ko-option=//')
60    ;;
61   -g)
62     strip_g=true
63     ;;
64   -o)
65     if [ -z "${lists[$nout]}" -a -z "${ptns[$nout]}" ]; then
66       out=$2
67     else
68       outs[$nout]=$2
69       ((nout++))
70     fi
71     shift
72     ;;
73   -l)
74     lists[$nout]="${lists[$nout]} $2"
75     shift
76     ;;
77   -p)
78     ptns[$nout]=$2
79     shift
80     ;;
81   -r)
82     strip_r=true
83     ;;
84   *)
85     BUILDDIR=$1
86     shift
87     break
88     ;;
89   esac
90   shift
91 done
92
93 i=0
94 while ((i < nout)); do
95   outs[$i]="$BUILDDIR/${outs[$i]}"
96   l=''
97   for f in ${lists[$i]}; do
98     l="$l $BUILDDIR/$f"
99   done
100   lists[$i]=$l
101   ((++i))
102 done
103
104 LISTFILE="$BUILDDIR/$out"
105 SOURCEFILE="$BUILDDIR/debugsources.list"
106 LINKSFILE="$BUILDDIR/debuglinks.list"
107
108 > "$SOURCEFILE"
109 > "$LISTFILE"
110 > "$LINKSFILE"
111
112 debugdir="${RPM_BUILD_ROOT}/usr/lib/debug"
113 tooldir=$(rpm --eval %{_rpmconfigdir})
114
115 strip_to_debug()
116 {
117   local g=
118   local r=
119
120   if test "$strip_disable" = true ; then
121       exit
122   fi
123
124   $strip_r && r=--reloc-debug-sections
125   $strip_g && case "$(file -bi "$2")" in
126   application/x-sharedlib*) g=-g ;;
127   esac
128
129   case $2 in
130       *.ko)
131           # don't attempt to create a minimal backtrace binary for
132           # kernel modules as this just causes the stripping process
133           # to be skipped entirely
134           eu-strip --remove-comment $r $strip_ko_option -f "$1" "$2" || exit
135           ;;
136       *)
137           # Support an alternative way to choose between strip (binutils) and
138           # eu-strip (elfutils) to handle a large shared object (e.g. chromium)
139           if [ "$STRIP_DEFAULT_PACKAGE" != "binutils" ]; then
140               eu-strip --remove-comment $g $strip_option -f "$1" "$2" || exit
141           else
142               cp "$2" "$1"
143               strip --remove-section=.comment $g $strip_option "$2" || exit
144               objcopy --add-gnu-debuglink="$1" "$2" || exit
145           fi
146   esac
147   chmod 444 "$1" || exit
148 }
149
150 # Make a relative symlink to $1 called $3$2
151 shopt -s extglob
152 link_relative()
153 {
154   local t="$1" f="$2" pfx="$3"
155   local fn="${f#/}" tn="${t#/}"
156   local fd td d
157
158   while fd="${fn%%/*}"; td="${tn%%/*}"; [ "$fd" = "$td" ]; do
159     fn="${fn#*/}"
160     tn="${tn#*/}"
161   done
162
163   d="${fn%/*}"
164   if [ "$d" != "$fn" ]; then
165     d="${d//+([!\/])/..}"
166     tn="${d}/${tn}"
167   fi
168
169   mkdir -p "$(dirname "$pfx$f")" && ln -snf "$tn" "$pfx$f"
170 }
171
172 # Make a symlink in /usr/lib/debug/$2 to $1
173 debug_link()
174 {
175   local l="/usr/lib/debug$2"
176   local t="$1"
177   echo >> "$LINKSFILE" "$l $t"
178
179   # this should correspond to what brp-symlink is doing
180   case $t in
181       /usr*)
182           link_relative "$t" "$l" "$RPM_BUILD_ROOT"
183           ;;
184       *)
185           if [ ! -e $t ]; then
186               link_relative "$t" "$l" "$RPM_BUILD_ROOT"
187           else
188               mkdir -p "$(dirname "$RPM_BUILD_ROOT$l")" && \
189                   ln -snf "$t" "$RPM_BUILD_ROOT$l"
190           fi
191           ;;
192   esac
193 }
194
195 # Provide .2, .3, ... symlinks to all filename instances of this build-id.
196 make_id_dup_link()
197 {
198   # See https://bugzilla.redhat.com/show_bug.cgi?id=641377 for the reasoning, 
199   # but it has seveal drawbacks as we would need to split the .1 suffixes into 
200   # different subpackages and it's about impossible to predict the number
201   # -> perhaps later
202   return
203   local id="$1" file="$2" idfile
204
205   local n=1
206   while true; do
207     idfile=".build-id/${id:0:2}/${id:2}.$n"
208     [ $# -eq 3 ] && idfile="${idfile}$3"
209     if [ ! -L "$RPM_BUILD_ROOT/usr/lib/debug/$idfile" ]; then
210       break
211     fi
212     n=$[$n+1]
213   done
214   debug_link "$file" "/$idfile"
215 }
216
217 # Compare two binaries but ignore the .note.gnu.build-id section
218 elfcmp()
219 {
220   local tmp1=$(mktemp -t ${1##*/}.XXXXXX)
221   local tmp2=$(mktemp -t ${2##*/}.XXXXXX)
222
223   objcopy -R .note.gnu.build-id -R .gnu_debuglink $1 $tmp1
224   objcopy -R .note.gnu.build-id -R .gnu_debuglink $2 $tmp2
225   cmp -s $tmp1 $tmp2
226   local res=$?
227   rm -f $tmp1 $tmp2
228   return $res
229 }
230
231 # Make a build-id symlink for id $1 with suffix $3 to file $2.
232 make_id_link()
233 {
234   local id="$1" file="$2"
235   local idfile=".build-id/${id:0:2}/${id:2}"
236   [ $# -eq 3 ] && idfile="${idfile}$3"
237   local root_idfile="$RPM_BUILD_ROOT/usr/lib/debug/$idfile"
238
239   if [ ! -L "$root_idfile" ]; then
240     debug_link "$file" "/$idfile"
241     return
242   fi
243
244   make_id_dup_link "$@"
245
246   [ $# -eq 3 ] && return 0
247
248   local other=$(readlink -m "$root_idfile")
249   other=${other#$RPM_BUILD_ROOT}
250   if cmp -s "$RPM_BUILD_ROOT$other" "$RPM_BUILD_ROOT$file" ||
251      elfcmp "$RPM_BUILD_ROOT$other" "$RPM_BUILD_ROOT$file" ; then
252     # Two copies.  Maybe one has to be setuid or something.
253     echo >&2 "*** WARNING: identical binaries are copied, not linked:"
254     echo >&2 "        $file"
255     echo >&2 "   and  $other"
256   else
257     # This is pathological, break the build.
258     echo >&2 "*** ERROR: same build ID in nonidentical files!"
259     echo >&2 "        $file"
260     echo >&2 "   and  $other"
261     exit 2
262   fi
263 }
264
265 get_debugfn()
266 {
267   dn=$(dirname "${1#$RPM_BUILD_ROOT}")
268 # Do not strip existing .debug suffixes
269   bn=$(basename "$1").debug
270
271   debugdn=${debugdir}${dn}
272   debugfn=${debugdn}/${bn}
273 }
274
275 set -o pipefail
276
277 strict_error=ERROR
278 $strict || strict_error=WARNING
279
280 # Strip ELF binaries (and no static libraries)
281 find $RPM_BUILD_ROOT ! -path "${debugdir}/*.debug" -type f \( -perm /111 -or -name "*.so*" -or -name "*.ko" \) ! -name "*.a" -print0 | sort -z |
282 xargs --no-run-if-empty -0 stat -c '%h %D_%i %n' |
283 while read nlinks inum f; do
284   case $(objdump -h $f 2>/dev/null | sed -n '/^Sections:/,$p' | egrep -o '(debug[\.a-z_]*|gnu.version)') in
285     *debuglink*) continue ;;
286     *debug*) ;;
287     *gnu.version*)
288         echo "WARNING: "`echo $f | sed -e "s,^$RPM_BUILD_ROOT/*,/,"`" is already stripped!"
289         continue
290         ;;
291     *) continue ;;
292   esac
293   get_debugfn "$f"
294   [ -f "${debugfn}" ] && continue
295
296   # If this file has multiple links, keep track and make
297   # the corresponding .debug files all links to one file too.
298   if [ $nlinks -gt 1 ]; then
299     eval linked=\$linked_$inum
300     if [ -n "$linked" ]; then
301       eval id=\$linkedid_$inum
302       make_id_dup_link "$id" "$dn/$(basename $f)"
303       make_id_dup_link "$id" "/usr/lib/debug$dn/$bn" .debug
304       link=$debugfn
305       get_debugfn "$linked"
306       echo "hard linked $link to $debugfn"
307       mkdir -p "$(dirname "$link")" && ln -nf "$debugfn" "$link"
308       continue
309     else
310       eval linked_$inum=\$f
311       echo "file $f has $[$nlinks - 1] other hard links"
312     fi
313   fi
314
315   echo "extracting debug info from $f"
316   id=$($(DEBUGEDIT=$(which debugedit 2>/dev/null); \
317       echo ${DEBUGEDIT:-${tooldir}/debugedit}) -b "$RPM_BUILD_DIR" \
318       -d /usr/src/debug -i -l "$SOURCEFILE" "$f") || exit
319   if [ $nlinks -gt 1 ]; then
320     eval linkedid_$inum=\$id
321   fi
322   if [ -z "$id" ]; then
323     echo >&2 "*** ${strict_error}: No build ID note found in $f"
324     $strict && exit 2
325   fi
326
327   [ -x /usr/bin/gdb-add-index ] && /usr/bin/gdb-add-index "$f" > /dev/null 2>&1
328
329   # A binary already copied into /usr/lib/debug doesn't get stripped,
330   # just has its file names collected and adjusted.
331   case "$dn" in
332   /usr/lib/debug/*)
333     [ -z "$id" ] || make_id_link "$id" "$dn/$(basename $f)"
334     continue ;;
335   esac
336
337   mkdir -p "${debugdn}"
338   if [ -e "${BUILDDIR}/Kconfig" ] ; then
339       mode=$(stat -c %a "$f")
340       chmod +w "$f"
341       objcopy --only-keep-debug $f $debugfn || :
342       (
343           shopt -s extglob
344           strip_option="--strip-all"
345           case "$f" in
346               *.ko)
347                   strip_option="--strip-debug" ;;
348               *$STRIP_KEEP_SYMTAB*)
349                   if test -n "$STRIP_KEEP_SYMTAB"; then
350                       strip_option="--strip-debug"
351                   fi
352                   ;;
353           esac
354           if test "$NO_DEBUGINFO_STRIP_DEBUG" = true ; then
355               strip_option=
356           fi
357           if test "$strip_disable" = true ; then
358               strip_option=
359           fi
360           objcopy --add-gnu-debuglink=$debugfn -R .comment -R .GCC.command.line $strip_option $f
361           chmod $mode $f
362       ) || :
363   else
364       if test -w "$f"; then
365           strip_to_debug "${debugfn}" "$f"
366       else
367           chmod u+w "$f"
368           strip_to_debug "${debugfn}" "$f"
369           chmod u-w "$f"
370       fi
371   fi
372
373   if [ -n "$id" ]; then
374     make_id_link "$id" "$dn/$(basename $f)"
375     make_id_link "$id" "/usr/lib/debug$dn/$bn" .debug
376   fi
377 done || exit
378
379 # We used to make a .debug symlink for each symlink whose target
380 # has a .debug file to that file.  This is not necessary because
381 # the debuglink section contains only the destination of those links.
382 # Creating those links anyway results in debuginfo packages for
383 # devel packages just because of the .so symlinks in them.
384
385 if [ -s "$SOURCEFILE" ]; then
386   mkdir -p "${RPM_BUILD_ROOT}/usr/src/debug"
387   # Get package name from directory and then filter out all files not
388   # starting with this name
389   pn=$(basename "$BUILDDIR")
390   LC_ALL=C sort -z -u "$SOURCEFILE" | grep -E -v -z '(<internal>|<built-in>)$' |
391   grep -E -z "^${pn}" |
392   (cd "$RPM_BUILD_DIR"; cpio -pd0mL "${RPM_BUILD_ROOT}/usr/src/debug")
393   # stupid cpio creates new directories in mode 0700, fixup
394   find "${RPM_BUILD_ROOT}/usr/src/debug" -type d -print0 |
395   xargs --no-run-if-empty -0 chmod a+rx
396   find "${RPM_BUILD_ROOT}/usr/src/debug" -type f -print0 |
397   xargs --no-run-if-empty -0 chmod a+r
398 fi
399
400 if [ -d "${RPM_BUILD_ROOT}/usr/lib" -o -d "${RPM_BUILD_ROOT}/usr/src" ]; then
401   ((nout > 0)) ||
402   test ! -d "${RPM_BUILD_ROOT}/usr/lib" ||
403   (cd "${RPM_BUILD_ROOT}/usr/lib"; test ! -d debug || find debug -type d) |
404   sed 's,^,%dir /usr/lib/,' >> "$LISTFILE"
405
406   (cd "${RPM_BUILD_ROOT}/usr"
407    test ! -d lib/debug || find lib/debug ! -type d
408   ) | sed 's,^,/usr/,' >> "$LISTFILE"
409 fi
410
411 : > "$SOURCEFILE"
412 if [ -d "${RPM_BUILD_ROOT}/usr/src" ]; then
413   (cd "${RPM_BUILD_ROOT}/usr"
414    test ! -d src/debug || find src/debug -mindepth 1 -maxdepth 1
415   ) | sed 's,^,/usr/,' >> "$SOURCEFILE"
416 fi
417
418 # Append to $1 only the lines from stdin not already in the file.
419 append_uniq()
420 {
421   grep -F -f "$1" -x -v >> "$1"
422 }
423
424 # Helper to generate list of corresponding .debug files from a file list.
425 filelist_debugfiles()
426 {
427   local extra="$1"
428   shift
429   sed 's/^%[a-z0-9_][a-z0-9_]*([^)]*) *//
430 s/^%[a-z0-9_][a-z0-9_]* *//
431 /^$/d
432 '"$extra" "$@"
433 }
434
435 # Write an output debuginfo file list based on given input file lists.
436 filtered_list()
437 {
438   local out="$1"
439   shift
440   test $# -gt 0 || return
441   grep -F -f <(filelist_debugfiles 's,^.*$,/usr/lib/debug&.debug,' "$@") \
442         -x $LISTFILE >> $out
443   sed -n -f <(filelist_debugfiles 's/[\\.*+#]/\\&/g
444 h
445 s,^.*$,s# &$##p,p
446 g
447 s,^.*$,s# /usr/lib/debug&.debug$##p,p
448 ' "$@") "$LINKSFILE" | append_uniq "$out"
449 }
450
451 # Write an output debuginfo file list based on an grep -E -style regexp.
452 pattern_list()
453 {
454   local out="$1" ptn="$2"
455   test -n "$ptn" || return
456   grep -E -x -e "$ptn" "$LISTFILE" >> "$out"
457   sed -n -r "\#^$ptn #s/ .*\$//p" "$LINKSFILE" | append_uniq "$out"
458 }
459
460 #
461 # When given multiple -o switches, split up the output as directed.
462 #
463 i=0
464 while ((i < nout)); do
465   > ${outs[$i]}
466   filtered_list ${outs[$i]} ${lists[$i]}
467   pattern_list ${outs[$i]} "${ptns[$i]}"
468   grep -Fvx -f ${outs[$i]} "$LISTFILE" > "${LISTFILE}.new"
469   mv "${LISTFILE}.new" "$LISTFILE"
470   ((++i))
471 done
472 if ((nout > 0)); then
473   # Now add the right %dir lines to each output list.
474   (cd "${RPM_BUILD_ROOT}"; find usr/lib/debug -type d) |
475   sed 's#^.*$#\\@^/&/@{h;s@^.*$@%dir /&@p;g;}#' |
476   LC_ALL=C sort -ur > "${LISTFILE}.dirs.sed"
477   i=0
478   while ((i < nout)); do
479     sed -n -f "${LISTFILE}.dirs.sed" "${outs[$i]}" | sort -u > "${outs[$i]}.new"
480     cat "${outs[$i]}" >> "${outs[$i]}.new"
481     mv -f "${outs[$i]}.new" "${outs[$i]}"
482     ((++i))
483   done
484   sed -n -f "${LISTFILE}.dirs.sed" "${LISTFILE}" | sort -u > "${LISTFILE}.new"
485   cat "$LISTFILE" >> "${LISTFILE}.new"
486   mv "${LISTFILE}.new" "$LISTFILE"
487 fi