| // Copyright 2026 Google LLC |
| // |
| // Licensed under the Apache License, Version 2.0 (the "License"); |
| // you may not use this file except in compliance with the License. |
| // You may obtain a copy of the License at |
| // |
| // http://www.apache.org/licenses/LICENSE-2.0 |
| // |
| // Unless required by applicable law or agreed to in writing, software |
| // distributed under the License is distributed on an "AS IS" BASIS, |
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| // See the License for the specific language governing permissions and |
| // limitations under the License. |
| |
| package cosboot |
| |
| import ( |
| "bytes" |
| "compress/gzip" |
| "debug/elf" |
| "errors" |
| "io" |
| ) |
| |
| // elfFromBZImage converts a given bzImage into an ELF. Adapted from |
| // extract-vmlinux in the kernel tree. |
| func elfFromBZImage(img []byte) ([]byte, error) { |
| gzipMagic := []byte{0x1f, 0x8b, 0x08} |
| |
| for searchOffset := 0; searchOffset < len(img); { |
| i := bytes.Index(img[searchOffset:], gzipMagic) |
| if i == -1 { |
| break |
| } |
| i += searchOffset |
| searchOffset = i + 1 |
| |
| // Found a potential gzip header, attempt decompression. |
| gzReader, err := gzip.NewReader(bytes.NewReader(img[i:])) |
| if err != nil { |
| continue |
| } |
| gzReader.Multistream(false) |
| |
| decompressed, err := io.ReadAll(gzReader) |
| gzReader.Close() |
| if err != nil { |
| continue |
| } |
| |
| // Verify if the decompressed content is a valid ELF file. |
| if f, err := elf.NewFile(bytes.NewReader(decompressed)); err == nil { |
| f.Close() |
| return decompressed, nil |
| } |
| } |
| |
| return nil, errors.New("could not find a compressed ELF payload in the bzImage") |
| } |