Best Syzkaller code snippet using qemu.qmp
qemu.go
Source:qemu.go
...31const (32 // Path of QEMU (installed in the Docker container)33 binPath = "/usr/bin/qemu-system-x86_64"34 // QEMU QMP Socket35 qmpUDS = "/tmp/qmp-socket"36 // console socket37 consoleUDS = "console.sock"38 // shutdown timeout39 powerdownTimeout = 1 * time.Minute40)41// These kernel parameters will be appended42var kernelParams = [][]string{43 {"tsc", "reliable"},44 {"no_timer_check", ""},45 {"rcupdate.rcu_expedited", "1"},46 {"i8042.direct", "1"},47 {"i8042.dumbkbd", "1"},48 {"i8042.nopnp", "1"},49 {"i8042.noaux", "1"},50 {"noreplace-smp", ""},51 {"reboot", "k"},52 // this is used to read the VM output via the UNIX socket53 {"console", "hvc0"},54 {"console", "hvc1"},55 {"cryptomgr.notests", ""},56 {"net.ifnames", "0"},57 {"pci", "lastbus=0"},58}59type qmpLogger struct {60 *log.Logger61}62func ExecuteQEMU(guest api.Guest) error {63 // create a context64 ctx := context.Background()65 // set the list of QEMU parameters66 qemuConfig, err := createSandbox(ctx, guest)67 if err != nil {68 return fmt.Errorf("failed to create sandbox: %v", err)69 }70 if _, err := qemu.LaunchQemu(qemuConfig, newQMPLogger()); err != nil {71 return fmt.Errorf("failed to launch QEMU instance: %v", err)72 }73 if err := watchConsole(); err != nil {74 return fmt.Errorf("failed to watch console output: %v", err)75 }76 // This channel will be closed when the instance dies.77 disconnectedCh := make(chan struct{})78 // Set up our options.79 cfg := qemu.QMPConfig{Logger: newQMPLogger()}80 // Start monitoring the qemu instance. This functon will block until we have81 // connect to the QMP socket and received the welcome message.82 q, _, err := qemu.QMPStart(ctx, qmpUDS, cfg, disconnectedCh)83 if err != nil {84 return fmt.Errorf("failed to connect to the QMP socket: %v", err)85 }86 // This has to be the first command executed in a QMP session.87 if err := q.ExecuteQMPCapabilities(ctx); err != nil {88 return fmt.Errorf("failed to run QMP commmand: %v", err)89 }90 installSignalHandlers(ctx, q)91 // disconnectedCh is closed when the VM exits. This line blocks until this92 // event occurs.93 <-disconnectedCh94 return nil95}96func newQMPLogger() qmpLogger {97 return qmpLogger{98 logs.Logger,99 }100}101func (l qmpLogger) V(level int32) bool {102 return l.IsLevelEnabled(log.Level(level))103}104func createSandbox(ctx context.Context, guest api.Guest) (qemu.Config, error) {105 knobs := qemu.Knobs{106 NoUserConfig: true,107 NoDefaults: true,108 NoGraphic: true,109 Daemonize: true,110 }111 kernel, err := kernel(guest)112 if err != nil {113 return qemu.Config{}, fmt.Errorf("failed to create kernel object: %v", err)114 }115 mem := memory(guest)116 smp, err := smp(guest)117 if err != nil {118 return qemu.Config{}, fmt.Errorf("failed to create smp object: %v", err)119 }120 devices := buildDevices(guest)121 config := qemu.Config{122 Name: guest.Name,123 Path: binPath,124 Ctx: ctx,125 CPUModel: cpuModel(),126 Machine: machine(),127 VGA: vga(),128 Knobs: knobs,129 Kernel: kernel,130 Memory: mem,131 SMP: smp,132 QMPSockets: qmpSockets(),133 Devices: devices,134 }135 fwcfgs := fwcfgs(guest.OS.IgnitionConfig)136 if fwcfgs != nil {137 config.FwCfg = fwcfgs138 }139 return config, nil140}141func cpuModel() string {142 return "host,pmu=off"143}144func machine() qemu.Machine {145 defaultType := "q35"146 kvmAcceleration := "kvm"147 m := qemu.Machine{148 Type: defaultType,149 Acceleration: kvmAcceleration,150 }151 return m152}153func vga() string {154 return "none"155}156func kernel(guest api.Guest) (qemu.Kernel, error) {157 var kp [][]string158 if !util.FileExists(guest.OS.Kernel) {159 return qemu.Kernel{}, fmt.Errorf("file %s not found", guest.OS.Kernel)160 }161 if !util.FileExists(guest.OS.Initrd) {162 return qemu.Kernel{}, fmt.Errorf("file %s not found", guest.OS.Initrd)163 }164 k := qemu.Kernel{165 Path: guest.OS.Kernel,166 InitrdPath: guest.OS.Initrd,167 }168 for i := range guest.Disks {169 d := guest.Disks[i]170 if d.IsRoot {171 diskSerial := fmt.Sprintf("/dev/disk/by-id/virtio-%s", d.ID)172 rootDisk := []string{"root", diskSerial}173 kp = append(kp, rootDisk)174 break175 }176 }177 // if ignition is found add the parameter178 // Ref: https://docs.flatcar-linux.org/ignition/what-is-ignition/#when-is-ignition-executed179 if guest.OS.IgnitionConfig != "" {180 kp = append(kp, []string{"flatcar.first_boot", "1"})181 }182 kp = append(kp, kernelParams...)183 k.Params = serializeKernelParams(kp)184 return k, nil185}186func serializeKernelParams(params [][]string) string {187 var paramsStr string188 var lastElemIndex = len(params) - 1189 for i, p := range params {190 paramsStr += fmt.Sprintf("%s=%s", p[0], p[1])191 if i != lastElemIndex {192 paramsStr += " "193 }194 }195 return paramsStr196}197func memory(guest api.Guest) qemu.Memory {198 m := qemu.Memory{Size: guest.Memory}199 return m200}201func smp(guest api.Guest) (qemu.SMP, error) {202 cpus, err := strconv.Atoi(guest.CPUs)203 if err != nil {204 return qemu.SMP{}, err205 }206 s := qemu.SMP{CPUs: uint32(cpus)}207 return s, nil208}209func fwcfgs(ignitionConfig string) []qemu.FwCfg {210 var f []qemu.FwCfg211 if ignitionConfig == "" {212 return nil213 }214 name := "opt/org.flatcar-linux/config"215 fwcfg := qemu.FwCfg{216 Name: name,217 File: ignitionConfig,218 }219 f = append(f, fwcfg)220 return f221}222func qmpSockets() []qemu.QMPSocket {223 var q []qemu.QMPSocket224 qmpSocket := qemu.QMPSocket{225 Type: qemu.Unix,226 Name: qmpUDS,227 Server: true,228 NoWait: true,229 }230 q = append(q, qmpSocket)231 return q232}233func buildDevices(guest api.Guest) []qemu.Device {234 var devices []qemu.Device235 // append all the network devices236 devices = appendNetworkDevices(devices, guest.NICs)237 // append all the block devices238 devices = appendBlockDevices(devices, guest.Disks)239 // append all the FS devices240 devices = appendFSDevices(devices, guest.HostVolumes)241 // append console device242 devices = appendConsoleDevice(devices)243 // add random device244 id := "rng0"...
qmp
Using AI Code Generation
1import (2func main() {3 q, err := qmp.NewSocketMonitor("unix", "/tmp/qmp-sock", 2)4 if err != nil {5 fmt.Println("Error:", err)6 }7 defer q.Disconnect()8 if err := q.Connect(); err != nil {9 fmt.Println("Error:", err)10 }11 result, err := q.Run([]byte(`{"execute": "qmp_capabilities"}`))12 if err != nil {13 fmt.Println("Error:", err)14 }15 fmt.Println("QMP capabilities:", string(result))16 result, err = q.Run([]byte(`{"execute": "query-status"}`))17 if err != nil {18 fmt.Println("Error:", err)19 }20 fmt.Println("QMP status:", string(result))21 result, err = q.Run([]byte(`{"execute": "query-chardev"}`))22 if err != nil {23 fmt.Println("Error:", err)24 }25 fmt.Println("QMP chardev:", string(result))26 result, err = q.Run([]byte(`{"execute": "query-block"}`))27 if err != nil {28 fmt.Println("Error:", err)29 }30 fmt.Println("QMP block:", string(result))31}
qmp
Using AI Code Generation
1import (2func main() {3 q, err := qmp.NewSocketMonitor("unix", "/var/run/libvirt/qemu/test.sock", 2)4 if err != nil {5 log.Fatal(err)6 }7 defer q.Disconnect()8 err = q.Connect()9 if err != nil {10 log.Fatal(err)11 }12 err = q.ExecuteQMPCapabilities()13 if err != nil {14 log.Fatal(err)15 }16 err = q.ExecuteQMPStop()17 if err != nil {18 log.Fatal(err)19 }20 err = q.ExecuteQMPCont()21 if err != nil {22 log.Fatal(err)23 }24 err = q.ExecuteQMPSystemPowerdown()25 if err != nil {26 log.Fatal(err)27 }28 err = q.ExecuteQMPQuit()29 if err != nil {30 log.Fatal(err)31 }32 fmt.Println("done")33}34{ "class": "GenericError", "desc": "Operation not permitted" }35I am using the following code to connect to the libvirt socket and use the QMP commands. But when I try to execute the QMP commands, it is giving me the following error: { "class": "GenericError", "desc": "Operation not permitted" } The code is able to connect to the socket and execute the capabilities command. But when I try to execute the QMP commands, it is throwing the above error. Can anyone please help me with this?36I am trying to use QMP to send commands to a VM. I am able to connect to the VM's socket and execute the capabilities command. But when I try to execute the QMP commands, it is giving me the following error: { "class": "GenericError", "desc": "Operation not permitted" }
qmp
Using AI Code Generation
1import (2func main() {3 conn, err := qmp.NewSocketConnection("/var/run/libvirt/qemu/instance-0000001a.sock")4 if err != nil {5 fmt.Println("error")6 }7 qmp := qmp.NewQMP(conn)8 err = qmp.Connect()9 if err != nil {10 fmt.Println("error")11 }12 defer qmp.Disconnect()13 _, err = qmp.Run([]byte(`{"execute": "query-status"}`))14 if err != nil {15 fmt.Println("error")16 }17}18import (19func main() {20 conn, err := qmp.NewSocketConnection("/var/run/libvirt/qemu/instance-0000001a.sock")21 if err != nil {22 fmt.Println("error")23 }24 qmp := qmp.NewQMP(conn)25 err = qmp.Connect()26 if err != nil {27 fmt.Println("error")28 }29 defer qmp.Disconnect()30 _, err = qmp.Run([]byte(`{"execute": "query-status"}`))31 if err != nil {32 fmt.Println("error")33 }34}
qmp
Using AI Code Generation
1import (2func main() {3 conn, err := qmp.NewSocketConnection("/tmp/qmp-socket")4 if err != nil {5 fmt.Println(err)6 }7 defer conn.Close()8 q, err := qmp.NewQMP(conn)9 if err != nil {10 fmt.Println(err)11 }12 resp, err := q.ExecuteQMPSystemPowerdown()13 if err != nil {14 fmt.Println(
qmp
Using AI Code Generation
1import (2func main() {3 conn, err := qmp.NewSocketConnection("/var/run/qemu/qmp-sock")4 if err != nil {5 log.Fatal(err)6 }7 defer conn.Close()8 q, err := qmp.NewQMP(conn)9 if err != nil {10 log.Fatal(err)11 }12 defer q.Shutdown()13 if err := q.ExecuteQMPCapabilities(); err != nil {14 log.Fatal(err)15 }16 status, err := q.ExecuteQueryStatus()17 if err != nil {18 log.Fatal(err)19 }20 fmt.Printf("status: %v21 blocks, err := q.ExecuteQueryBlock()22 if err != nil {23 log.Fatal(err)24 }25 for _, block := range blocks.Return {26 fmt.Printf("block: %v27 }28}
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!