github.com/google/syzkaller@v0.0.0-20240517125934-c0f1611a36d6/pkg/image/compression_test.go (about)

     1  // Copyright 2022 syzkaller project authors. All rights reserved.
     2  // Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
     3  
     4  package image_test
     5  
     6  import (
     7  	"bytes"
     8  	"fmt"
     9  	"math/rand"
    10  	"os"
    11  	"path/filepath"
    12  	"testing"
    13  
    14  	. "github.com/google/syzkaller/pkg/image"
    15  	"github.com/google/syzkaller/pkg/testutil"
    16  	"github.com/google/syzkaller/prog"
    17  	_ "github.com/google/syzkaller/sys/linux/gen"
    18  )
    19  
    20  func TestCompress(t *testing.T) {
    21  	t.Parallel()
    22  	r := rand.New(testutil.RandSource(t))
    23  	for i := 0; i < testutil.IterCount(); i++ {
    24  		t.Run(fmt.Sprint(i), func(t *testing.T) {
    25  			randBytes := testutil.RandMountImage(r)
    26  			resultBytes := Compress(randBytes)
    27  			resultBytes, dtor := MustDecompress(resultBytes)
    28  			defer dtor()
    29  			if !bytes.Equal(randBytes, resultBytes) {
    30  				t.Fatalf("roundtrip changes data (length %v->%v)", len(randBytes), len(resultBytes))
    31  			}
    32  		})
    33  	}
    34  }
    35  
    36  func TestEncode(t *testing.T) {
    37  	t.Parallel()
    38  	r := rand.New(testutil.RandSource(t))
    39  	for i := 0; i < testutil.IterCount(); i++ {
    40  		randBytes := testutil.RandMountImage(r)
    41  		resultBytes := EncodeB64(randBytes)
    42  		resultBytes, err := DecodeB64(resultBytes)
    43  		if err != nil {
    44  			t.Fatalf("decoding failed: %v", err)
    45  		}
    46  		if !bytes.Equal(randBytes, resultBytes) {
    47  			t.Fatalf("roundtrip changes data (original length %d)", len(randBytes))
    48  		}
    49  	}
    50  }
    51  
    52  func BenchmarkDecompress(b *testing.B) {
    53  	// Extract the largest image seed.
    54  	data, err := os.ReadFile(filepath.FromSlash("../../sys/linux/test/syz_mount_image_gfs2_0"))
    55  	if err != nil {
    56  		b.Fatal(err)
    57  	}
    58  	target, err := prog.GetTarget("linux", "amd64")
    59  	if err != nil {
    60  		b.Fatal(err)
    61  	}
    62  	p, err := target.Deserialize(data, prog.Strict)
    63  	if err != nil {
    64  		b.Fatalf("failed to deserialize the program: %v", err)
    65  	}
    66  	compressed := p.Calls[0].Args[6].(*prog.PointerArg).Res.(*prog.DataArg).Data()
    67  	if len(compressed) < 100<<10 {
    68  		b.Fatalf("compressed data is too small: %v", len(compressed))
    69  	}
    70  	b.ReportAllocs()
    71  	b.ResetTimer()
    72  	for i := 0; i < b.N; i++ {
    73  		uncompressed, dtor := MustDecompress(compressed)
    74  		if len(uncompressed) < 10<<20 {
    75  			b.Fatalf("uncompressed data is too small: %v", len(uncompressed))
    76  		}
    77  		dtor()
    78  	}
    79  }