xref: /openbmc/qemu/tests/qemu-iotests/common.qemu (revision 1da79ecc)
1#!/usr/bin/env bash
2#
3# This allows for launching of multiple QEMU instances, with independent
4# communication possible to each instance.
5#
6# Each instance can choose, at launch, to use either the QMP or the
7# HMP (monitor) interface.
8#
9# All instances are cleaned up via _cleanup_qemu, including killing the
10# running qemu instance.
11#
12# Copyright (C) 2014 Red Hat, Inc.
13#
14# This program is free software; you can redistribute it and/or modify
15# it under the terms of the GNU General Public License as published by
16# the Free Software Foundation; either version 2 of the License, or
17# (at your option) any later version.
18#
19# This program is distributed in the hope that it will be useful,
20# but WITHOUT ANY WARRANTY; without even the implied warranty of
21# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22# GNU General Public License for more details.
23#
24# You should have received a copy of the GNU General Public License
25# along with this program.  If not, see <http://www.gnu.org/licenses/>.
26#
27
28QEMU_COMM_TIMEOUT=10
29
30QEMU_FIFO_IN="${QEMU_TEST_DIR}/qmp-in-$$"
31QEMU_FIFO_OUT="${QEMU_TEST_DIR}/qmp-out-$$"
32
33QEMU_HANDLE=0
34export _QEMU_HANDLE=0
35
36# If bash version is >= 4.1, these will be overwritten and dynamic
37# file descriptor values assigned.
38_out_fd=3
39_in_fd=4
40
41# Wait for expected QMP response from QEMU.  Will time out
42# after 10 seconds, which counts as failure.
43#
44# Override QEMU_COMM_TIMEOUT for a timeout different than the
45# default 10 seconds
46#
47# $1: The handle to use
48# $2+ All remaining arguments comprise the string to search for
49#    in the response.
50#
51# If $silent is set to anything but an empty string, then
52# response is not echoed out.
53# If $mismatch_only is set, only non-matching responses will
54# be echoed.
55#
56# If $success_or_failure is set, the meaning of the arguments is
57# changed as follows:
58# $2: A string to search for in the response; if found, this indicates
59#     success and ${QEMU_STATUS[$1]} is set to 0.
60# $3: A string to search for in the response; if found, this indicates
61#     failure and the test is either aborted (if $qemu_error_no_exit
62#     is not set) or ${QEMU_STATUS[$1]} is set to -1 (otherwise).
63_timed_wait_for()
64{
65    local h=${1}
66    shift
67
68    if [ -z "${success_or_failure}" ]; then
69        success_match=${*}
70        failure_match=
71    else
72        success_match=${1}
73        failure_match=${2}
74    fi
75
76    timeout=yes
77
78    QEMU_STATUS[$h]=0
79    while IFS= read -t ${QEMU_COMM_TIMEOUT} resp <&${QEMU_OUT[$h]}
80    do
81        if [ -z "${silent}" ] && [ -z "${mismatch_only}" ]; then
82            echo "${resp}" | _filter_testdir | _filter_qemu \
83                           | _filter_qemu_io | _filter_qmp | _filter_hmp
84        fi
85        if [ -n "${failure_match}" ]; then
86            grep -q "${failure_match}" < <(echo "${resp}")
87            if [ $? -eq 0 ]; then
88                timeout=
89                break
90            fi
91        fi
92        grep -q "${success_match}" < <(echo "${resp}")
93        if [ $? -eq 0 ]; then
94            return
95        fi
96        if [ -z "${silent}" ] && [ -n "${mismatch_only}" ]; then
97            echo "${resp}" | _filter_testdir | _filter_qemu \
98                           | _filter_qemu_io | _filter_qmp | _filter_hmp
99        fi
100
101    done
102    QEMU_STATUS[$h]=-1
103    if [ -z "${qemu_error_no_exit}" ]; then
104        if [ -n "${timeout}" ]; then
105            echo "Timeout waiting for ${success_match} on handle ${h}"
106        else
107            echo "Wrong response matching ${failure_match} on handle ${h}"
108        fi
109        exit 1  # Timeout or wrong match mean the test failed
110    fi
111}
112
113
114# Sends QMP or HMP command to QEMU, and waits for the expected response
115#
116# $1:       QEMU handle to use
117# $2:       String of the QMP command to send
118# ${@: -1}  (Last string passed)
119#             String that the QEMU response should contain. If it is a null
120#             string, do not wait for a response
121#
122# Set qemu_cmd_repeat to the number of times to repeat the cmd
123# until either timeout, or a response.  If it is not set, or <=0,
124# then the command is only sent once.
125#
126# If neither $silent nor $mismatch_only is set, and $cmd begins with '{',
127# echo the command before sending it the first time.
128#
129# If $qemu_error_no_exit is set, then even if the expected response
130# is not seen, we will not exit.  $QEMU_STATUS[$1] will be set it -1 in
131# that case.
132#
133# If $success_or_failure is set, then the last two strings are the
134# strings the response will be scanned for.  The first of the two
135# indicates success, the latter indicates failure.  Failure is handled
136# like a timeout.
137_send_qemu_cmd()
138{
139    local h=${1}
140    local count=1
141    local cmd=
142    local use_error=${qemu_error_no_exit}
143    shift
144
145    if [ ${qemu_cmd_repeat} -gt 0 ] 2>/dev/null; then
146        count=${qemu_cmd_repeat}
147        use_error="no"
148    fi
149
150    cmd=$1
151    shift
152
153    # Display QMP being sent, but not HMP (since HMP already echoes its
154    # input back to output); decide based on leading '{'
155    if [ -z "$silent" ] && [ -z "$mismatch_only" ] &&
156            [ "$cmd" != "${cmd#\{}" ]; then
157        echo "${cmd}" | _filter_testdir | _filter_imgfmt
158    fi
159    while [ ${count} -gt 0 ]
160    do
161        echo "${cmd}" >&${QEMU_IN[${h}]}
162        if [ -n "${1}" ]; then
163            if [ -z "${success_or_failure}" ]; then
164                qemu_error_no_exit=${use_error} _timed_wait_for ${h} "${1}"
165            else
166                qemu_error_no_exit=${use_error} _timed_wait_for ${h} "${1}" "${2}"
167            fi
168            if [ ${QEMU_STATUS[$h]} -eq 0 ]; then
169                return
170            fi
171        fi
172        let count--;
173    done
174    if [ ${QEMU_STATUS[$h]} -ne 0 ] && [ -z "${qemu_error_no_exit}" ]; then
175        echo "Timeout waiting for ${1} on handle ${h}"
176        exit 1 #Timeout means the test failed
177    fi
178}
179
180
181# Launch a QEMU process.
182#
183# Input parameters:
184# $qemu_comm_method: set this variable to 'monitor' (case insensitive)
185#                    to use the QEMU HMP monitor for communication.
186#                    Otherwise, the default of QMP is used.
187# $qmp_pretty: Set this variable to 'y' to enable QMP pretty printing.
188# $keep_stderr: Set this variable to 'y' to keep QEMU's stderr output on stderr.
189#               If this variable is empty, stderr will be redirected to stdout.
190# Returns:
191# $QEMU_HANDLE: set to a handle value to communicate with this QEMU instance.
192#
193_launch_qemu()
194{
195    local comm=
196    local fifo_out=
197    local fifo_in=
198
199    if (shopt -s nocasematch; [[ "${qemu_comm_method}" == "monitor" ]])
200    then
201        comm="-monitor stdio"
202    else
203        local qemu_comm_method="qmp"
204        if [ "$qmp_pretty" = "y" ]; then
205            comm="-monitor none -qmp-pretty stdio"
206        else
207            comm="-monitor none -qmp stdio"
208        fi
209    fi
210
211    fifo_out=${QEMU_FIFO_OUT}_${_QEMU_HANDLE}
212    fifo_in=${QEMU_FIFO_IN}_${_QEMU_HANDLE}
213    mkfifo "${fifo_out}"
214    mkfifo "${fifo_in}"
215
216    object_options=
217    if [ -n "$IMGKEYSECRET" ]; then
218        object_options="--object secret,id=keysec0,data=$IMGKEYSECRET"
219    fi
220
221    if [ -z "$keep_stderr" ]; then
222        QEMU_NEED_PID='y'\
223        ${QEMU} ${object_options} -nographic -serial none ${comm} "${@}" >"${fifo_out}" \
224                                                       2>&1 \
225                                                       <"${fifo_in}" &
226    elif [ "$keep_stderr" = "y" ]; then
227        QEMU_NEED_PID='y'\
228        ${QEMU} ${object_options} -nographic -serial none ${comm} "${@}" >"${fifo_out}" \
229                                                       <"${fifo_in}" &
230    else
231        exit 1
232    fi
233
234    if [[ "${BASH_VERSINFO[0]}" -ge "5" ||
235        ("${BASH_VERSINFO[0]}" -ge "4"  &&  "${BASH_VERSINFO[1]}" -ge "1") ]]
236    then
237        # bash >= 4.1 required for automatic fd
238        exec {_out_fd}<"${fifo_out}"
239        exec {_in_fd}>"${fifo_in}"
240    else
241        let _out_fd++
242        let _in_fd++
243        eval "exec ${_out_fd}<'${fifo_out}'"
244        eval "exec ${_in_fd}>'${fifo_in}'"
245    fi
246
247    QEMU_OUT[${_QEMU_HANDLE}]=${_out_fd}
248    QEMU_IN[${_QEMU_HANDLE}]=${_in_fd}
249    QEMU_STATUS[${_QEMU_HANDLE}]=0
250
251    if [ "${qemu_comm_method}" == "qmp" ]
252    then
253        # Don't print response, since it has version information in it
254        silent=yes _timed_wait_for ${_QEMU_HANDLE} "capabilities"
255        if [ "$qmp_pretty" = "y" ]; then
256            silent=yes _timed_wait_for ${_QEMU_HANDLE} "^}"
257        fi
258    fi
259    QEMU_HANDLE=${_QEMU_HANDLE}
260    let _QEMU_HANDLE++
261}
262
263
264# Silently kills the QEMU process
265#
266# If $wait is set to anything other than the empty string, the process will not
267# be killed but only waited for, and any output will be forwarded to stdout. If
268# $wait is empty, the process will be killed and all output will be suppressed.
269_cleanup_qemu()
270{
271    # QEMU_PID[], QEMU_IN[], QEMU_OUT[] all use same indices
272    for i in "${!QEMU_OUT[@]}"
273    do
274        local QEMU_PID
275        if [ -f "${QEMU_TEST_DIR}/qemu-${i}.pid" ]; then
276            read QEMU_PID < "${QEMU_TEST_DIR}/qemu-${i}.pid"
277            rm -f "${QEMU_TEST_DIR}/qemu-${i}.pid"
278            if [ -z "${wait}" ] && [ -n "${QEMU_PID}" ]; then
279                kill -KILL ${QEMU_PID} 2>/dev/null
280            fi
281            if [ -n "${QEMU_PID}" ]; then
282                wait ${QEMU_PID} 2>/dev/null # silent kill
283            fi
284        fi
285
286        if [ -n "${wait}" ]; then
287            cat <&${QEMU_OUT[$i]} | _filter_testdir | _filter_qemu \
288                                  | _filter_qemu_io | _filter_qmp | _filter_hmp
289        fi
290        rm -f "${QEMU_FIFO_IN}_${i}" "${QEMU_FIFO_OUT}_${i}"
291        eval "exec ${QEMU_IN[$i]}<&-"   # close file descriptors
292        eval "exec ${QEMU_OUT[$i]}<&-"
293
294        unset QEMU_IN[$i]
295        unset QEMU_OUT[$i]
296    done
297}
298