While researching 14662 I discovered that strip --only-keep-debug is broken. objcopy.c:is_strip_section_1 doesn't handle, figuratively speaking, !SEC_DEBUGGING && STRIP_NONDEBUG.
Partial patch posted here: http://sourceware.org/ml/binutils/2012-10/msg00019.html
Testcase? I think you misunderstand how --only-keep-debug is supposed to work.
Testcase: gcc -g hello.c && strip --only-keep-debug a.out && (objdump -h a.out | grep text)
Your grep misses the relevant line. Add -w to objdump or -2 to grep options. gcc -g hello.c && (objdump -w -h a.out | grep text) 11 .text 00000430 0000000010000490 0000000010000490 00000490 2**4 CONTENTS, ALLOC, LOAD, READONLY, CODE gcc -g hello.c && strip --only-keep-debug a.out && (objdump -w -h a.out | grep text) 11 .text 00000430 0000000010000490 0000000010000490 00000258 2**4 ALLOC, READONLY, CODE Notice lack of CONTENTS after stripping. Keeping the section headers like this gives a user confidence that a debug file matches his binary..
Clarification in the documentation required then.
It already says it: `--only-keep-debug' Strip a file, removing contents of any sections that would not be ^^^^^^^^^^^^^^^^^ stripped by `--strip-debug' and leaving the debugging sections intact. In ELF files, this preserves all note sections in the output.
I think a few extra words, noting that the contents are gone, but the section headers remain, would go a long way.
I want to ask a related question. Why have these sections to be kept in the section header table while they are made SHT_NOBITS? Don't debuggers/symbolizes just pick sections they are interested in, i.e. .debug_* (and probably SHF_ALLOC .note* if that is why SHF_ALLOC+SHT_NOTE is not made SHT_NOBITS)? In addition, can the program headers be removed? Currently sh_offset in the section header table, and p_offset/p_filesz in the program headers are rewritten. Their values no longer reflect the original values (a consequence of **removed section contents**). If you inspect such separate debug files with readelf -Sl, you can get weird section->segment attribution. I find gdb and lldb are still happy with such separate debug files w/o progam headers.
(In reply to Fangrui Song from comment #8) > I want to ask a related question. Why have these sections to be kept in the > section header table while they are made SHT_NOBITS? It was for matching executables against their debug-only objects. There are better ways to do that, of course, but that was the original motivation.