Merge branch 'master' into devel
[tools/build.git] / 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] [-g] [-r] [-m]
6 #                          [-o debugfiles.list]
7 #                          [--run-dwz] [--dwz-low-mem-die-limit N]
8 #                          [--dwz-max-die-limit N]
9 #                          [[-l filelist]... [-p 'pattern'] -o debuginfo.list]
10 #                          [builddir]
11 #
12 # The -g flag says to use strip -g instead of full strip on DSOs or EXEs.
13 # The --strict-build-id flag says to exit with failure status if
14 # any ELF binary processed fails to contain a build-id note.
15 # The -r flag says to use eu-strip --reloc-debug-sections.
16 #
17 # A single -o switch before any -l or -p switches simply renames
18 # the primary output file from debugfiles.list to something else.
19 # A -o switch that follows a -p switch or some -l switches produces
20 # an additional output file with the debuginfo for the files in
21 # the -l filelist file, or whose names match the -p pattern.
22 # The -p argument is an grep -E -style regexp matching the a file name,
23 # and must not use anchors (^ or $).
24 #
25 # The --run-dwz flag instructs find-debuginfo.sh to run the dwz utility
26 # if available, and --dwz-low-mem-die-limit and --dwz-max-die-limit
27 # provide detailed limits.  See dwz(1) -l and -L option for details.
28 #
29 # All file names in switches are relative to builddir (. if not given).
30 #
31
32 # With -g arg, pass it to strip on libraries or executables.
33 strip_g=false
34
35 # with -r arg, pass --reloc-debug-sections to eu-strip.
36 strip_r=false
37
38 # with -m arg, add minimal debuginfo to binary.
39 include_minidebug=false
40
41 # Barf on missing build IDs.
42 strict=false
43
44 # DWZ parameters.
45 run_dwz=false
46 dwz_low_mem_die_limit=
47 dwz_max_die_limit=
48
49 BUILDDIR=.
50 out=debugfiles.list
51 nout=0
52 while [ $# -gt 0 ]; do
53   case "$1" in
54   --strict-build-id)
55     strict=true
56     ;;
57   --run-dwz)
58     run_dwz=true
59     ;;
60   --dwz-low-mem-die-limit)
61     dwz_low_mem_die_limit=$2
62     shift
63     ;;
64   --dwz-max-die-limit)
65     dwz_max_die_limit=$2
66     shift
67     ;;
68   -g)
69     strip_g=true
70     ;;
71   -m)
72     include_minidebug=true
73     ;;
74   -o)
75     if [ -z "${lists[$nout]}" -a -z "${ptns[$nout]}" ]; then
76       out=$2
77     else
78       outs[$nout]=$2
79       ((nout++))
80     fi
81     shift
82     ;;
83   -l)
84     lists[$nout]="${lists[$nout]} $2"
85     shift
86     ;;
87   -p)
88     ptns[$nout]=$2
89     shift
90     ;;
91   -r)
92     strip_r=true
93     ;;
94   *)
95     BUILDDIR=$1
96     shift
97     break
98     ;;
99   esac
100   shift
101 done
102
103 i=0
104 while ((i < nout)); do
105   outs[$i]="$BUILDDIR/${outs[$i]}"
106   l=''
107   for f in ${lists[$i]}; do
108     l="$l $BUILDDIR/$f"
109   done
110   lists[$i]=$l
111   ((++i))
112 done
113
114 LISTFILE="$BUILDDIR/$out"
115 SOURCEFILE="$BUILDDIR/debugsources.list"
116 LINKSFILE="$BUILDDIR/debuglinks.list"
117 ELFBINSFILE="$BUILDDIR/elfbins.list"
118
119 echo "/usr" > "$SOURCEFILE"
120 echo "/usr" > "$LISTFILE"
121 echo "/usr" > "$LINKSFILE"
122 echo "/usr" > "$ELFBINSFILE"
123
124 debugdir="${RPM_BUILD_ROOT}/usr/lib/debug"
125
126 strip_to_debug()
127 {
128   local g=
129   local r=
130   $strip_r && r=--reloc-debug-sections
131   $strip_g && case "$(file -bi "$2")" in
132   application/x-sharedlib*) g=-g ;;
133   application/x-executable*) g=-g ;;
134   esac
135   eu-strip --remove-comment $r $g -f "$1" "$2" || exit
136   chmod 444 "$1" || exit
137 }
138
139 add_minidebug()
140 {
141   local debuginfo="$1"
142   local binary="$2"
143
144   local dynsyms=`mktemp`
145   local funcsyms=`mktemp`
146   local keep_symbols=`mktemp`
147   local mini_debuginfo=`mktemp`
148
149   # Extract the dynamic symbols from the main binary, there is no need to also have these
150   # in the normal symbol table
151   nm -D "$binary" --format=posix --defined-only | awk '{ print $1 }' | sort > "$dynsyms"
152   # Extract all the text (i.e. function) symbols from the debuginfo 
153   nm "$debuginfo" --format=posix --defined-only | awk '{ if ($2 == "T" || $2 == "t") print $1 }' | sort > "$funcsyms"
154   # Keep all the function symbols not already in the dynamic symbol table
155   comm -13 "$dynsyms" "$funcsyms" > "$keep_symbols"
156   # Copy the full debuginfo, keeping only a minumal set of symbols and removing some unnecessary sections
157   objcopy -S --remove-section .gdb_index --remove-section .comment --keep-symbols="$keep_symbols" "$debuginfo" "$mini_debuginfo" &> /dev/null
158   #Inject the compressed data into the .gnu_debugdata section of the original binary
159   xz "$mini_debuginfo"
160   mini_debuginfo="${mini_debuginfo}.xz"
161   objcopy --add-section .gnu_debugdata="$mini_debuginfo" "$binary"
162   rm -f "$dynsyms" "$funcsyms" "$keep_symbols" "$mini_debuginfo"
163 }
164
165 # Make a relative symlink to $1 called $3$2
166 shopt -s extglob
167 link_relative()
168 {
169   local t="$1" f="$2" pfx="$3"
170   local fn="${f#/}" tn="${t#/}"
171   local fd td d
172
173   while fd="${fn%%/*}"; td="${tn%%/*}"; [ "$fd" = "$td" ]; do
174     fn="${fn#*/}"
175     tn="${tn#*/}"
176   done
177
178   d="${fn%/*}"
179   if [ "$d" != "$fn" ]; then
180     d="${d//+([!\/])/..}"
181     tn="${d}/${tn}"
182   fi
183
184   mkdir -p "$(dirname "$pfx$f")" && ln -snf "$tn" "$pfx$f"
185 }
186
187 # Make a symlink in /usr/lib/debug/$2 to $1
188 debug_link()
189 {
190   local l="/usr/lib/debug$2"
191   local t="$1"
192   echo >> "$LINKSFILE" "$l $t"
193   link_relative "$t" "$l" "$RPM_BUILD_ROOT"
194 }
195
196 # Provide .2, .3, ... symlinks to all filename instances of this build-id.
197 make_id_dup_link()
198 {
199   local id="$1" file="$2" idfile
200
201   local n=1
202   while true; do
203     idfile=".build-id/${id:0:2}/${id:2}.$n"
204     [ $# -eq 3 ] && idfile="${idfile}$3"
205     if [ ! -L "$RPM_BUILD_ROOT/usr/lib/debug/$idfile" ]; then
206       break
207     fi
208     n=$[$n+1]
209   done
210   debug_link "$file" "/$idfile"
211 }
212
213 # Make a build-id symlink for id $1 with suffix $3 to file $2.
214 make_id_link()
215 {
216   local id="$1" file="$2"
217   local idfile=".build-id/${id:0:2}/${id:2}"
218   [ $# -eq 3 ] && idfile="${idfile}$3"
219   local root_idfile="$RPM_BUILD_ROOT/usr/lib/debug/$idfile"
220
221   if [ ! -L "$root_idfile" ]; then
222     debug_link "$file" "/$idfile"
223     return
224   fi
225
226   make_id_dup_link "$@"
227
228   [ $# -eq 3 ] && return 0
229
230   local other=$(readlink -m "$root_idfile")
231   other=${other#$RPM_BUILD_ROOT}
232   if cmp -s "$root_idfile" "$RPM_BUILD_ROOT$file" ||
233      eu-elfcmp -q "$root_idfile" "$RPM_BUILD_ROOT$file" 2> /dev/null; then
234     # Two copies.  Maybe one has to be setuid or something.
235     echo >&2 "*** WARNING: identical binaries are copied, not linked:"
236     echo >&2 "        $file"
237     echo >&2 "   and  $other"
238   else
239     # This is pathological, break the build.
240     echo >&2 "*** ERROR: same build ID in nonidentical files!"
241     echo >&2 "        $file"
242     echo >&2 "   and  $other"
243     exit 2
244   fi
245 }
246
247 get_debugfn()
248 {
249   dn=$(dirname "${1#$RPM_BUILD_ROOT}")
250   bn=$(basename "$1" .debug).debug
251
252   debugdn=${debugdir}${dn}
253   debugfn=${debugdn}/${bn}
254 }
255
256 set -o pipefail
257
258 strict_error=ERROR
259 $strict || strict_error=WARNING
260
261 # Strip ELF binaries
262 find "$RPM_BUILD_ROOT" ! -path "${debugdir}/*.debug" -type f \
263                      \( -perm -0100 -or -perm -0010 -or -perm -0001 \) \
264                      -print |
265 file -N -f - | sed -n -e 's/^\(.*\):[   ]*.*ELF.*, not stripped.*/\1/p' |
266 xargs --no-run-if-empty stat -c '%h %D_%i %n' |
267 while read nlinks inum f; do
268   get_debugfn "$f"
269   [ -f "${debugfn}" ] && continue
270
271   # If this file has multiple links, keep track and make
272   # the corresponding .debug files all links to one file too.
273   if [ $nlinks -gt 1 ]; then
274     eval linked=\$linked_$inum
275     if [ -n "$linked" ]; then
276       eval id=\$linkedid_$inum
277       make_id_dup_link "$id" "$dn/$(basename $f)"
278       make_id_dup_link "$id" "/usr/lib/debug$dn/$bn" .debug
279       link=$debugfn
280       get_debugfn "$linked"
281       echo "hard linked $link to $debugfn"
282       mkdir -p "$(dirname "$link")" && ln -nf "$debugfn" "$link"
283       continue
284     else
285       eval linked_$inum=\$f
286       echo "file $f has $[$nlinks - 1] other hard links"
287     fi
288   fi
289
290   echo "extracting debug info from $f"
291   id=$(/usr/lib/rpm/debugedit -b "$RPM_BUILD_DIR" -d /usr/src/debug \
292                               -i -l "$SOURCEFILE" "$f") || exit
293   if [ $nlinks -gt 1 ]; then
294     eval linkedid_$inum=\$id
295   fi
296   if [ -z "$id" ]; then
297     echo >&2 "*** ${strict_error}: No build ID note found in $f"
298     $strict && exit 2
299   fi
300
301   [ -x /usr/bin/gdb-add-index ] && /usr/bin/gdb-add-index "$f" > /dev/null 2>&1
302
303   # A binary already copied into /usr/lib/debug doesn't get stripped,
304   # just has its file names collected and adjusted.
305   case "$dn" in
306   /usr/lib/debug/*)
307     [ -z "$id" ] || make_id_link "$id" "$dn/$(basename $f)"
308     continue ;;
309   esac
310
311   mkdir -p "${debugdn}"
312   if test -w "$f"; then
313     strip_to_debug "${debugfn}" "$f"
314   else
315     chmod u+w "$f"
316     strip_to_debug "${debugfn}" "$f"
317     chmod u-w "$f"
318   fi
319
320   # strip -g implies we have full symtab, don't add mini symtab in that case.
321   $strip_g || ($include_minidebug && add_minidebug "${debugfn}" "$f")
322
323   echo "./${f#$RPM_BUILD_ROOT}" >> "$ELFBINSFILE"
324   
325   if [ -n "$id" ]; then
326     make_id_link "$id" "$dn/$(basename $f)"
327     make_id_link "$id" "/usr/lib/debug$dn/$bn" .debug
328   fi
329 done || exit
330
331 # Invoke the DWARF Compressor utility.
332 if $run_dwz && type dwz >/dev/null 2>&1 \
333    && [ -d "${RPM_BUILD_ROOT}/usr/lib/debug" ]; then
334   dwz_files="`cd "${RPM_BUILD_ROOT}/usr/lib/debug"; find -type f -name \*.debug`"
335   if [ -n "${dwz_files}" ]; then
336     dwz_multifile_name="${RPM_PACKAGE_NAME}-${RPM_PACKAGE_VERSION}-${RPM_PACKAGE_RELEASE}.${RPM_ARCH}"
337     dwz_multifile_suffix=
338     dwz_multifile_idx=0
339     while [ -f "${RPM_BUILD_ROOT}/usr/lib/debug/.dwz/${dwz_multifile_name}${dwz_multifile_suffix}" ]; do
340       let ++dwz_multifile_idx
341       dwz_multifile_suffix=".${dwz_multifile_idx}"
342     done
343     dwz_multfile_name="${dwz_multifile_name}${dwz_multifile_suffix}"
344     dwz_opts="-h -q -r -m .dwz/${dwz_multifile_name}"
345     mkdir -p "${RPM_BUILD_ROOT}/usr/lib/debug/.dwz"
346     [ -n "${dwz_low_mem_die_limit}" ] \
347       && dwz_opts="${dwz_opts} -l ${dwz_low_mem_die_limit}"
348     [ -n "${dwz_max_die_limit}" ] \
349       && dwz_opts="${dwz_opts} -L ${dwz_max_die_limit}"
350     ( cd "${RPM_BUILD_ROOT}/usr/lib/debug" && dwz $dwz_opts $dwz_files )
351     # Remove .dwz directory if empty
352     rmdir "${RPM_BUILD_ROOT}/usr/lib/debug/.dwz" 2>/dev/null
353     if [ -f "${RPM_BUILD_ROOT}/usr/lib/debug/.dwz/${dwz_multifile_name}" ]; then
354       id="`readelf -Wn "${RPM_BUILD_ROOT}/usr/lib/debug/.dwz/${dwz_multifile_name}" \
355              2>/dev/null | sed -n 's/^    Build ID: \([0-9a-f]\+\)/\1/p'`"
356       [ -n "$id" ] \
357         && make_id_link "$id" "/usr/lib/debug/.dwz/${dwz_multifile_name}" .debug
358     fi
359   fi
360 fi
361
362 # dwz invalidates .gnu_debuglink CRC32 in the main files.
363 cat "$ELFBINSFILE" |
364 (cd "$RPM_BUILD_ROOT"; xargs -d '\n' /usr/lib/rpm/sepdebugcrcfix usr/lib/debug)
365
366 # For each symlink whose target has a .debug file,
367 # make a .debug symlink to that file.
368 find "$RPM_BUILD_ROOT" ! -path "${debugdir}/*" -type l -print |
369 while read f
370 do
371   t=$(readlink -m "$f").debug
372   f=${f#$RPM_BUILD_ROOT}
373   t=${t#$RPM_BUILD_ROOT}
374   if [ -f "$debugdir$t" ]; then
375     echo "symlinked /usr/lib/debug$t to /usr/lib/debug${f}.debug"
376     debug_link "/usr/lib/debug$t" "${f}.debug"
377   fi
378 done
379
380 if [ -s "$SOURCEFILE" ]; then
381   mkdir -p "${RPM_BUILD_ROOT}/usr/src/debug"
382   LC_ALL=C sort -z -u "$SOURCEFILE" | grep -E -v -z '(<internal>|<built-in>)$' |
383   (cd "$RPM_BUILD_DIR"; cpio -pd0mL "${RPM_BUILD_ROOT}/usr/src/debug")
384   # stupid cpio creates new directories in mode 0700, fixup
385   find "${RPM_BUILD_ROOT}/usr/src/debug" -type d -print0 |
386   xargs --no-run-if-empty -0 chmod a+rx
387 fi
388
389 if [ -d "${RPM_BUILD_ROOT}/usr/lib" -o -d "${RPM_BUILD_ROOT}/usr/src" ]; then
390   ((nout > 0)) ||
391   test ! -d "${RPM_BUILD_ROOT}/usr/lib" ||
392   (cd "${RPM_BUILD_ROOT}/usr/lib"; find debug -type d) |
393   sed 's,^,%dir /usr/lib/,' >> "$LISTFILE"
394
395   (cd "${RPM_BUILD_ROOT}/usr"
396    test ! -d lib/debug || find lib/debug ! -type d
397    test ! -d src/debug || find src/debug -mindepth 1 -maxdepth 1
398   ) | sed 's,^,/usr/,' >> "$LISTFILE"
399 fi
400
401 # Append to $1 only the lines from stdin not already in the file.
402 append_uniq()
403 {
404   grep -F -f "$1" -x -v >> "$1"
405 }
406
407 # Helper to generate list of corresponding .debug files from a file list.
408 filelist_debugfiles()
409 {
410   local extra="$1"
411   shift
412   sed 's/^%[a-z0-9_][a-z0-9_]*([^)]*) *//
413 s/^%[a-z0-9_][a-z0-9_]* *//
414 /^$/d
415 '"$extra" "$@"
416 }
417
418 # Write an output debuginfo file list based on given input file lists.
419 filtered_list()
420 {
421   local out="$1"
422   shift
423   test $# -gt 0 || return
424   grep -F -f <(filelist_debugfiles 's,^.*$,/usr/lib/debug&.debug,' "$@") \
425         -x $LISTFILE >> $out
426   sed -n -f <(filelist_debugfiles 's/[\\.*+#]/\\&/g
427 h
428 s,^.*$,s# &$##p,p
429 g
430 s,^.*$,s# /usr/lib/debug&.debug$##p,p
431 ' "$@") "$LINKSFILE" | append_uniq "$out"
432 }
433
434 # Write an output debuginfo file list based on an grep -E -style regexp.
435 pattern_list()
436 {
437   local out="$1" ptn="$2"
438   test -n "$ptn" || return
439   grep -E -x -e "$ptn" "$LISTFILE" >> "$out"
440   sed -n -r "\#^$ptn #s/ .*\$//p" "$LINKSFILE" | append_uniq "$out"
441 }
442
443 #
444 # When given multiple -o switches, split up the output as directed.
445 #
446 i=0
447 while ((i < nout)); do
448   > ${outs[$i]}
449   filtered_list ${outs[$i]} ${lists[$i]}
450   pattern_list ${outs[$i]} "${ptns[$i]}"
451   grep -Fvx -f ${outs[$i]} "$LISTFILE" > "${LISTFILE}.new"
452   mv "${LISTFILE}.new" "$LISTFILE"
453   ((++i))
454 done
455 if ((nout > 0)); then
456   # Now add the right %dir lines to each output list.
457   (cd "${RPM_BUILD_ROOT}"; find usr/lib/debug -type d) |
458   sed 's#^.*$#\\@^/&/@{h;s@^.*$@%dir /&@p;g;}#' |
459   LC_ALL=C sort -ur > "${LISTFILE}.dirs.sed"
460   i=0
461   while ((i < nout)); do
462     sed -n -f "${LISTFILE}.dirs.sed" "${outs[$i]}" | sort -u > "${outs[$i]}.new"
463     cat "${outs[$i]}" >> "${outs[$i]}.new"
464     mv -f "${outs[$i]}.new" "${outs[$i]}"
465     ((++i))
466   done
467   sed -n -f "${LISTFILE}.dirs.sed" "${LISTFILE}" | sort -u > "${LISTFILE}.new"
468   cat "$LISTFILE" >> "${LISTFILE}.new"
469   mv "${LISTFILE}.new" "$LISTFILE"
470 fi