// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package buildinfo provides access to information embedded in a Go binary // about how it was built. This includes the Go toolchain version, and the // set of modules used (for binaries built in module mode). // // Build information is available for the currently running binary in // runtime/debug.ReadBuildInfo.
package buildinfo import ( ) // Type alias for build info. We cannot move the types here, since // runtime/debug would need to import this package, which would make it // a much larger dependency. type BuildInfo = debug.BuildInfo var ( // errUnrecognizedFormat is returned when a given executable file doesn't // appear to be in a known format, or it breaks the rules of that format, // or when there are I/O errors reading the file. errUnrecognizedFormat = errors.New("unrecognized file format") // errNotGoExe is returned when a given executable file is valid but does // not contain Go build information. errNotGoExe = errors.New("not a Go executable") // The build info blob left by the linker is identified by // a 16-byte header, consisting of buildInfoMagic (14 bytes), // the binary's pointer size (1 byte), // and whether the binary is big endian (1 byte). buildInfoMagic = []byte("\xff Go buildinf:") ) // ReadFile returns build information embedded in a Go binary // file at the given path. Most information is only available for binaries built // with module support. func ( string) ( *BuildInfo, error) { defer func() { if := (*fs.PathError)(nil); errors.As(, &) { = fmt.Errorf("could not read Go build info: %w", ) } else if != nil { = fmt.Errorf("could not read Go build info from %s: %w", , ) } }() , := os.Open() if != nil { return nil, } defer .Close() return Read() } // Read returns build information embedded in a Go binary file // accessed through the given ReaderAt. Most information is only available for // binaries built with module support. func ( io.ReaderAt) (*BuildInfo, error) { , , := readRawBuildInfo() if != nil { return nil, } , := debug.ParseBuildInfo() if != nil { return nil, } .GoVersion = return , nil } type exe interface { // ReadData reads and returns up to size bytes starting at virtual address addr. ReadData(addr, size uint64) ([]byte, error) // DataStart returns the virtual address and size of the segment or section that // should contain build information. This is either a specially named section // or the first writable non-zero data segment. DataStart() (uint64, uint64) } // readRawBuildInfo extracts the Go toolchain version and module information // strings from a Go binary. On success, vers should be non-empty. mod // is empty if the binary was not built with modules enabled. func readRawBuildInfo( io.ReaderAt) (, string, error) { // Read the first bytes of the file to identify the format, then delegate to // a format-specific function to load segment and section headers. := make([]byte, 16) if , := .ReadAt(, 0); < len() || != nil { return "", "", errUnrecognizedFormat } var exe switch { case bytes.HasPrefix(, []byte("\x7FELF")): , := elf.NewFile() if != nil { return "", "", errUnrecognizedFormat } = &elfExe{} case bytes.HasPrefix(, []byte("MZ")): , := pe.NewFile() if != nil { return "", "", errUnrecognizedFormat } = &peExe{} case bytes.HasPrefix(, []byte("\xFE\xED\xFA")) || bytes.HasPrefix([1:], []byte("\xFA\xED\xFE")): , := macho.NewFile() if != nil { return "", "", errUnrecognizedFormat } = &machoExe{} case bytes.HasPrefix(, []byte("\xCA\xFE\xBA\xBE")) || bytes.HasPrefix(, []byte("\xCA\xFE\xBA\xBF")): , := macho.NewFatFile() if != nil || len(.Arches) == 0 { return "", "", errUnrecognizedFormat } = &machoExe{.Arches[0].File} case bytes.HasPrefix(, []byte{0x01, 0xDF}) || bytes.HasPrefix(, []byte{0x01, 0xF7}): , := xcoff.NewFile() if != nil { return "", "", errUnrecognizedFormat } = &xcoffExe{} case hasPlan9Magic(): , := plan9obj.NewFile() if != nil { return "", "", errUnrecognizedFormat } = &plan9objExe{} default: return "", "", errUnrecognizedFormat } // Read segment or section to find the build info blob. // On some platforms, the blob will be in its own section, and DataStart // returns the address of that section. On others, it's somewhere in the // data segment; the linker puts it near the beginning. // See cmd/link/internal/ld.Link.buildinfo. , := .DataStart() if == 0 { return "", "", errNotGoExe } , := .ReadData(, ) if != nil { return "", "", } const ( = 16 = 32 ) for { := bytes.Index(, buildInfoMagic) if < 0 || len()- < { return "", "", errNotGoExe } if % == 0 && len()- >= { = [:] break } = [(+-1)&^(-1):] } // Decode the blob. // The first 14 bytes are buildInfoMagic. // The next two bytes indicate pointer size in bytes (4 or 8) and endianness // (0 for little, 1 for big). // Two virtual addresses to Go strings follow that: runtime.buildVersion, // and runtime.modinfo. // On 32-bit platforms, the last 8 bytes are unused. // If the endianness has the 2 bit set, then the pointers are zero // and the 32-byte header is followed by varint-prefixed string data // for the two string values we care about. := int([14]) if [15]&2 != 0 { , = decodeString([32:]) , = decodeString() } else { := [15] != 0 var binary.ByteOrder if { = binary.BigEndian } else { = binary.LittleEndian } var func([]byte) uint64 if == 4 { = func( []byte) uint64 { return uint64(.Uint32()) } } else if == 8 { = .Uint64 } else { return "", "", errNotGoExe } = readString(, , , ([16:])) = readString(, , , ([16+:])) } if == "" { return "", "", errNotGoExe } if len() >= 33 && [len()-17] == '\n' { // Strip module framing: sentinel strings delimiting the module info. // These are cmd/go/internal/modload.infoStart and infoEnd. = [16 : len()-16] } else { = "" } return , , nil } func hasPlan9Magic( []byte) bool { if len() >= 4 { := binary.BigEndian.Uint32() switch { case plan9obj.Magic386, plan9obj.MagicAMD64, plan9obj.MagicARM: return true } } return false } func decodeString( []byte) ( string, []byte) { , := binary.Uvarint() if <= 0 || > uint64(len()-) { return "", nil } return string([ : uint64()+]), [uint64()+:] } // readString returns the string at address addr in the executable x. func readString( exe, int, func([]byte) uint64, uint64) string { , := .ReadData(, uint64(2*)) if != nil || len() < 2* { return "" } := () := ([:]) , := .ReadData(, ) if != nil || uint64(len()) < { return "" } return string() } // elfExe is the ELF implementation of the exe interface. type elfExe struct { f *elf.File } func ( *elfExe) (, uint64) ([]byte, error) { for , := range .f.Progs { if .Vaddr <= && <= .Vaddr+.Filesz-1 { := .Vaddr + .Filesz - if > { = } return saferio.ReadDataAt(, , int64(-.Vaddr)) } } return nil, errUnrecognizedFormat } func ( *elfExe) () (uint64, uint64) { for , := range .f.Sections { if .Name == ".go.buildinfo" { return .Addr, .Size } } for , := range .f.Progs { if .Type == elf.PT_LOAD && .Flags&(elf.PF_X|elf.PF_W) == elf.PF_W { return .Vaddr, .Memsz } } return 0, 0 } // peExe is the PE (Windows Portable Executable) implementation of the exe interface. type peExe struct { f *pe.File } func ( *peExe) () uint64 { switch oh := .f.OptionalHeader.(type) { case *pe.OptionalHeader32: return uint64(.ImageBase) case *pe.OptionalHeader64: return .ImageBase } return 0 } func ( *peExe) (, uint64) ([]byte, error) { -= .imageBase() for , := range .f.Sections { if uint64(.VirtualAddress) <= && <= uint64(.VirtualAddress+.Size-1) { := uint64(.VirtualAddress+.Size) - if > { = } return saferio.ReadDataAt(, , int64(-uint64(.VirtualAddress))) } } return nil, errUnrecognizedFormat } func ( *peExe) () (uint64, uint64) { // Assume data is first writable section. const ( = 0x00000020 = 0x00000040 = 0x00000080 = 0x20000000 = 0x40000000 = 0x80000000 = 0x2000000 = 0x1000000 = 0x600000 ) for , := range .f.Sections { if .VirtualAddress != 0 && .Size != 0 && .Characteristics&^ == || { return uint64(.VirtualAddress) + .imageBase(), uint64(.VirtualSize) } } return 0, 0 } // machoExe is the Mach-O (Apple macOS/iOS) implementation of the exe interface. type machoExe struct { f *macho.File } func ( *machoExe) (, uint64) ([]byte, error) { for , := range .f.Loads { , := .(*macho.Segment) if ! { continue } if .Addr <= && <= .Addr+.Filesz-1 { if .Name == "__PAGEZERO" { continue } := .Addr + .Filesz - if > { = } return saferio.ReadDataAt(, , int64(-.Addr)) } } return nil, errUnrecognizedFormat } func ( *machoExe) () (uint64, uint64) { // Look for section named "__go_buildinfo". for , := range .f.Sections { if .Name == "__go_buildinfo" { return .Addr, .Size } } // Try the first non-empty writable segment. const = 3 for , := range .f.Loads { , := .(*macho.Segment) if && .Addr != 0 && .Filesz != 0 && .Prot == && .Maxprot == { return .Addr, .Memsz } } return 0, 0 } // xcoffExe is the XCOFF (AIX eXtended COFF) implementation of the exe interface. type xcoffExe struct { f *xcoff.File } func ( *xcoffExe) (, uint64) ([]byte, error) { for , := range .f.Sections { if .VirtualAddress <= && <= .VirtualAddress+.Size-1 { := .VirtualAddress + .Size - if > { = } return saferio.ReadDataAt(, , int64(-.VirtualAddress)) } } return nil, errors.New("address not mapped") } func ( *xcoffExe) () (uint64, uint64) { if := .f.SectionByType(xcoff.STYP_DATA); != nil { return .VirtualAddress, .Size } return 0, 0 } // plan9objExe is the Plan 9 a.out implementation of the exe interface. type plan9objExe struct { f *plan9obj.File } func ( *plan9objExe) () (uint64, uint64) { if := .f.Section("data"); != nil { return uint64(.Offset), uint64(.Size) } return 0, 0 } func ( *plan9objExe) (, uint64) ([]byte, error) { for , := range .f.Sections { if uint64(.Offset) <= && <= uint64(.Offset+.Size-1) { := uint64(.Offset+.Size) - if > { = } return saferio.ReadDataAt(, , int64(-uint64(.Offset))) } } return nil, errors.New("address not mapped") }