Inspect ELF, PE, Mach-O and DWARF
Inspect ELF, PE, Mach-O and DWARF
ELF is common on Linux, PE on Windows and Mach-O on macOS. DWARF is debugging information, not an executable format. The debug packages read these structures without executing them. Work only with trusted lab binaries; these parsers are not hardened against adversarial inputs.
package main
import ( "debug/elf" "fmt" "os" "runtime")
func ownELF() (*elf.File, error) { p, e := os.Executable() if e != nil { return nil, e } return elf.Open(p)}func main() { if runtime.GOOS != "linux" { fmt.Println("use Linux fixture") return } f, e := ownELF() if e != nil { panic(e) } defer f.Close() fmt.Println(f.Class != elf.ELFCLASSNONE, len(f.Sections) > 0)}elf.Open reads the current lab executable; Close releases the file. Class describes 32/64-bit ELF representation and Machine describes the target architecture. Not all files contain the same sections. Do not execute an unfamiliar binary to identify its format.
Expected output:
true trueFormat-specific parsing errors
package main
import ( "bytes" "debug/elf" "debug/macho" "debug/pe" "fmt")
func main() { b := []byte("not a binary") _, e1 := elf.NewFile(bytes.NewReader(b)) _, e2 := pe.NewFile(bytes.NewReader(b)) _, e3 := macho.NewFile(bytes.NewReader(b)) fmt.Println(e1 != nil, e2 != nil, e3 != nil)}Use pe.Open for a known PE file and macho.Open for a known thin Mach-O file; macho.OpenFat handles universal containers. Each parser exposes DWARF() when the necessary debug data exists. Build without stripping debug information (go build, not go run for debugger data); call Data.Reader().Next() to iterate entries and check errors. Debug sections may be absent. Cross-building does not test target execution.
Expected output:
true true trueTry it locally
On Linux, open the executable and check that its machine is not EM_NONE and .text is present. Use the same trusted fixture only.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Specialized library 05: Inspect ELF, PE, Mach-O and DWARF
Check the lesson objective before moving on.
What is DWARF?
What does a cross-built PE inspection establish?