src

Go monorepo.
git clone git://code.dwrz.net/src
Log | Files | Refs

extract.go (1534B)


      1 // Copyright 2023 The Go 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 scan
      6 
      7 import (
      8 	"encoding/json"
      9 	"fmt"
     10 	"io"
     11 	"sort"
     12 
     13 	"golang.org/x/vuln/internal/derrors"
     14 	"golang.org/x/vuln/internal/vulncheck"
     15 )
     16 
     17 const (
     18 	// extractModeID is the unique name of the extract mode protocol
     19 	extractModeID      = "govulncheck-extract"
     20 	extractModeVersion = "0.1.0"
     21 )
     22 
     23 // header information for the blob output.
     24 type header struct {
     25 	Name    string `json:"name"`
     26 	Version string `json:"version"`
     27 }
     28 
     29 // runExtract dumps the extracted abstraction of binary at cfg.patterns to out.
     30 // It prints out exactly two blob messages, one with the header and one with
     31 // the vulncheck.Bin as the body.
     32 func runExtract(cfg *config, out io.Writer) (err error) {
     33 	defer derrors.Wrap(&err, "govulncheck")
     34 
     35 	bin, err := createBin(cfg.patterns[0])
     36 	if err != nil {
     37 		return err
     38 	}
     39 	sortBin(bin) // sort for easier testing and validation
     40 	header := header{
     41 		Name:    extractModeID,
     42 		Version: extractModeVersion,
     43 	}
     44 
     45 	enc := json.NewEncoder(out)
     46 
     47 	if err := enc.Encode(header); err != nil {
     48 		return fmt.Errorf("marshaling blob header: %v", err)
     49 	}
     50 	if err := enc.Encode(bin); err != nil {
     51 		return fmt.Errorf("marshaling blob body: %v", err)
     52 	}
     53 	return nil
     54 }
     55 
     56 func sortBin(bin *vulncheck.Bin) {
     57 	sort.SliceStable(bin.PkgSymbols, func(i, j int) bool {
     58 		return bin.PkgSymbols[i].Pkg+"."+bin.PkgSymbols[i].Name < bin.PkgSymbols[j].Pkg+"."+bin.PkgSymbols[j].Name
     59 	})
     60 }