github.com/anchore/syft@v1.4.2-0.20240516191711-1bec1fc5d397/syft/pkg/cataloger/rust/parse_audit_binary.go (about)

     1  package rust
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  
     7  	rustaudit "github.com/microsoft/go-rustaudit"
     8  
     9  	"github.com/anchore/syft/internal/log"
    10  	"github.com/anchore/syft/syft/artifact"
    11  	"github.com/anchore/syft/syft/file"
    12  	"github.com/anchore/syft/syft/internal/unionreader"
    13  	"github.com/anchore/syft/syft/pkg"
    14  	"github.com/anchore/syft/syft/pkg/cataloger/generic"
    15  )
    16  
    17  // Catalog identifies executables then attempts to read Rust dependency information from them
    18  func parseAuditBinary(_ context.Context, _ file.Resolver, _ *generic.Environment, reader file.LocationReadCloser) ([]pkg.Package, []artifact.Relationship, error) {
    19  	var pkgs []pkg.Package
    20  
    21  	unionReader, err := unionreader.GetUnionReader(reader.ReadCloser)
    22  	if err != nil {
    23  		return nil, nil, err
    24  	}
    25  
    26  	for _, versionInfo := range parseAuditBinaryEntry(unionReader, reader.RealPath) {
    27  		pkgs = append(pkgs, newPackagesFromAudit(reader.Location, versionInfo)...)
    28  	}
    29  
    30  	return pkgs, nil, nil
    31  }
    32  
    33  // scanFile scans file to try to report the Rust crate dependencies
    34  func parseAuditBinaryEntry(reader unionreader.UnionReader, filename string) []rustaudit.VersionInfo {
    35  	// NOTE: multiple readers are returned to cover universal binaries, which are files
    36  	// with more than one binary
    37  	readers, err := unionreader.GetReaders(reader)
    38  	if err != nil {
    39  		log.Warnf("rust cataloger: failed to open a binary: %v", err)
    40  		return nil
    41  	}
    42  
    43  	var versionInfos []rustaudit.VersionInfo
    44  	for _, r := range readers {
    45  		versionInfo, err := rustaudit.GetDependencyInfo(r)
    46  
    47  		if err != nil {
    48  			if errors.Is(err, rustaudit.ErrNoRustDepInfo) {
    49  				// since the cataloger can only select executables and not distinguish if they are a Rust-compiled
    50  				// binary, we should not show warnings/logs in this case.
    51  				return nil
    52  			}
    53  			log.Tracef("rust cataloger: unable to read dependency information (file=%q): %v", filename, err)
    54  			return nil
    55  		}
    56  
    57  		versionInfos = append(versionInfos, versionInfo)
    58  	}
    59  
    60  	return versionInfos
    61  }