symbols_map: don't error on bad elf files
There are cc_binary_prebuilt modules in the tree that are shell
scripts, and attempting to extract an elf ID from them results
in an error. Ignore too short files and files missing the elf
magic header the same way we do for elf files without an elf ID.
Bug: 218888599
Test: Test_elfIdentifierFromReaderAt_BadElfFile
Change-Id: If7117925ca2371a8ee61ba3616372f6e9b0fab0e
diff --git a/cmd/symbols_map/elf.go b/cmd/symbols_map/elf.go
index b38896a..3c8b1e4 100644
--- a/cmd/symbols_map/elf.go
+++ b/cmd/symbols_map/elf.go
@@ -18,8 +18,10 @@
"debug/elf"
"encoding/binary"
"encoding/hex"
+ "errors"
"fmt"
"io"
+ "os"
)
const gnuBuildID = "GNU\x00"
@@ -27,12 +29,33 @@
// elfIdentifier extracts the elf build ID from an elf file. If allowMissing is true it returns
// an empty identifier if the file exists but the build ID note does not.
func elfIdentifier(filename string, allowMissing bool) (string, error) {
- f, err := elf.Open(filename)
+ f, err := os.Open(filename)
if err != nil {
return "", fmt.Errorf("failed to open %s: %w", filename, err)
}
defer f.Close()
+ return elfIdentifierFromReaderAt(f, filename, allowMissing)
+}
+
+// elfIdentifier extracts the elf build ID from a ReaderAt. If allowMissing is true it returns
+// an empty identifier if the file exists but the build ID note does not.
+func elfIdentifierFromReaderAt(r io.ReaderAt, filename string, allowMissing bool) (string, error) {
+ f, err := elf.NewFile(r)
+ if err != nil {
+ if allowMissing {
+ if errors.Is(err, io.EOF) {
+ return "", nil
+ }
+ if _, ok := err.(*elf.FormatError); ok {
+ // The file was not an elf file.
+ return "", nil
+ }
+ }
+ return "", fmt.Errorf("failed to parse elf file %s: %w", filename, err)
+ }
+ defer f.Close()
+
buildIDNote := f.Section(".note.gnu.build-id")
if buildIDNote == nil {
if allowMissing {