Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/ELF/ELFDynEntry.jl
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,11 @@ function ELFDynEntries(oh::ELFHandle)
# Figure out what kind of DynEntry objects we're going to read in
DT = dyn_entry_type(oh)

# Split-debuginfo files keep the `.dynamic` header, but not its contents
if !isnothing(dyn_section) && !section_has_contents(dyn_section)
return ELFDynEntryRef{typeof(oh)}[]
end

# Seek to the proper spot, and read 'em in until we reach a DT_NULL
seekstart(dyn_section)
dts = [ELFDynEntryRef(dyn_section, unpack(oh, DT))]
Expand Down
15 changes: 14 additions & 1 deletion src/ELF/ELFSection.jl
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export ELFSections, ELFSection, ELFSection32, ELFSection64, ELFSectionRef

# Export certain extensions to the base API
export section_type
export section_type, section_has_contents

"""
ELFSections
Expand Down Expand Up @@ -65,6 +65,18 @@ section_size(s::ELFSection) = s.sh_size
section_offset(s::ELFSection) = s.sh_offset
section_address(s::ELFSection) = s.sh_addr

"""
section_has_contents(s::ELFSection)

Return `false` if the given section occupies no space in the file (its type is
`SHT_NOBITS`), so its `sh_offset`/`sh_size` don't describe any bytes that can be
read. Besides `.bss`, this covers the loadable sections (`.dynamic`,
`.dynsym`, `.dynstr`, `.gnu.version_r`, ...) of a split-debuginfo file such as
one made by `objcopy --only-keep-debug`, which keeps their headers but not
their contents.
"""
section_has_contents(s::ELFSection) = section_type(s) != SHT_NOBITS



"""
Expand All @@ -86,6 +98,7 @@ sections(s::ELFSectionRef) = s.sections
handle(s::ELFSectionRef) = handle(sections(s))
section_number(s::ELFSectionRef) = s.idx
@derefmethod section_type(s::ELFSectionRef)
@derefmethod section_has_contents(s::ELFSectionRef)

function section_name(section::ELFSectionRef)
# Actually do the strtab lookup to get the name of this guy
Expand Down
3 changes: 3 additions & 0 deletions src/ELF/ELFSymbol.jl
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ handle(syms::ELFSymbols) = handle(Section(syms))
symtab_entry_type(syms::ELFSymbols) = symtab_entry_type(handle(syms))

function lastindex(syms::ELFSymbols{H}) where {H <: ELFHandle}
# A `SHT_NOBITS` symbol table (e.g. `.dynsym` in a split-debuginfo file)
# has no entries in the file
section_has_contents(Section(syms)) || return 0
sect_size = section_size(Section(syms))
sym_size = sizeof(symtab_entry_type(syms))
return div(sect_size, sym_size)
Expand Down
123 changes: 84 additions & 39 deletions src/ELF/ELFVersion.jl
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ end
@io struct ELFVerNeed{H <: ELFHandle}
vn_version::UInt16
vn_cnt::UInt16
vn_file::UInt16
vn_file::UInt32
vn_aux::UInt32
vn_next::UInt32
end
Expand All @@ -43,47 +43,92 @@ struct ELFVersionNeededEntry{H <: ELFHandle}
names::Vector{String}
end

"""
read_version_struct(oh, s, offset, T)

Read a `T` from `offset` bytes into the version section `s`, throwing an error
if it would extend past the end of the section.
"""
function read_version_struct(oh::ELFHandle, s::ELFSectionRef, offset::Integer, ::Type{T}) where {T}
if offset + packed_sizeof(T) > section_size(s)
error("Malformed $(section_name(s)) section: $(nameof(T)) at offset $(offset) " *
"runs past the end of the section ($(section_size(s)) bytes)")
end
seek(oh, section_offset(s) + offset)
return unpack(oh, T)
end

"""
version_name(strtab, name_offset)

Look up a version or library name in `.dynstr`, throwing an error if
`name_offset` lies outside of it.
"""
function version_name(strtab::ELFStrTab, name_offset::Integer)
dynstr = strtab.section_ref
if name_offset >= section_size(dynstr)
error("Malformed version section: name offset $(name_offset) lies outside " *
"of $(section_name(dynstr)) ($(section_size(dynstr)) bytes)")
end
return strtab_lookup(strtab, name_offset)
end

"""
version_sections(oh, name)

Return the version section `name` and the `.dynstr` section its names point
into, or `nothing` if either is missing or has no contents in the file.
"""
function version_sections(oh::ELFHandle, name::AbstractString)
s = findfirst(Sections(oh), name)
dynstr = findfirst(Sections(oh), ".dynstr")
(isnothing(s) || isnothing(dynstr)) && return nothing
# Split-debuginfo files keep these section headers, but not their contents
(section_has_contents(s) && section_has_contents(dynstr)) || return nothing
section_size(s) == 0 && return nothing
return s, StrTab(dynstr)
end

"""
Collect all version definitions from .gnu.version_d. This section contains a
sequence of verdef structs `vd`, each of which owns exactly `vd.vd_cnt` verdaux
structs which we convert to names. The first name is generally the only
important one to the given `vd`; it is the version being defined, and
corresponds to `vd.vd_hash`. If present, a second verdaux usually notes the
parent version (e.g. `names = ["GLIBCXX_3.4.7", "GLIBCXX_3.4.6"]`)

Returns an empty list if the section is missing, empty, or `SHT_NOBITS`, and
throws an error if an entry or name points outside of its section.
"""
function ELFVersionData(oh::H) where {H <: ELFHandle}
s = findfirst(Sections(oh), ".gnu.version_d")
strtab = StrTab(findfirst(Sections(oh), ".dynstr"))
(isnothing(s) || isnothing(strtab)) && return ELFVersionEntry[]

# Queue oh up to the beginning of this section
seek(oh, section_offset(s))

# Read out ALL OF THE version definitions
version_defs = ELFVersionEntry[]
secs = version_sections(oh, ".gnu.version_d")
isnothing(secs) && return version_defs
s, strtab = secs

# Every offset is relative to the start of the section. `vd_next` and
# `vda_next` are unsigned, so a nonzero step always moves forward, and the
# bounds check in `read_version_struct()` ends the walk.
vd_offset = 0
while true
vd_pos = position(oh)
vd = unpack(oh, ELFVerDef{H})
vd = read_version_struct(oh, s, vd_offset, ELFVerDef{H})

# Find aux names and resolve immediately to strings
auxes = String[]
aux_offset = 0
names = String[]
aux_offset = vd_offset + vd.vd_aux
for aux_idx in 1:vd.vd_cnt
seek(oh, vd_pos + vd.vd_aux + aux_offset)
aux = unpack(oh, ELFVerdAux{H})
name = strtab_lookup(strtab, aux.vda_name)
push!(auxes, name)
aux = read_version_struct(oh, s, aux_offset, ELFVerdAux{H})
push!(names, version_name(strtab, aux.vda_name))
aux.vda_next == 0 && break
aux_offset += aux.vda_next
end

push!(version_defs, ELFVersionEntry(vd, auxes))
push!(version_defs, ELFVersionEntry(vd, names))

if vd.vd_next == 0
break
end
seek(oh, vd_pos + vd.vd_next)
vd.vd_next == 0 && break
vd_offset += vd.vd_next
end

return version_defs
end

Expand All @@ -92,34 +137,34 @@ Collect all version requirements from .gnu.version_r. This section is
structurally similar to the version definition section, but the primary
"verneed" struct corresponds to one shared library, and the auxiliary struct
corresponds to a version.

Returns an empty list if the section is missing, empty, or `SHT_NOBITS`, and
throws an error if an entry or name points outside of its section.
"""
function ELFVersionNeededData(oh::H) where {H <: ELFHandle}
s = findfirst(Sections(oh), ".gnu.version_r")
strtab = StrTab(findfirst(Sections(oh), ".dynstr"))
(isnothing(s) || isnothing(strtab)) && return ELFVersionNeededEntry[]

seek(oh, section_offset(s))
verneeds = ELFVersionNeededEntry[]
secs = version_sections(oh, ".gnu.version_r")
isnothing(secs) && return verneeds
s, strtab = secs

# Offsets are relative to the start of the section, as in `ELFVersionData()`
vn_offset = 0
while true
vn_pos = position(oh)
vn = unpack(oh, ELFVerNeed{H})
vn = read_version_struct(oh, s, vn_offset, ELFVerNeed{H})
auxes = ELFVernAux[]
names = String[]
aux_offset = 0
aux_offset = vn_offset + vn.vn_aux
for aux_idx in 1:vn.vn_cnt
seek(oh, vn_pos + vn.vn_aux + aux_offset)
aux = unpack(oh, ELFVernAux{H})
name = strtab_lookup(strtab, aux.vna_name)
aux = read_version_struct(oh, s, aux_offset, ELFVernAux{H})
push!(auxes, aux)
push!(names, name)
push!(names, version_name(strtab, aux.vna_name))
aux.vna_next == 0 && break
aux_offset += aux.vna_next
end
push!(verneeds, ELFVersionNeededEntry(vn, auxes, names))

if vn.vn_next == 0
break
end
seek(oh, vn_pos + vn.vn_next)
vn.vn_next == 0 && break
vn_offset += vn.vn_next
end

return verneeds
Expand Down
113 changes: 113 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,119 @@ test_libfoo_and_fooifier("./win64/fooifier.exe", "./win64/libfoo.dll")
end
end

# `test/splitdebug/libfoo.so` defines `FOO_1.0` and needs `GLIBC_*` from libc
readmeta("./splitdebug/libfoo.so") do ohs
oh = only(ohs)
verdefs = ELFVersionData(oh)
foreach(check_verdef, verdefs)
@test "FOO_1.0" in vcat((x -> x.names).(verdefs)...)
verneeds = ELFVersionNeededData(oh)
foreach(check_verneed, verneeds)
@test length(verneeds) == 1
@test all(startswith("GLIBC_"), only(verneeds).names)
@test strtab_lookup(StrTab(findfirst(Sections(oh), ".dynstr")), only(verneeds).ver_need.vn_file) == "libc.so.6"
end
end

# Corrupt the version sections of `test/splitdebug/libfoo.so` in memory, and
# check that the version readers stop at the section bounds.
@testset "ELF version sections out of bounds" begin
using ObjectFile.ELF

data = read("./splitdebug/libfoo.so")
load(data) = only(readmeta(IOBuffer(data)))

# Find a section's header and its contents in `data` (0-based offsets)
oh = load(data)
@test is64bit(oh) && endianness(oh) == :LittleEndian
function section_info(name)
s = findfirst(Sections(oh), name)
hdr = header(oh).e_shoff + (section_number(s) - 1) * header(oh).e_shentsize
return hdr, Int(section_offset(s)), Int(section_size(s))
end
# `Elf64_Shdr.sh_size` is at byte 32 of the section header
function with_size(name, size)
hdr, _, _ = section_info(name)
d = copy(data)
d[hdr+33:hdr+40] = reinterpret(UInt8, [UInt64(size)])
return d
end
function with_u32(name, field_offset, value)
_, off, _ = section_info(name)
d = copy(data)
d[off+field_offset+1:off+field_offset+4] = reinterpret(UInt8, [UInt32(value)])
return d
end

# Sanity-check the layout these patches assume
@test length(ELFVersionNeededData(oh)) == 1
vn = only(ELFVersionNeededData(oh)).ver_need
@test vn.vn_aux == 16 && vn.vn_next == 0
@test strtab_lookup(StrTab(findfirst(Sections(oh), ".dynstr")), vn.vn_file) == "libc.so.6"
_, _, verneed_size = section_info(".gnu.version_r")
_, _, verdef_size = section_info(".gnu.version_d")
_, _, dynstr_size = section_info(".dynstr")

# Zero-length sections hold no entries
@test isempty(ELFVersionNeededData(load(with_size(".gnu.version_r", 0))))
@test isempty(ELFVersionData(load(with_size(".gnu.version_d", 0))))

# Truncated sections: shorter than one entry, or cutting off the last aux
@test_throws ErrorException ELFVersionNeededData(load(with_size(".gnu.version_r", 8)))
@test_throws ErrorException ELFVersionNeededData(load(with_size(".gnu.version_r", verneed_size - 1)))
@test_throws ErrorException ELFVersionData(load(with_size(".gnu.version_d", 8)))
@test_throws ErrorException ELFVersionData(load(with_size(".gnu.version_d", verdef_size - 1)))

# `vn_next` (byte 12) or `vn_aux` (byte 8) pointing past the end
@test_throws ErrorException ELFVersionNeededData(load(with_u32(".gnu.version_r", 12, verneed_size)))
@test_throws ErrorException ELFVersionNeededData(load(with_u32(".gnu.version_r", 8, 0x7fffffff)))
# `vna_name` (byte 8 of the aux) pointing outside of `.dynstr`
@test_throws ErrorException ELFVersionNeededData(load(with_u32(".gnu.version_r", vn.vn_aux + 8, dynstr_size)))
# `vd_next` (byte 16) pointing past the end
@test_throws ErrorException ELFVersionData(load(with_u32(".gnu.version_d", 16, verdef_size)))
end

# `objcopy --only-keep-debug` turns the loadable sections into `SHT_NOBITS`:
# their headers stay, but their contents are gone, so there is nothing to read.
@testset "ELF split debuginfo" begin
using ObjectFile.ELF

readmeta("./splitdebug/libfoo.so") do ohs
oh = only(ohs)
sections = Sections(oh)
for name in (".dynamic", ".dynsym", ".dynstr", ".gnu.version_d", ".gnu.version_r")
@test section_has_contents(findfirst(sections, name))
end
@test !section_has_contents(findfirst(sections, ".bss"))
@test !isempty(ELFVersionData(oh))
@test !isempty(ELFVersionNeededData(oh))
@test !isempty(ELF.ELFDynEntries(oh))
@test path.(DynamicLinks(oh)) == ["libc.so.6"]
@test !isempty(Symbols(only(findall(sections, ".dynsym"))))
end

readmeta("./splitdebug/libfoo.so.debug") do ohs
oh = only(ohs)
sections = Sections(oh)
for name in (".dynamic", ".dynsym", ".dynstr", ".gnu.version_d", ".gnu.version_r")
s = findfirst(sections, name)
@test section_type(s) == ELF.SHT_NOBITS
@test !section_has_contents(s)
end
@test section_has_contents(findfirst(sections, ".symtab"))

@test isempty(ELFVersionData(oh))
@test isempty(ELFVersionNeededData(oh))
@test isempty(ELF.ELFDynEntries(oh))
@test isempty(DynamicLinks(oh))
@test isempty(rpaths(RPath(oh)))
@test isempty(Symbols(only(findall(sections, ".dynsym"))))

# `.symtab` is debug info, so it is kept, and still readable
syms = Symbols(oh)
@test Section(syms) == findfirst(sections, ".symtab")
@test "foo" in symbol_name.(syms)
end
end

# Ensure that these tricksy win32 files work
Expand Down
22 changes: 22 additions & 0 deletions test/splitdebug/build.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#!/bin/bash
# Regenerates the split-debuginfo ELF fixtures in this directory. Requires
# `gcc` and `objcopy`. `libfoo.so` defines versioned symbols (`.gnu.version_d`)
# and needs versioned glibc symbols (`.gnu.version_r`). `libfoo.so.debug` is
# its `objcopy --only-keep-debug` counterpart: it keeps every section header,
# but the loadable sections (`.dynamic`, `.dynsym`, `.dynstr`, `.gnu.version*`,
# ...) become `SHT_NOBITS` and have no contents in the file.
set -euo pipefail
cd "$(dirname "$0")"
tmp="$(mktemp -d)"
trap 'rm -rf "${tmp}"' EXIT

cat > "${tmp}/foo.c" <<'SRC'
#include <stdio.h>
#include <string.h>
int foo(const char *s) { printf("%s\n", s); return (int)strlen(s); }
SRC
printf 'FOO_1.0 { global: foo; local: *; };\n' > "${tmp}/foo.map"

gcc -shared -fPIC -g -O2 -Wl,--build-id=none -Wl,--version-script="${tmp}/foo.map" \
-o libfoo.so "${tmp}/foo.c"
objcopy --only-keep-debug libfoo.so libfoo.so.debug
Binary file added test/splitdebug/libfoo.so
Binary file not shown.
Binary file added test/splitdebug/libfoo.so.debug
Binary file not shown.
Loading