github.com/linuxboot/fiano@v1.2.0/cmds/cbfs/cbfs.go (about)

     1  // Copyright 2018-2021 the LinuxBoot Authors. All rights reserved
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package main
     6  
     7  import (
     8  	"encoding/json"
     9  	"fmt"
    10  	"log"
    11  	"os"
    12  	"path/filepath"
    13  	"strings"
    14  
    15  	"github.com/linuxboot/fiano/pkg/cbfs"
    16  	flag "github.com/spf13/pflag"
    17  )
    18  
    19  var debug = flag.BoolP("debug", "d", false, "enable debug prints")
    20  
    21  func main() {
    22  	flag.Parse()
    23  
    24  	if *debug {
    25  		cbfs.Debug = log.Printf
    26  	}
    27  
    28  	a := flag.Args()
    29  	if len(a) < 2 {
    30  		log.Fatal("Usage: cbfs <firmware-file> <json,list,extract <directory-name>>")
    31  	}
    32  
    33  	i, err := cbfs.Open(a[0])
    34  	if err != nil {
    35  		log.Fatal(err)
    36  	}
    37  
    38  	switch a[1] {
    39  	case "list":
    40  		fmt.Printf("%s", i.String())
    41  	case "json":
    42  		j, err := json.MarshalIndent(i, "  ", "  ")
    43  		if err != nil {
    44  			log.Fatal(err)
    45  		}
    46  		fmt.Printf("%s", string(j))
    47  	case "extract":
    48  		if len(a) != 3 {
    49  			log.Fatal("provide a directory name")
    50  		}
    51  		dir := filepath.Join(".", a[2])
    52  		err := os.MkdirAll(dir, os.ModePerm)
    53  		if err != nil {
    54  			log.Fatal(err)
    55  		}
    56  		base := i.Area.Offset
    57  		log.Printf("FMAP base at %x", base)
    58  		for s := range i.Segs {
    59  			f := i.Segs[s].GetFile()
    60  			n := f.Name
    61  			c := f.Compression()
    62  			o := f.RecordStart
    63  			if f.Type.String() == cbfs.TypeDeleted.String() || f.Type.String() == cbfs.TypeDeleted2.String() {
    64  				log.Printf("Skipping empty/deleted file at 0x%x", o)
    65  			} else {
    66  				log.Printf("Extracting %v from 0x%x, compression: %v", n, o, c)
    67  				fpath := filepath.Join(dir, strings.Replace(n, "/", "_", -1))
    68  				d, err := f.Decompress()
    69  				if err != nil {
    70  					log.Fatal(err)
    71  				}
    72  				err = os.WriteFile(fpath, d, 0644)
    73  				if err != nil {
    74  					log.Fatal(err)
    75  				}
    76  			}
    77  		}
    78  	default:
    79  		log.Fatal("?")
    80  	}
    81  
    82  }