<commit_before>// Copyright 2015 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.

package qemu

import (
	"fmt"
	"net"
	"os"
	"os/exec"
	"path/filepath"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/google/syzkaller/fileutil"
	"github.com/google/syzkaller/vm"
)

func init() {
	vm.Register("qemu", ctor)
}

type instance struct {
	cfg     *vm.Config
	port    int
	image   string
	rpipe   *os.File
	wpipe   *os.File
	qemu    *exec.Cmd
	readerC chan error
	waiterC chan error

	mu      sync.Mutex
	outputB []byte
	outputC chan []byte
}

func ctor(cfg *vm.Config) (vm.Instance, error) {
	inst := &instance{
		cfg:   cfg,
		image: filepath.Join(cfg.Workdir, "image"),
	}
	closeInst := inst
	defer func() {
		if closeInst != nil {
			closeInst.Close()
		}
	}()

	if err := validateConfig(cfg); err != nil {
		return nil, err
	}

	os.Remove(inst.image)
	if err := fileutil.CopyFile(inst.cfg.Image, inst.image, true); err != nil {
		return nil, fmt.Errorf("failed to copy image file: %v", err)
	}
	var err error
	inst.rpipe, inst.wpipe, err = os.Pipe()
	if err != nil {
		return nil, fmt.Errorf("failed to create pipe: %v", err)
	}

	for i := 0; ; i++ {
		err := inst.Boot()
		if err == nil {
			break
		}
		if i < 1000 && strings.Contains(err.Error(), "could not set up host forwarding rule") {
			continue
		}
		return nil, err
	}
	closeInst = nil
	return inst, nil
}

func validateConfig(cfg *vm.Config) error {
	if cfg.Bin == "" {
		cfg.Bin = "qemu-system-x86_64"
	}
	if _, err := os.Stat(cfg.Kernel); err != nil {
		return fmt.Errorf("kernel file '%v' does not exist: %v", cfg.Kernel, err)
	}
	if _, err := os.Stat(cfg.Image); err != nil {
		return fmt.Errorf("image file '%v' does not exist: %v", cfg.Image, err)
	}
	if _, err := os.Stat(cfg.Sshkey); err != nil {
		return fmt.Errorf("ssh key '%v' does not exist: %v", cfg.Sshkey, err)
	}
	if cfg.Cpu <= 0 || cfg.Cpu > 1024 {
		return fmt.Errorf("bad qemu cpu: %v, want [1-1024]", cfg.Cpu)
	}
	if cfg.Mem < 128 || cfg.Mem > 1048576 {
		return fmt.Errorf("bad qemu mem: %v, want [128-1048576]", cfg.Mem)
	}
	return nil
}

func (inst *instance) HostAddr() string {
	return "10.0.2.10"
}

func (inst *instance) Close() {
	if inst.qemu != nil {
		inst.qemu.Process.Kill()
		err := <-inst.waiterC
		inst.waiterC <- err // repost it for waiting goroutines
		<-inst.readerC
	}
	if inst.rpipe != nil {
		inst.rpipe.Close()
	}
	if inst.wpipe != nil {
		inst.wpipe.Close()
	}
	os.RemoveAll(inst.cfg.Workdir)
}

func (inst *instance) Boot() error {
	for {
		// Find an unused TCP port.
		inst.port = int(time.Now().UnixNano()%(64<<10-1<<10) + 1<<10)
		ln, err := net.Listen("tcp", fmt.Sprintf("localhost:%v", inst.port))
		if err == nil {
			ln.Close()<commit_msg>vm/qemu: fix output reading bug<commit_after>// Copyright 2015 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.

package qemu

import (
	"fmt"
	"math/rand"
	"net"
	"os"
	"os/exec"
	"path/filepath"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/google/syzkaller/fileutil"
	"github.com/google/syzkaller/vm"
)

func init() {
	vm.Register("qemu", ctor)
}

type instance struct {
	cfg     *vm.Config
	port    int
	image   string
	rpipe   *os.File
	wpipe   *os.File
	qemu    *exec.Cmd
	readerC chan error
	waiterC chan error

	mu      sync.Mutex
	outputB []byte
	outputC chan []byte
}

func ctor(cfg *vm.Config) (vm.Instance, error) {
	for i := 0; ; i++ {
		inst, err := ctorImpl(cfg)
		if err == nil {
			return inst, nil
		}
		if i < 1000 && strings.Contains(err.Error(), "could not set up host forwarding rule") {
			continue
		}
		return nil, err
	}
}

func ctorImpl(cfg *vm.Config) (vm.Instance, error) {
	inst := &instance{
		cfg:   cfg,
		image: filepath.Join(cfg.Workdir, "image"),
	}
	closeInst := inst
	defer func() {
		if closeInst != nil {
			closeInst.Close()
		}
	}()

	if err := validateConfig(cfg); err != nil {
		return nil, err
	}

	os.Remove(inst.image)
	if err := fileutil.CopyFile(inst.cfg.Image, inst.image, true); err != nil {
		return nil, fmt.Errorf("failed to copy image file: %v", err)
	}
	var err error
	inst.rpipe, inst.wpipe, err = os.Pipe()
	if err != nil {
		return nil, fmt.Errorf("failed to create pipe: %v", err)
	}

	if err := inst.Boot(); err != nil {
		return nil, err
	}

	closeInst = nil
	return inst, nil
}

func validateConfig(cfg *vm.Config) error {
	if cfg.Bin == "" {
		cfg.Bin = "qemu-system-x86_64"
	}
	if _, err := os.Stat(cfg.Kernel); err != nil {
		return fmt.Errorf("kernel file '%v' does not exist: %v", cfg.Kernel, err)
	}
	if _, err := os.Stat(cfg.Image); err != nil {
		return fmt.Errorf("image file '%v' does not exist: %v", cfg.Image, err)
	}
	if _, err := os.Stat(cfg.Sshkey); err != nil {
		return fmt.Errorf("ssh key '%v' does not exist: %v", cfg.Sshkey, err)
	}
	if cfg.Cpu <= 0 || cfg.Cpu > 1024 {
		return fmt.Errorf("bad qemu cpu: %v, want [1-1024]", cfg.Cpu)
	}
	if cfg.Mem < 128 || cfg.Mem > 1048576 {
		return fmt.Errorf("bad qemu mem: %v, want [128-1048576]", cfg.Mem)
	}
	return nil
}

func (inst *instance) HostAddr() string {
	return "10.0.2.10"
}

func (inst *instance) Close() {
	if inst.qemu != nil {
		inst.qemu.Process.Kill()
		err := <-inst.waiterC
		inst.waiterC <- err // repost it for waiting goroutines
		<-inst.readerC
	}
	if inst.rpipe != nil {
		inst.rpipe.Close()
	}
	if inst.wpipe != nil {
		inst.wpipe.Close()
	}
	os.RemoveAll(inst.cfg.Workdir)
}

func (inst *instance) Boot() error {
	for {
		// Find an unused TCP port.
		inst.port = rand.Intn(64<<10-1<<10) + 1<<10
		ln, err := net.Listen("tcp", fmt.Sprintf("localhost:%v", inst.port))
		if err == nil {
			ln.Close()
{'fraction_non_alphanumeric': 0.16304914047577704, 'fraction_numerical': 0.020836950859524223, 'mean_word_length': 3.143884892086331, 'pattern_counts': {'":': 0, '<': 27, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 2, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '715070', 'n_tokens_mistral': 2421, 'n_tokens_neox': 2239, 'n_words': 630}