How to use Copy method of qemu Package

Best Syzkaller code snippet using qemu.Copy

qemu.go

Source:qemu.go Github

copy

Full Screen

1// Copyright 2019 The Fuchsia Authors. All rights reserved.2// Use of this source code is governed by a BSD-style license that can be3// found in the LICENSE file.4package target5import (6 "context"7 "fmt"8 "io"9 "io/ioutil"10 "log"11 "net"12 "os"13 "os/exec"14 "path/filepath"15 "go.fuchsia.dev/fuchsia/tools/bootserver/lib"16 "go.fuchsia.dev/fuchsia/tools/lib/iomisc"17 "go.fuchsia.dev/fuchsia/tools/qemu"18)19const (20 // qemuSystemPrefix is the prefix of the QEMU binary name, which is of the21 // form qemu-system-<QEMU arch suffix>.22 qemuSystemPrefix = "qemu-system"23 // DefaultInterfaceName is the name given to the emulated tap interface.24 defaultInterfaceName = "qemu"25 // DefaultMACAddr is the default MAC address given to a QEMU target.26 defaultMACAddr = "52:54:00:63:5e:7a"27 // DefaultNodename is the default nodename given to an target with the default QEMU MAC address.28 defaultNodename = "step-atom-yard-juicy"29)30// qemuTargetMapping maps the Fuchsia target name to the name recognized by QEMU.31var qemuTargetMapping = map[string]string{32 "x64": qemu.TargetX86_64,33 "arm64": qemu.TargetAArch64,34}35// MinFS is the configuration for the MinFS filesystem image.36type MinFS struct {37 // Image is the path to the filesystem image.38 Image string `json:"image"`39 // PCIAddress is the PCI address to map the device at.40 PCIAddress string `json:"pci_address"`41}42// QEMUConfig is a QEMU configuration.43type QEMUConfig struct {44 // Path is a path to a directory that contains QEMU system binary.45 Path string `json:"path"`46 // Target is the QEMU target to emulate.47 Target string `json:"target"`48 // CPU is the number of processors to emulate.49 CPU int `json:"cpu"`50 // Memory is the amount of memory (in MB) to provide.51 Memory int `json:"memory"`52 // KVM specifies whether to enable hardware virtualization acceleration.53 KVM bool `json:"kvm"`54 // Whether User networking is enabled; if false, a Tap interface will be used.55 UserNetworking bool `json:"user_networking"`56 // MinFS is the filesystem to mount as a device.57 MinFS *MinFS `json:"minfs,omitempty"`58}59// QEMUTarget is a QEMU target.60type QEMUTarget struct {61 config QEMUConfig62 opts Options63 c chan error64 cmd *exec.Cmd65 status error66}67// NewQEMUTarget returns a new QEMU target with a given configuration.68func NewQEMUTarget(config QEMUConfig, opts Options) *QEMUTarget {69 return &QEMUTarget{70 config: config,71 opts: opts,72 c: make(chan error),73 }74}75// Nodename returns the name of the target node.76func (t *QEMUTarget) Nodename() string {77 return defaultNodename78}79// IPv4Addr returns a nil address, as DHCP is not currently configured.80func (t *QEMUTarget) IPv4Addr() (net.IP, error) {81 return nil, nil82}83// Serial returns the serial device associated with the target for serial i/o.84func (t *QEMUTarget) Serial() io.ReadWriteCloser {85 return nil86}87// SSHKey returns the private SSH key path associated with the authorized key to be pavet.88func (t *QEMUTarget) SSHKey() string {89 return t.opts.SSHKey90}91// Start starts the QEMU target.92func (t *QEMUTarget) Start(ctx context.Context, images []bootserver.Image, args []string) error {93 qemuTarget, ok := qemuTargetMapping[t.config.Target]94 if !ok {95 return fmt.Errorf("invalid target %q", t.config.Target)96 }97 if t.config.Path == "" {98 return fmt.Errorf("directory must be set")99 }100 qemuSystem := filepath.Join(t.config.Path, fmt.Sprintf("%s-%s", qemuSystemPrefix, qemuTarget))101 if _, err := os.Stat(qemuSystem); err != nil {102 return fmt.Errorf("could not find qemu-system binary %q: %v", qemuSystem, err)103 }104 var qemuKernel, zirconA, storageFull bootserver.Image105 for _, img := range images {106 switch img.Name {107 case "qemu-kernel":108 qemuKernel = img109 case "zircon-a":110 zirconA = img111 case "storage-full":112 storageFull = img113 }114 }115 if qemuKernel.Reader == nil {116 return fmt.Errorf("could not find qemu-kernel")117 }118 if zirconA.Reader == nil {119 return fmt.Errorf("could not find zircon-a")120 }121 var drives []qemu.Drive122 if storageFull.Reader != nil {123 drives = append(drives, qemu.Drive{124 ID: "maindisk",125 File: getImageName(storageFull),126 })127 }128 if t.config.MinFS != nil {129 if _, err := os.Stat(t.config.MinFS.Image); err != nil {130 return fmt.Errorf("could not find minfs image %q: %v", t.config.MinFS.Image, err)131 }132 file, err := filepath.Abs(t.config.MinFS.Image)133 if err != nil {134 return err135 }136 // Swarming hard-links Isolate downloads with a cache and the very same137 // cached minfs image will be used across multiple tasks. To ensure138 // that it remains blank, we must break its link.139 if err := overwriteFileWithCopy(file); err != nil {140 return err141 }142 drives = append(drives, qemu.Drive{143 ID: "testdisk",144 File: file,145 Addr: t.config.MinFS.PCIAddress,146 })147 }148 netdev := qemu.Netdev{149 ID: "net0",150 MAC: defaultMACAddr,151 }152 if t.config.UserNetworking {153 netdev.User = &qemu.NetdevUser{}154 } else {155 netdev.Tap = &qemu.NetdevTap{156 Name: defaultInterfaceName,157 }158 }159 networks := []qemu.Netdev{netdev}160 config := qemu.Config{161 Binary: qemuSystem,162 Target: qemuTarget,163 CPU: t.config.CPU,164 Memory: t.config.Memory,165 KVM: t.config.KVM,166 Kernel: getImageName(qemuKernel),167 Initrd: getImageName(zirconA),168 Drives: drives,169 Networks: networks,170 }171 // The system will halt on a kernel panic instead of rebooting.172 args = append(args, "kernel.halt-on-panic=true")173 // Print a message if `dm poweroff` times out.174 args = append(args, "devmgr.suspend-timeout-debug=true")175 // Do not print colors.176 args = append(args, "TERM=dumb")177 if t.config.Target == "x64" {178 // Necessary to redirect to stdout.179 args = append(args, "kernel.serial=legacy")180 }181 invocation, err := qemu.CreateInvocation(config, args)182 if err != nil {183 return err184 }185 // The QEMU command needs to be invoked within an empty directory, as QEMU186 // will attempt to pick up files from its working directory, one notable187 // culprit being multiboot.bin. This can result in strange behavior.188 workdir, err := ioutil.TempDir("", "qemu-working-dir")189 if err != nil {190 return err191 }192 for _, img := range []bootserver.Image{qemuKernel, zirconA, storageFull} {193 if img.Reader != nil {194 if err := transferToDir(workdir, img); err != nil {195 return err196 }197 }198 }199 t.cmd = &exec.Cmd{200 Path: invocation[0],201 Args: invocation,202 Dir: workdir,203 Stdout: os.Stdout,204 Stderr: os.Stderr,205 }206 log.Printf("QEMU invocation:\n%s", invocation)207 if err := t.cmd.Start(); err != nil {208 os.RemoveAll(workdir)209 return fmt.Errorf("failed to start: %v", err)210 }211 // Ensure that the working directory when QEMU finishes whether the Wait212 // method is invoked or not.213 go func() {214 defer os.RemoveAll(workdir)215 t.c <- qemu.CheckExitCode(t.cmd.Wait())216 }()217 return nil218}219// Wait waits for the QEMU target to stop.220func (t *QEMUTarget) Restart(ctx context.Context) error {221 return ErrUnimplemented222}223// Stop stops the QEMU target.224func (t *QEMUTarget) Stop(ctx context.Context) error {225 return t.cmd.Process.Kill()226}227// Wait waits for the QEMU target to stop.228func (t *QEMUTarget) Wait(ctx context.Context) error {229 return <-t.c230}231// getImageName returns the absolute path to the image if it exists on the filesystem, else just the image name.232func getImageName(img bootserver.Image) string {233 if f, ok := img.Reader.(*os.File); ok {234 absName, err := filepath.Abs(f.Name())235 if err != nil {236 log.Printf("failed to get abs path: %v", err)237 } else {238 return absName239 }240 }241 return img.Name242}243func transferToDir(dir string, img bootserver.Image) error {244 filename := filepath.Join(dir, img.Name)245 if filepath.IsAbs(getImageName(img)) {246 log.Printf("img %s has path: %s\n", img.Name, getImageName(img))247 } else {248 tmp, err := os.Create(filename)249 if err != nil {250 return err251 }252 defer tmp.Close()253 if _, err := io.Copy(tmp, iomisc.ReaderAtToReader(img.Reader)); err != nil {254 return err255 }256 log.Printf("transferred %s to %s\n", img.Name, filename)257 }258 return nil259}260func overwriteFileWithCopy(path string) error {261 tmpfile, err := ioutil.TempFile(filepath.Dir(path), "botanist")262 if err != nil {263 return err264 }265 defer tmpfile.Close()266 if err := copyFile(path, tmpfile.Name()); err != nil {267 return err268 }269 return os.Rename(tmpfile.Name(), path)270}271func copyFile(src, dest string) error {272 in, err := os.Open(src)273 if err != nil {274 return err275 }276 defer in.Close()277 info, err := in.Stat()278 if err != nil {279 return err280 }281 out, err := os.OpenFile(dest, os.O_WRONLY|os.O_CREATE, info.Mode().Perm())282 if err != nil {283 return err284 }285 defer out.Close()286 _, err = io.Copy(out, in)287 return err288}...

Full Screen

Full Screen

qemu_amd64_test.go

Source:qemu_amd64_test.go Github

copy

Full Screen

1//go:build linux2// +build linux3// Copyright (c) 2018 Intel Corporation4//5// SPDX-License-Identifier: Apache-2.06//7package virtcontainers8import (9 "context"10 "fmt"11 "os"12 "testing"13 "github.com/intel-go/cpuid"14 govmmQemu "github.com/kata-containers/kata-containers/src/runtime/pkg/govmm/qemu"15 "github.com/kata-containers/kata-containers/src/runtime/virtcontainers/types"16 "github.com/stretchr/testify/assert"17)18func qemuConfig(machineType string) HypervisorConfig {19 return HypervisorConfig{20 HypervisorMachineType: machineType,21 }22}23func newTestQemu(assert *assert.Assertions, machineType string) qemuArch {24 config := qemuConfig(machineType)25 arch, err := newQemuArch(config)26 assert.NoError(err)27 return arch28}29func TestQemuAmd64BadMachineType(t *testing.T) {30 assert := assert.New(t)31 config := qemuConfig("no-such-machine-type")32 _, err := newQemuArch(config)33 assert.Error(err)34}35func TestQemuAmd64Capabilities(t *testing.T) {36 assert := assert.New(t)37 amd64 := newTestQemu(assert, QemuQ35)38 caps := amd64.capabilities()39 assert.True(caps.IsBlockDeviceHotplugSupported())40 amd64 = newTestQemu(assert, QemuMicrovm)41 caps = amd64.capabilities()42 assert.False(caps.IsBlockDeviceHotplugSupported())43}44func TestQemuAmd64Bridges(t *testing.T) {45 assert := assert.New(t)46 len := 547 amd64 := newTestQemu(assert, QemuMicrovm)48 amd64.bridges(uint32(len))49 bridges := amd64.getBridges()50 assert.Nil(bridges)51 amd64 = newTestQemu(assert, QemuQ35)52 amd64.bridges(uint32(len))53 bridges = amd64.getBridges()54 assert.Len(bridges, len)55 for i, b := range bridges {56 id := fmt.Sprintf("%s-bridge-%d", types.PCI, i)57 assert.Equal(types.PCI, b.Type)58 assert.Equal(id, b.ID)59 assert.NotNil(b.Devices)60 }61}62func TestQemuAmd64CPUModel(t *testing.T) {63 assert := assert.New(t)64 amd64 := newTestQemu(assert, QemuQ35)65 expectedOut := defaultCPUModel66 model := amd64.cpuModel()67 assert.Equal(expectedOut, model)68 amd64.disableNestingChecks()69 base, ok := amd64.(*qemuAmd64)70 assert.True(ok)71 base.vmFactory = true72 expectedOut = defaultCPUModel73 model = amd64.cpuModel()74 assert.Equal(expectedOut, model)75}76func TestQemuAmd64MemoryTopology(t *testing.T) {77 assert := assert.New(t)78 amd64 := newTestQemu(assert, QemuQ35)79 memoryOffset := uint64(1024)80 hostMem := uint64(100)81 mem := uint64(120)82 slots := uint8(10)83 expectedMemory := govmmQemu.Memory{84 Size: fmt.Sprintf("%dM", mem),85 Slots: slots,86 MaxMem: fmt.Sprintf("%dM", hostMem+memoryOffset),87 }88 m := amd64.memoryTopology(mem, hostMem, slots)89 assert.Equal(expectedMemory, m)90}91func TestQemuAmd64AppendImage(t *testing.T) {92 assert := assert.New(t)93 f, err := os.CreateTemp("", "img")94 assert.NoError(err)95 defer func() { _ = f.Close() }()96 defer func() { _ = os.Remove(f.Name()) }()97 imageStat, err := f.Stat()98 assert.NoError(err)99 // Save default supportedQemuMachines options100 machinesCopy := make([]govmmQemu.Machine, len(supportedQemuMachines))101 assert.Equal(len(supportedQemuMachines), copy(machinesCopy, supportedQemuMachines))102 cfg := qemuConfig(QemuQ35)103 cfg.ImagePath = f.Name()104 cfg.DisableImageNvdimm = false105 amd64, err := newQemuArch(cfg)106 assert.NoError(err)107 assert.Contains(amd64.machine().Options, qemuNvdimmOption)108 expectedOut := []govmmQemu.Device{109 govmmQemu.Object{110 Driver: govmmQemu.NVDIMM,111 Type: govmmQemu.MemoryBackendFile,112 DeviceID: "nv0",113 ID: "mem0",114 MemPath: f.Name(),115 Size: (uint64)(imageStat.Size()),116 ReadOnly: true,117 },118 }119 devices, err := amd64.appendImage(context.Background(), nil, f.Name())120 assert.NoError(err)121 assert.Equal(expectedOut, devices)122 // restore default supportedQemuMachines options123 assert.Equal(len(supportedQemuMachines), copy(supportedQemuMachines, machinesCopy))124 cfg.DisableImageNvdimm = true125 amd64, err = newQemuArch(cfg)126 assert.NoError(err)127 assert.NotContains(amd64.machine().Options, qemuNvdimmOption)128 found := false129 devices, err = amd64.appendImage(context.Background(), nil, f.Name())130 assert.NoError(err)131 for _, d := range devices {132 if b, ok := d.(govmmQemu.BlockDevice); ok {133 assert.Equal(b.Driver, govmmQemu.VirtioBlock)134 assert.True(b.ShareRW)135 found = true136 }137 }138 assert.True(found)139 // restore default supportedQemuMachines options140 assert.Equal(len(supportedQemuMachines), copy(supportedQemuMachines, machinesCopy))141}142func TestQemuAmd64AppendBridges(t *testing.T) {143 var devices []govmmQemu.Device144 assert := assert.New(t)145 // Check Q35146 amd64 := newTestQemu(assert, QemuQ35)147 amd64.bridges(1)148 bridges := amd64.getBridges()149 assert.Len(bridges, 1)150 devices = []govmmQemu.Device{}151 devices = amd64.appendBridges(devices)152 assert.Len(devices, 1)153 expectedOut := []govmmQemu.Device{154 govmmQemu.BridgeDevice{...

Full Screen

Full Screen

exec_binfmt.go

Source:exec_binfmt.go Github

copy

Full Screen

...53 root := m.idmap.RootPair()54 uid = root.UID55 gid = root.GID56 }57 if err := copy.Copy(context.TODO(), filepath.Dir(m.path), filepath.Base(m.path), tmpdir, qemuMountName, func(ci *copy.CopyInfo) {58 m := 055559 ci.Mode = &m60 }, copy.WithChown(uid, gid)); err != nil {61 return nil, nil, err62 }63 ret = true64 return []mount.Mount{{65 Type: "bind",66 Source: filepath.Join(tmpdir, qemuMountName),67 Options: []string{"ro", "bind"},68 }}, func() error {69 return os.RemoveAll(tmpdir)70 }, nil71}...

Full Screen

Full Screen

Copy

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 q, err := qemu.NewQemu("/usr/bin/qemu-system-x86_64", qemu.QemuArch("x86_64"), qemu.QemuMachine("pc"))4 if err != nil {5 fmt.Println(err)6 }7 err = q.Open("image.img")8 if err != nil {9 fmt.Println(err)10 }11 err = q.Copy("/etc/passwd", "passwd")12 if err != nil {13 fmt.Println(err)14 }15}16q.Copy("/etc/passwd", "passwd")17q.Copy("/etc/passwd", "/tmp/passwd")18q.Copy("passwd", "/etc/passwd")19q.Copy("/tmp/passwd", "/etc/passwd")20q.Copy("passwd", "passwd")21q.Copy("/tmp/passwd", "/tmp/passwd")

Full Screen

Full Screen

Copy

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 q, err := qemu.NewQemu("/usr/bin/qemu-system-x86_64", qemu.Virtio9P)4 if err != nil {5 panic(err)6 }7 q.SetMachine("pc")8 q.AddDrive("/home/username/Downloads/centos7.qcow2", qemu.DiskFormatQCOW2, qemu.DriveCacheNone)9 q.AddNet("user")10 q.SetCpus(2)11 q.SetMemory("1024")12 q.SetKernel("/home/username/Downloads/vmlinuz-3.10.0-514.el7.x86_64")13 q.SetInitrd("/home/username/Downloads/initramfs-3.10.0-514.el7.x86_64.img")14 q.SetAppend("console=ttyS0")15 q.SetDisplay("none")16 q.SetSerial("mon:stdio")17 q.SetVirtfs("local,path=/home/username/Downloads,security_model=none,mount_tag=host0")18 q.Start()19 q.Stop()20 q.Copy("/home/username/Downloads/2.go", "/home/username/2.go")21}

Full Screen

Full Screen

Copy

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 q, err := qemu.NewQemu("/usr/bin/qemu-system-x86_64", qemu.Options{Verbose: true})4 if err != nil {5 panic(err)6 }7 err = q.CreateImage("/home/ashish/Downloads/centos-7-x86_64.qcow2", qemu.ImageOptions{BackingFile: "/home/ashish/Downloads/centos-7-x86_64.qcow2", Format: "qcow2", Size: "20G"})8 if err != nil {9 panic(err)10 }11}12import (

Full Screen

Full Screen

Copy

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 q := qemu.NewQemu("/usr/bin/qemu-system-x86_64", qemu.Virtio9P)4 drive := qemu.Drive{5 }6 q.AddDrive(drive)7 nic := qemu.NetDevice{8 }9 q.AddNetwork(nic)10 share := qemu.Virtio9PShare{11 }12 q.AddVirtio9PShare(share)13 if err := q.Launch(); err != nil {14 fmt.Println("error launching qemu:", err)15 }16 if err := q.Wait(); err != nil {17 fmt.Println("error waiting for qemu to exit:", err)18 }19 if err := q.Copy("/home/user/9p/README.md", "/tmp/README.md"); err != nil {20 fmt.Println("error copying file from guest to host:", err)21 }22}23import (24func main() {25 q := qemu.NewQemu("/usr/bin/qemu-system-x86_64", qemu.Virtio9P)26 drive := qemu.Drive{27 }28 q.AddDrive(drive)29 nic := qemu.NetDevice{30 }31 q.AddNetwork(nic)32 share := qemu.Virtio9PShare{33 }34 q.AddVirtio9PShare(share)35 if err := q.Launch();

Full Screen

Full Screen

Copy

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 q := qemu.NewQemu("/usr/bin/qemu-system-x86_64", "qemu-system-x86_64")4 err := q.Copy("/home/user/Downloads/centos7.qcow2", "/home/user/Downloads/centos7_copy.qcow2")5 if err != nil {6 fmt.Println("Error while copying disk image")7 fmt.Println(err)8 }9}

Full Screen

Full Screen

Copy

Using AI Code Generation

copy

Full Screen

1import "fmt"2type Qemu struct {3}4func (q Qemu) Copy() Qemu {5}6func main() {7 q1 := Qemu{"Qemu", 20, "Earth"}8 q2 := q1.Copy()9 fmt.Println(q2)10}11import "fmt"12type Qemu struct {13}14func (q *Qemu) Copy() *Qemu {15}16func main() {17 q1 := Qemu{"Qemu", 20, "Earth"}18 q2 := q1.Copy()19 fmt.Println(q2)20}21import "fmt"22type Qemu struct {23}24func (q Qemu) Copy() Qemu {25}26func main() {27 q1 := Qemu{"Qemu", 20, "Earth"}28 q2 := q1.Copy()29 fmt.Println(q2)30 fmt.Println(q2)31}32import "fmt"33type Qemu struct {34}35func (q *Qemu) Copy() *Qemu {36}37func main() {38 q1 := Qemu{"Qemu", 20, "Earth"}39 q2 := q1.Copy()40 fmt.Println(q2)

Full Screen

Full Screen

Copy

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 q := qemu.New()4 q.Copy("hostpath", "guestpath")5 q.Copy("guestpath", "hostpath")6}7import (8func main() {9 q := qemu.New()10 q.Run("command")11}12import (13func main() {14 q := qemu.New()15 q.Run("command")16}17import (18func main() {19 q := qemu.New()20 q.Run("command")21}22import (23func main() {24 q := qemu.New()25 q.Run("command")26}27import (28func main() {29 q := qemu.New()30 q.Run("command")31}32import (33func main() {34 q := qemu.New()35 q.Run("command")36}

Full Screen

Full Screen

Copy

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 m, err = qmp.NewSocketMonitor("unix", "/var/run/qemu-guest-agent.0", 2*time.Second)4 if err != nil {5 fmt.Println(err)6 }7 err = m.Connect()8 if err != nil {9 fmt.Println(err)10 }11 defer m.Disconnect()12 r, e = m.Run([]byte(`{"execute":"guest-file-open","arguments":{"path":"/tmp/test.txt","mode":"w+"}}`))13 if e != nil {14 fmt.Println(e)15 }16 fmt.Println(r)17 r, e = m.Run([]byte(`{"execute":"guest-file-write","arguments":{"handle":0,"buf-b64":"dGVzdA=="}}`))18 if e != nil {19 fmt.Println(e)20 }21 fmt.Println(r)22 r, e = m.Run([]byte(`{"execute":"guest-file-close","arguments":{"handle":0}}`))23 if e != nil {24 fmt.Println(e)25 }26 fmt.Println(r)27}28{"QMP": {"version": {"qemu": {"micro": 0, "minor": 12, "major": 1}, "package": ""}, "capabilities": []}}29{"return": {"count": 5, "eof": false, "offset": 0}}30{"return": {}}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Syzkaller automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful