github.com/google/trillian-examples@v0.0.0-20240520080811-0d40d35cef0e/binary_transparency/firmware/devices/usbarmory/bootloader/elf.go (about)

     1  // https://github.com/usbarmory/armory-boot
     2  //
     3  // Copyright (c) F-Secure Corporation
     4  // https://foundry.f-secure.com
     5  //
     6  // Use of this source code is governed by the license
     7  // that can be found in the LICENSE file.
     8  
     9  //go:build armory
    10  // +build armory
    11  
    12  package main
    13  
    14  import (
    15  	"bytes"
    16  	"debug/elf"
    17  	"fmt"
    18  
    19  	"github.com/usbarmory/tamago/dma"
    20  )
    21  
    22  // loadELF attempts to load the provided ELF image.
    23  //
    24  // This function implements a _very_ simple ELF loader which is suitable for
    25  // loading bare-metal ELF files like those produced by TamaGo.
    26  func loadELF(mem uint, kernel []byte) (addr uint) {
    27  	f, err := elf.NewFile(bytes.NewReader(kernel))
    28  
    29  	if err != nil {
    30  		panic(err)
    31  	}
    32  
    33  	for idx, prg := range f.Progs {
    34  		if prg.Type != elf.PT_LOAD {
    35  			continue
    36  		}
    37  
    38  		b := make([]byte, prg.Memsz)
    39  
    40  		_, err := prg.ReadAt(b[0:prg.Filesz], 0)
    41  
    42  		if err != nil {
    43  			panic(fmt.Sprintf("failed to read LOAD section at idx %d, %q", idx, err))
    44  		}
    45  
    46  		offset := uint(prg.Paddr) - mem
    47  		dma.Write(mem, int(offset), b)
    48  	}
    49  
    50  	return uint(f.Entry)
    51  }