gvisor.dev/gvisor@v0.0.0-20240520182842-f9d4d51c7e0f/tools/tracereplay/tracereplay.go (about)

     1  // Copyright 2022 The gVisor Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  // Package tracereplay implements a tool that can save and replay messages
    16  // issued from remote.Remote.
    17  package tracereplay
    18  
    19  import (
    20  	"encoding/binary"
    21  	"fmt"
    22  	"io"
    23  	"os"
    24  )
    25  
    26  const signature = "tracereplay file"
    27  
    28  func writeSize(w io.Writer, val int) error {
    29  	var bin [8]byte
    30  	binary.LittleEndian.PutUint64(bin[:], uint64(val))
    31  	_, err := w.Write(bin[:])
    32  	return err
    33  }
    34  
    35  func readSize(r io.Reader) (int, error) {
    36  	var bin [8]byte
    37  	if read, err := r.Read(bin[:]); err != nil {
    38  		return 0, err
    39  	} else if read != 8 {
    40  		return 0, fmt.Errorf("truncated read (%d bytes)", read)
    41  	}
    42  	size := int(binary.LittleEndian.Uint64(bin[:]))
    43  	// Prevent returning a too large size to avoid OOMs.
    44  	if size > 1024*1024 {
    45  		return 0, fmt.Errorf("size is too big: %d", size)
    46  	}
    47  	return size, nil
    48  }
    49  
    50  func writeWithSize(f *os.File, buf []byte) error {
    51  	if err := writeSize(f, len(buf)); err != nil {
    52  		return err
    53  	}
    54  	_, err := f.Write(buf)
    55  	return err
    56  }
    57  
    58  func readWithSize(r io.Reader) ([]byte, error) {
    59  	size, err := readSize(r)
    60  	if err != nil {
    61  		return nil, err
    62  	}
    63  	bytes := make([]byte, size)
    64  	if err := readFull(r, bytes); err != nil {
    65  		return nil, err
    66  	}
    67  	return bytes, nil
    68  }
    69  
    70  func readFull(r io.Reader, dest []byte) error {
    71  	if read, err := r.Read(dest); err != nil {
    72  		return err
    73  	} else if read < len(dest) {
    74  		return fmt.Errorf("truncated read. Read %d bytes, expected %d bytes", read, len(dest))
    75  	}
    76  	return nil
    77  }
    78  
    79  // Config contains information required to replay messages from a file.
    80  type Config struct {
    81  	// Version is the wire format saved in the file.
    82  	Version uint32 `json:"version"`
    83  }