summaryrefslogtreecommitdiff
path: root/tests
diff options
context:
space:
mode:
authorYonghee Han <onstudy@samsung.com>2016-07-27 16:42:54 +0900
committerYonghee Han <onstudy@samsung.com>2016-07-27 00:56:08 -0700
commita03c4728275d119af5f66c4a69e8d9d5a1730031 (patch)
tree2b4ed9542884bf8b947076c55c4ef1814217cb69 /tests
parent3158f4a51894e46ecb593bffbfd12824e1d6534a (diff)
downloadqemu-a03c4728275d119af5f66c4a69e8d9d5a1730031.tar.gz
qemu-a03c4728275d119af5f66c4a69e8d9d5a1730031.tar.bz2
qemu-a03c4728275d119af5f66c4a69e8d9d5a1730031.zip
Imported Upstream version 2.5.1.1upstream/2.5.1.1
Change-Id: Ie290b0e68882590d8a64fab165a943940b7c98ed
Diffstat (limited to 'tests')
-rw-r--r--tests/.gitignore12
-rw-r--r--tests/Makefile309
-rw-r--r--tests/ahci-test.c158
-rw-r--r--tests/bios-tables-test.c44
-rw-r--r--tests/check-qjson.c25
-rw-r--r--tests/check-qom-proplist.c205
-rw-r--r--tests/crypto-tls-x509-helpers.c487
-rw-r--r--tests/crypto-tls-x509-helpers.h133
-rw-r--r--tests/device-introspect-test.c42
-rw-r--r--tests/ds1338-test.c78
-rw-r--r--tests/fdc-test.c4
-rw-r--r--tests/fw_cfg-test.c4
-rw-r--r--tests/i440fx-test.c2
-rw-r--r--tests/ide-test.c263
-rwxr-xr-xtests/image-fuzzer/runner.py2
-rw-r--r--tests/ivshmem-test.c494
-rw-r--r--tests/libqos/ahci.c2
-rw-r--r--tests/libqos/i2c-imx.c209
-rw-r--r--tests/libqos/i2c.h3
-rw-r--r--tests/libqos/libqos.c54
-rw-r--r--tests/libqos/libqos.h2
-rw-r--r--tests/libqtest.c95
-rw-r--r--tests/libqtest.h14
-rw-r--r--tests/pkix_asn1_tab.c1104
-rw-r--r--tests/qapi-schema/alternate-clash.err2
-rw-r--r--tests/qapi-schema/alternate-clash.json9
-rw-r--r--tests/qapi-schema/alternate-empty.err (renamed from tests/qapi-schema/alternate-good.err)0
-rw-r--r--tests/qapi-schema/alternate-empty.exit (renamed from tests/qapi-schema/alternate-good.exit)0
-rw-r--r--tests/qapi-schema/alternate-empty.json2
-rw-r--r--tests/qapi-schema/alternate-empty.out4
-rw-r--r--tests/qapi-schema/alternate-good.json9
-rw-r--r--tests/qapi-schema/alternate-good.out6
-rw-r--r--tests/qapi-schema/alternate-nested.json2
-rw-r--r--tests/qapi-schema/alternate-unknown.json2
-rw-r--r--tests/qapi-schema/args-alternate.err1
-rw-r--r--tests/qapi-schema/args-alternate.exit (renamed from tests/qapi-schema/data-array-empty.exit)0
-rw-r--r--tests/qapi-schema/args-alternate.json3
-rw-r--r--tests/qapi-schema/args-alternate.out (renamed from tests/qapi-schema/data-array-empty.out)0
-rw-r--r--tests/qapi-schema/args-any.err1
-rw-r--r--tests/qapi-schema/args-any.exit (renamed from tests/qapi-schema/data-array-unknown.exit)0
-rw-r--r--tests/qapi-schema/args-any.json2
-rw-r--r--tests/qapi-schema/args-any.out (renamed from tests/qapi-schema/data-array-unknown.out)0
-rw-r--r--tests/qapi-schema/args-array-empty.err (renamed from tests/qapi-schema/data-array-empty.err)2
-rw-r--r--tests/qapi-schema/args-array-empty.exit (renamed from tests/qapi-schema/data-int.exit)0
-rw-r--r--tests/qapi-schema/args-array-empty.json (renamed from tests/qapi-schema/data-array-empty.json)0
-rw-r--r--tests/qapi-schema/args-array-empty.out (renamed from tests/qapi-schema/data-int.out)0
-rw-r--r--tests/qapi-schema/args-array-unknown.err1
-rw-r--r--tests/qapi-schema/args-array-unknown.exit (renamed from tests/qapi-schema/data-member-array-bad.exit)0
-rw-r--r--tests/qapi-schema/args-array-unknown.json (renamed from tests/qapi-schema/data-array-unknown.json)0
-rw-r--r--tests/qapi-schema/args-array-unknown.out (renamed from tests/qapi-schema/data-member-array-bad.out)0
-rw-r--r--tests/qapi-schema/args-int.err1
-rw-r--r--tests/qapi-schema/args-int.exit (renamed from tests/qapi-schema/data-member-unknown.exit)0
-rw-r--r--tests/qapi-schema/args-int.json (renamed from tests/qapi-schema/data-int.json)0
-rw-r--r--tests/qapi-schema/args-int.out (renamed from tests/qapi-schema/data-member-array.err)0
-rw-r--r--tests/qapi-schema/args-invalid.err1
-rw-r--r--tests/qapi-schema/args-invalid.exit (renamed from tests/qapi-schema/data-unknown.exit)0
-rw-r--r--tests/qapi-schema/args-invalid.json2
-rw-r--r--tests/qapi-schema/args-invalid.out (renamed from tests/qapi-schema/data-member-unknown.out)0
-rw-r--r--tests/qapi-schema/args-member-array-bad.err (renamed from tests/qapi-schema/data-member-array-bad.err)2
-rw-r--r--tests/qapi-schema/args-member-array-bad.exit (renamed from tests/qapi-schema/enum-union-clash.exit)0
-rw-r--r--tests/qapi-schema/args-member-array-bad.json (renamed from tests/qapi-schema/data-member-array-bad.json)0
-rw-r--r--tests/qapi-schema/args-member-array-bad.out (renamed from tests/qapi-schema/data-unknown.out)0
-rw-r--r--tests/qapi-schema/args-member-unknown.err1
-rw-r--r--tests/qapi-schema/args-member-unknown.exit (renamed from tests/qapi-schema/flat-union-base-star.exit)0
-rw-r--r--tests/qapi-schema/args-member-unknown.json (renamed from tests/qapi-schema/data-member-unknown.json)0
-rw-r--r--tests/qapi-schema/args-member-unknown.out (renamed from tests/qapi-schema/enum-empty.err)0
-rw-r--r--tests/qapi-schema/args-name-clash.err (renamed from tests/qapi-schema/enum-union-clash.out)0
-rw-r--r--tests/qapi-schema/args-name-clash.exit (renamed from tests/qapi-schema/data-member-array.exit)0
-rw-r--r--tests/qapi-schema/args-name-clash.json5
-rw-r--r--tests/qapi-schema/args-name-clash.out6
-rw-r--r--tests/qapi-schema/args-union.err1
-rw-r--r--tests/qapi-schema/args-union.exit (renamed from tests/qapi-schema/flat-union-branch-clash.exit)0
-rw-r--r--tests/qapi-schema/args-union.json4
-rw-r--r--tests/qapi-schema/args-union.out (renamed from tests/qapi-schema/flat-union-base-star.out)0
-rw-r--r--tests/qapi-schema/args-unknown.err1
-rw-r--r--tests/qapi-schema/args-unknown.exit (renamed from tests/qapi-schema/nested-struct-returns.exit)0
-rw-r--r--tests/qapi-schema/args-unknown.json (renamed from tests/qapi-schema/data-unknown.json)0
-rw-r--r--tests/qapi-schema/args-unknown.out (renamed from tests/qapi-schema/flat-union-branch-clash.out)0
-rw-r--r--tests/qapi-schema/command-int.json3
-rw-r--r--tests/qapi-schema/comments.out5
-rw-r--r--tests/qapi-schema/data-array-unknown.err1
-rw-r--r--tests/qapi-schema/data-int.err1
-rw-r--r--tests/qapi-schema/data-member-array.json4
-rw-r--r--tests/qapi-schema/data-member-array.out5
-rw-r--r--tests/qapi-schema/data-member-unknown.err1
-rw-r--r--tests/qapi-schema/data-unknown.err1
-rw-r--r--tests/qapi-schema/duplicate-key.err2
-rw-r--r--tests/qapi-schema/duplicate-key.json1
-rw-r--r--tests/qapi-schema/empty.out4
-rw-r--r--tests/qapi-schema/enum-bad-prefix.err1
-rw-r--r--tests/qapi-schema/enum-bad-prefix.exit (renamed from tests/qapi-schema/type-bypass-no-gen.exit)0
-rw-r--r--tests/qapi-schema/enum-bad-prefix.json2
-rw-r--r--tests/qapi-schema/enum-bad-prefix.out (renamed from tests/qapi-schema/flat-union-reverse-define.err)0
-rw-r--r--tests/qapi-schema/enum-empty.json2
-rw-r--r--tests/qapi-schema/enum-empty.out3
-rw-r--r--tests/qapi-schema/enum-union-clash.err1
-rw-r--r--tests/qapi-schema/event-case.out5
-rw-r--r--tests/qapi-schema/flat-union-bad-base.err2
-rw-r--r--tests/qapi-schema/flat-union-base-any.err1
-rw-r--r--tests/qapi-schema/flat-union-base-any.exit1
-rw-r--r--tests/qapi-schema/flat-union-base-any.json (renamed from tests/qapi-schema/flat-union-base-star.json)2
-rw-r--r--tests/qapi-schema/flat-union-base-any.out (renamed from tests/qapi-schema/nested-struct-returns.out)0
-rw-r--r--tests/qapi-schema/flat-union-base-star.err1
-rw-r--r--tests/qapi-schema/flat-union-base-union.err2
-rw-r--r--tests/qapi-schema/flat-union-base-union.json5
-rw-r--r--tests/qapi-schema/flat-union-branch-clash.err1
-rw-r--r--tests/qapi-schema/flat-union-clash-branch.err (renamed from tests/qapi-schema/returns-int.err)0
-rw-r--r--tests/qapi-schema/flat-union-clash-branch.exit (renamed from tests/qapi-schema/enum-empty.exit)0
-rw-r--r--tests/qapi-schema/flat-union-clash-branch.json18
-rw-r--r--tests/qapi-schema/flat-union-clash-branch.out14
-rw-r--r--tests/qapi-schema/flat-union-clash-member.err1
-rw-r--r--tests/qapi-schema/flat-union-clash-member.exit1
-rw-r--r--tests/qapi-schema/flat-union-clash-member.json (renamed from tests/qapi-schema/flat-union-branch-clash.json)3
-rw-r--r--tests/qapi-schema/flat-union-clash-member.out (renamed from tests/qapi-schema/type-bypass-no-gen.out)0
-rw-r--r--tests/qapi-schema/flat-union-clash-type.err1
-rw-r--r--tests/qapi-schema/flat-union-clash-type.exit1
-rw-r--r--tests/qapi-schema/flat-union-clash-type.json14
-rw-r--r--tests/qapi-schema/flat-union-clash-type.out (renamed from tests/qapi-schema/type-bypass.err)0
-rw-r--r--tests/qapi-schema/flat-union-empty.err0
-rw-r--r--tests/qapi-schema/flat-union-empty.exit (renamed from tests/qapi-schema/flat-union-reverse-define.exit)0
-rw-r--r--tests/qapi-schema/flat-union-empty.json4
-rw-r--r--tests/qapi-schema/flat-union-empty.out7
-rw-r--r--tests/qapi-schema/flat-union-inline.err2
-rw-r--r--tests/qapi-schema/flat-union-inline.json4
-rw-r--r--tests/qapi-schema/flat-union-no-base.err2
-rw-r--r--tests/qapi-schema/flat-union-reverse-define.json17
-rw-r--r--tests/qapi-schema/flat-union-reverse-define.out9
-rw-r--r--tests/qapi-schema/ident-with-escape.out8
-rw-r--r--tests/qapi-schema/include-non-file.err2
-rw-r--r--tests/qapi-schema/include-non-file.json2
-rw-r--r--tests/qapi-schema/include-relpath.out5
-rw-r--r--tests/qapi-schema/include-repetition.out5
-rw-r--r--tests/qapi-schema/include-simple.out5
-rw-r--r--tests/qapi-schema/indented-expr.out8
-rw-r--r--tests/qapi-schema/leading-comma-list.err1
-rw-r--r--tests/qapi-schema/leading-comma-list.exit1
-rw-r--r--tests/qapi-schema/leading-comma-list.json2
-rw-r--r--tests/qapi-schema/leading-comma-list.out0
-rw-r--r--tests/qapi-schema/leading-comma-object.err1
-rw-r--r--tests/qapi-schema/leading-comma-object.exit1
-rw-r--r--tests/qapi-schema/leading-comma-object.json2
-rw-r--r--tests/qapi-schema/leading-comma-object.out0
-rw-r--r--tests/qapi-schema/nested-struct-data.json3
-rw-r--r--tests/qapi-schema/nested-struct-returns.err1
-rw-r--r--tests/qapi-schema/nested-struct-returns.json3
-rw-r--r--tests/qapi-schema/qapi-schema-test.json86
-rw-r--r--tests/qapi-schema/qapi-schema-test.out262
-rw-r--r--tests/qapi-schema/reserved-command-q.err1
-rw-r--r--tests/qapi-schema/reserved-command-q.exit1
-rw-r--r--tests/qapi-schema/reserved-command-q.json5
-rw-r--r--tests/qapi-schema/reserved-command-q.out0
-rw-r--r--tests/qapi-schema/reserved-member-has.err1
-rw-r--r--tests/qapi-schema/reserved-member-has.exit1
-rw-r--r--tests/qapi-schema/reserved-member-has.json5
-rw-r--r--tests/qapi-schema/reserved-member-has.out0
-rw-r--r--tests/qapi-schema/reserved-member-q.err1
-rw-r--r--tests/qapi-schema/reserved-member-q.exit1
-rw-r--r--tests/qapi-schema/reserved-member-q.json4
-rw-r--r--tests/qapi-schema/reserved-member-q.out0
-rw-r--r--tests/qapi-schema/reserved-member-u.err1
-rw-r--r--tests/qapi-schema/reserved-member-u.exit1
-rw-r--r--tests/qapi-schema/reserved-member-u.json7
-rw-r--r--tests/qapi-schema/reserved-member-u.out0
-rw-r--r--tests/qapi-schema/reserved-type-kind.err1
-rw-r--r--tests/qapi-schema/reserved-type-kind.exit1
-rw-r--r--tests/qapi-schema/reserved-type-kind.json (renamed from tests/qapi-schema/enum-union-clash.json)2
-rw-r--r--tests/qapi-schema/reserved-type-kind.out0
-rw-r--r--tests/qapi-schema/reserved-type-list.err1
-rw-r--r--tests/qapi-schema/reserved-type-list.exit1
-rw-r--r--tests/qapi-schema/reserved-type-list.json5
-rw-r--r--tests/qapi-schema/reserved-type-list.out0
-rw-r--r--tests/qapi-schema/returns-dict.err1
-rw-r--r--tests/qapi-schema/returns-dict.exit1
-rw-r--r--tests/qapi-schema/returns-dict.json2
-rw-r--r--tests/qapi-schema/returns-dict.out0
-rw-r--r--tests/qapi-schema/returns-int.json3
-rw-r--r--tests/qapi-schema/returns-int.out3
-rw-r--r--tests/qapi-schema/returns-whitelist.err2
-rw-r--r--tests/qapi-schema/struct-base-clash-deep.err2
-rw-r--r--tests/qapi-schema/struct-base-clash-deep.json5
-rw-r--r--tests/qapi-schema/struct-base-clash.err2
-rw-r--r--tests/qapi-schema/struct-base-clash.json3
-rw-r--r--tests/qapi-schema/struct-data-invalid.err1
-rw-r--r--tests/qapi-schema/struct-data-invalid.exit1
-rw-r--r--tests/qapi-schema/struct-data-invalid.json2
-rw-r--r--tests/qapi-schema/struct-data-invalid.out0
-rw-r--r--tests/qapi-schema/struct-member-invalid.err1
-rw-r--r--tests/qapi-schema/struct-member-invalid.exit1
-rw-r--r--tests/qapi-schema/struct-member-invalid.json2
-rw-r--r--tests/qapi-schema/struct-member-invalid.out0
-rw-r--r--tests/qapi-schema/test-qapi.py47
-rw-r--r--tests/qapi-schema/type-bypass-no-gen.err1
-rw-r--r--tests/qapi-schema/type-bypass-no-gen.json2
-rw-r--r--tests/qapi-schema/type-bypass.json2
-rw-r--r--tests/qapi-schema/type-bypass.out3
-rw-r--r--tests/qapi-schema/union-base-no-discriminator.err2
-rw-r--r--tests/qapi-schema/union-clash-branches.err1
-rw-r--r--tests/qapi-schema/union-clash-branches.exit1
-rw-r--r--tests/qapi-schema/union-clash-branches.json5
-rw-r--r--tests/qapi-schema/union-clash-branches.out0
-rw-r--r--tests/qapi-schema/union-clash-data.err0
-rw-r--r--tests/qapi-schema/union-clash-data.exit (renamed from tests/qapi-schema/returns-int.exit)0
-rw-r--r--tests/qapi-schema/union-clash-data.json7
-rw-r--r--tests/qapi-schema/union-clash-data.out6
-rw-r--r--tests/qapi-schema/union-clash-type.err1
-rw-r--r--tests/qapi-schema/union-clash-type.exit1
-rw-r--r--tests/qapi-schema/union-clash-type.json9
-rw-r--r--tests/qapi-schema/union-clash-type.out0
-rw-r--r--tests/qapi-schema/union-empty.err0
-rw-r--r--tests/qapi-schema/union-empty.exit (renamed from tests/qapi-schema/type-bypass.exit)0
-rw-r--r--tests/qapi-schema/union-empty.json2
-rw-r--r--tests/qapi-schema/union-empty.out3
-rw-r--r--tests/qapi-schema/union-invalid-base.err2
-rw-r--r--tests/qemu-iotests/017.out2
-rw-r--r--tests/qemu-iotests/018.out2
-rw-r--r--tests/qemu-iotests/019.out2
-rw-r--r--tests/qemu-iotests/020.out2
-rw-r--r--tests/qemu-iotests/024.out2
-rw-r--r--tests/qemu-iotests/028.out4
-rwxr-xr-xtests/qemu-iotests/0305
-rw-r--r--tests/qemu-iotests/034.out2
-rw-r--r--tests/qemu-iotests/037.out2
-rw-r--r--tests/qemu-iotests/038.out2
-rwxr-xr-xtests/qemu-iotests/03946
-rw-r--r--tests/qemu-iotests/039.out46
-rwxr-xr-xtests/qemu-iotests/04030
-rw-r--r--tests/qemu-iotests/040.out4
-rwxr-xr-xtests/qemu-iotests/04124
-rw-r--r--tests/qemu-iotests/043.out12
-rw-r--r--tests/qemu-iotests/046.out2
-rw-r--r--tests/qemu-iotests/049.out33
-rw-r--r--tests/qemu-iotests/050.out2
-rwxr-xr-xtests/qemu-iotests/0513
-rw-r--r--tests/qemu-iotests/051.out4
-rwxr-xr-xtests/qemu-iotests/05519
-rwxr-xr-xtests/qemu-iotests/05625
-rw-r--r--tests/qemu-iotests/056.out4
-rwxr-xr-xtests/qemu-iotests/05812
-rw-r--r--tests/qemu-iotests/059.out12
-rwxr-xr-xtests/qemu-iotests/0616
-rw-r--r--tests/qemu-iotests/061.out20
-rwxr-xr-xtests/qemu-iotests/06711
-rw-r--r--tests/qemu-iotests/067.out271
-rw-r--r--tests/qemu-iotests/069.out2
-rwxr-xr-xtests/qemu-iotests/07154
-rw-r--r--tests/qemu-iotests/071.out16
-rw-r--r--tests/qemu-iotests/073.out2
-rw-r--r--tests/qemu-iotests/079.out18
-rwxr-xr-xtests/qemu-iotests/08121
-rw-r--r--tests/qemu-iotests/081.out7
-rw-r--r--tests/qemu-iotests/082.out4
-rwxr-xr-xtests/qemu-iotests/085120
-rw-r--r--tests/qemu-iotests/085.out72
-rwxr-xr-xtests/qemu-iotests/0872
-rw-r--r--tests/qemu-iotests/087.out16
-rw-r--r--tests/qemu-iotests/095.out4
-rw-r--r--tests/qemu-iotests/09669
-rw-r--r--tests/qemu-iotests/096.out5
-rw-r--r--tests/qemu-iotests/097.out16
-rw-r--r--tests/qemu-iotests/098.out8
-rw-r--r--tests/qemu-iotests/110.out4
-rw-r--r--tests/qemu-iotests/112.out4
-rw-r--r--tests/qemu-iotests/114.out2
-rw-r--r--tests/qemu-iotests/115.out2
-rwxr-xr-xtests/qemu-iotests/118720
-rw-r--r--tests/qemu-iotests/118.out5
-rwxr-xr-xtests/qemu-iotests/1192
-rwxr-xr-xtests/qemu-iotests/1202
-rw-r--r--tests/qemu-iotests/121.out4
-rw-r--r--tests/qemu-iotests/122.out6
-rw-r--r--tests/qemu-iotests/124182
-rw-r--r--tests/qemu-iotests/124.out4
-rwxr-xr-xtests/qemu-iotests/1289
-rwxr-xr-xtests/qemu-iotests/1308
-rw-r--r--tests/qemu-iotests/130.out8
-rw-r--r--tests/qemu-iotests/136349
-rw-r--r--tests/qemu-iotests/136.out5
-rwxr-xr-xtests/qemu-iotests/137145
-rw-r--r--tests/qemu-iotests/137.out46
-rwxr-xr-xtests/qemu-iotests/13873
-rw-r--r--tests/qemu-iotests/138.out9
-rw-r--r--tests/qemu-iotests/139416
-rw-r--r--tests/qemu-iotests/139.out5
-rwxr-xr-xtests/qemu-iotests/144114
-rw-r--r--tests/qemu-iotests/144.out24
-rwxr-xr-xtests/qemu-iotests/check13
-rw-r--r--tests/qemu-iotests/common10
-rw-r--r--tests/qemu-iotests/common.config64
-rw-r--r--tests/qemu-iotests/common.filter7
-rw-r--r--tests/qemu-iotests/common.qemu20
-rw-r--r--tests/qemu-iotests/common.rc30
-rw-r--r--tests/qemu-iotests/group7
-rw-r--r--tests/qemu-iotests/iotests.py57
-rw-r--r--tests/qom-test.c21
-rw-r--r--tests/rtl8139-test.c2
-rw-r--r--tests/tcg/testthread.c1
-rw-r--r--tests/test-aio.c83
-rw-r--r--tests/test-blockjob-txn.c250
-rw-r--r--tests/test-coroutine.c4
-rw-r--r--tests/test-crypto-cipher.c80
-rw-r--r--tests/test-crypto-tlscredsx509.c731
-rw-r--r--tests/test-crypto-tlssession.c535
-rw-r--r--tests/test-cutils.c1346
-rw-r--r--tests/test-hbitmap.c6
-rw-r--r--tests/test-netfilter.c200
-rw-r--r--tests/test-qga.c877
-rw-r--r--tests/test-qmp-commands.c31
-rw-r--r--tests/test-qmp-event.c10
-rw-r--r--tests/test-qmp-input-strict.c145
-rw-r--r--tests/test-qmp-input-visitor.c428
-rw-r--r--tests/test-qmp-output-visitor.c254
-rw-r--r--tests/test-string-output-visitor.c16
-rw-r--r--tests/test-throttle.c21
-rw-r--r--tests/test-timed-average.c90
-rw-r--r--tests/test-visitor-serialization.c90
-rw-r--r--tests/test-vmstate.c2
-rw-r--r--tests/test-xbzrle.c2
-rw-r--r--tests/vhost-user-bridge.c1398
-rw-r--r--tests/vhost-user-test.c570
-rw-r--r--tests/virtio-net-test.c237
-rw-r--r--tests/virtio-scsi-test.c100
321 files changed, 13737 insertions, 1731 deletions
diff --git a/tests/.gitignore b/tests/.gitignore
index ccc92e476..1e55722b6 100644
--- a/tests/.gitignore
+++ b/tests/.gitignore
@@ -9,9 +9,17 @@ check-qom-proplist
rcutorture
test-aio
test-bitops
+test-blockjob-txn
test-coroutine
test-crypto-cipher
test-crypto-hash
+test-crypto-tlscredsx509
+test-crypto-tlscredsx509-work/
+test-crypto-tlscredsx509-certs/
+test-crypto-tlssession
+test-crypto-tlssession-work/
+test-crypto-tlssession-client/
+test-crypto-tlssession-server/
test-cutils
test-hbitmap
test-int128
@@ -23,11 +31,13 @@ test-qapi-types.[ch]
test-qapi-visit.[ch]
test-qdev-global-props
test-qemu-opts
+test-qga
test-qmp-commands
test-qmp-commands.h
test-qmp-event
test-qmp-input-strict
test-qmp-input-visitor
+test-qmp-introspect.[ch]
test-qmp-marshal.c
test-qmp-output-visitor
test-rcu-list
@@ -36,10 +46,12 @@ test-string-input-visitor
test-string-output-visitor
test-thread-pool
test-throttle
+test-timed-average
test-visitor-serialization
test-vmstate
test-write-threshold
test-x86-cpuid
test-xbzrle
+test-netfilter
*-test
qapi-schema/*.test.*
diff --git a/tests/Makefile b/tests/Makefile
index b453eb44a..a1d03b457 100644
--- a/tests/Makefile
+++ b/tests/Makefile
@@ -1,5 +1,7 @@
export SRC_PATH
+qapi-py = $(SRC_PATH)/scripts/qapi.py $(SRC_PATH)/scripts/ordereddict.py
+
# Get the list of all supported sysemu targets
SYSEMU_TARGET_LIST := $(subst -softmmu.mak,,$(notdir \
$(wildcard $(SRC_PATH)/default-configs/*-softmmu.mak)))
@@ -45,6 +47,8 @@ check-unit-y += tests/test-thread-pool$(EXESUF)
gcov-files-test-thread-pool-y = thread-pool.c
gcov-files-test-hbitmap-y = util/hbitmap.c
check-unit-y += tests/test-hbitmap$(EXESUF)
+gcov-files-test-hbitmap-y = blockjob.c
+check-unit-y += tests/test-blockjob-txn$(EXESUF)
check-unit-y += tests/test-x86-cpuid$(EXESUF)
# all code tested by test-x86-cpuid is inside topology.h
gcov-files-test-x86-cpuid-y =
@@ -76,6 +80,10 @@ check-unit-y += tests/test-write-threshold$(EXESUF)
gcov-files-test-write-threshold-y = block/write-threshold.c
check-unit-$(CONFIG_GNUTLS_HASH) += tests/test-crypto-hash$(EXESUF)
check-unit-y += tests/test-crypto-cipher$(EXESUF)
+check-unit-$(CONFIG_GNUTLS) += tests/test-crypto-tlscredsx509$(EXESUF)
+check-unit-$(CONFIG_GNUTLS) += tests/test-crypto-tlssession$(EXESUF)
+check-unit-$(CONFIG_LINUX) += tests/test-qga$(EXESUF)
+check-unit-y += tests/test-timed-average$(EXESUF)
check-block-$(CONFIG_POSIX) += tests/qemu-iotests-quick.sh
@@ -145,6 +153,8 @@ gcov-files-pci-y += hw/display/virtio-gpu-pci.c
gcov-files-pci-$(CONFIG_VIRTIO_VGA) += hw/display/virtio-vga.c
check-qtest-pci-y += tests/intel-hda-test$(EXESUF)
gcov-files-pci-y += hw/audio/intel-hda.c hw/audio/hda-codec.c
+check-qtest-pci-$(CONFIG_POSIX) += tests/ivshmem-test$(EXESUF)
+gcov-files-pci-y += hw/misc/ivshmem.c
check-qtest-i386-y = tests/endianness-test$(EXESUF)
check-qtest-i386-y += tests/fdc-test$(EXESUF)
@@ -187,7 +197,11 @@ gcov-files-i386-y += hw/usb/hcd-xhci.c
check-qtest-i386-y += tests/pc-cpu-test$(EXESUF)
check-qtest-i386-y += tests/q35-test$(EXESUF)
gcov-files-i386-y += hw/pci-host/q35.c
-check-qtest-i386-$(CONFIG_LINUX) += tests/vhost-user-test$(EXESUF)
+check-qtest-i386-$(CONFIG_VHOST_NET_TEST_i386) += tests/vhost-user-test$(EXESUF)
+ifeq ($(CONFIG_VHOST_NET_TEST_i386),)
+check-qtest-x86_64-$(CONFIG_VHOST_NET_TEST_x86_64) += tests/vhost-user-test$(EXESUF)
+endif
+check-qtest-i386-y += tests/test-netfilter$(EXESUF)
check-qtest-x86_64-y = $(check-qtest-i386-y)
gcov-files-i386-y += i386-softmmu/hw/timer/mc146818rtc.c
gcov-files-x86_64-y = $(subst i386-softmmu/,x86_64-softmmu/,$(gcov-files-i386-y))
@@ -204,6 +218,7 @@ check-qtest-sparc64-y = tests/endianness-test$(EXESUF)
gcov-files-sparc-y += hw/timer/m48t59.c
gcov-files-sparc64-y += hw/timer/m48t59.c
check-qtest-arm-y = tests/tmp105-test$(EXESUF)
+check-qtest-arm-y = tests/ds1338-test$(EXESUF)
gcov-files-arm-y += hw/misc/tmp105.c
check-qtest-arm-y += tests/virtio-blk-test$(EXESUF)
gcov-files-arm-y += arm-softmmu/hw/block/virtio-blk.c
@@ -216,49 +231,133 @@ check-qtest-xtensaeb-y = $(check-qtest-xtensa-y)
check-qtest-generic-y += tests/qom-test$(EXESUF)
-check-qapi-schema-y := $(addprefix tests/qapi-schema/, \
- comments.json empty.json enum-empty.json enum-missing-data.json \
- enum-wrong-data.json enum-int-member.json enum-dict-member.json \
- enum-clash-member.json enum-max-member.json enum-union-clash.json \
- enum-bad-name.json funny-char.json indented-expr.json \
- missing-type.json bad-ident.json ident-with-escape.json \
- escape-outside-string.json unknown-escape.json \
- escape-too-short.json escape-too-big.json unicode-str.json \
- double-type.json bad-base.json bad-type-bool.json bad-type-int.json \
- bad-type-dict.json double-data.json unknown-expr-key.json \
- redefined-type.json redefined-command.json redefined-builtin.json \
- redefined-event.json command-int.json bad-data.json event-max.json \
- type-bypass.json type-bypass-no-gen.json type-bypass-bad-gen.json \
- data-array-empty.json data-array-unknown.json data-int.json \
- data-unknown.json data-member-unknown.json data-member-array.json \
- data-member-array-bad.json returns-array-bad.json returns-int.json \
- returns-unknown.json returns-alternate.json returns-whitelist.json \
- missing-colon.json missing-comma-list.json missing-comma-object.json \
- nested-struct-data.json nested-struct-returns.json non-objects.json \
- qapi-schema-test.json quoted-structural-chars.json \
- trailing-comma-list.json trailing-comma-object.json \
- unclosed-list.json unclosed-object.json unclosed-string.json \
- duplicate-key.json union-invalid-base.json union-bad-branch.json \
- union-optional-branch.json union-unknown.json union-max.json \
- flat-union-optional-discriminator.json flat-union-no-base.json \
- flat-union-invalid-discriminator.json flat-union-inline.json \
- flat-union-invalid-branch-key.json flat-union-reverse-define.json \
- flat-union-string-discriminator.json union-base-no-discriminator.json \
- flat-union-bad-discriminator.json flat-union-bad-base.json \
- flat-union-base-star.json \
- flat-union-array-branch.json flat-union-int-branch.json \
- flat-union-base-union.json flat-union-branch-clash.json \
- alternate-nested.json alternate-unknown.json alternate-clash.json \
- alternate-good.json alternate-base.json alternate-array.json \
- alternate-conflict-string.json alternate-conflict-dict.json \
- include-simple.json include-relpath.json include-format-err.json \
- include-non-file.json include-no-file.json include-before-err.json \
- include-nested-err.json include-self-cycle.json include-cycle.json \
- include-repetition.json event-nest-struct.json event-case.json \
- struct-base-clash.json struct-base-clash-deep.json )
+qapi-schema += alternate-array.json
+qapi-schema += alternate-base.json
+qapi-schema += alternate-clash.json
+qapi-schema += alternate-conflict-dict.json
+qapi-schema += alternate-conflict-string.json
+qapi-schema += alternate-empty.json
+qapi-schema += alternate-nested.json
+qapi-schema += alternate-unknown.json
+qapi-schema += args-alternate.json
+qapi-schema += args-any.json
+qapi-schema += args-array-empty.json
+qapi-schema += args-array-unknown.json
+qapi-schema += args-int.json
+qapi-schema += args-invalid.json
+qapi-schema += args-member-array-bad.json
+qapi-schema += args-member-unknown.json
+qapi-schema += args-name-clash.json
+qapi-schema += args-union.json
+qapi-schema += args-unknown.json
+qapi-schema += bad-base.json
+qapi-schema += bad-data.json
+qapi-schema += bad-ident.json
+qapi-schema += bad-type-bool.json
+qapi-schema += bad-type-dict.json
+qapi-schema += bad-type-int.json
+qapi-schema += command-int.json
+qapi-schema += comments.json
+qapi-schema += double-data.json
+qapi-schema += double-type.json
+qapi-schema += duplicate-key.json
+qapi-schema += empty.json
+qapi-schema += enum-bad-name.json
+qapi-schema += enum-bad-prefix.json
+qapi-schema += enum-clash-member.json
+qapi-schema += enum-dict-member.json
+qapi-schema += enum-int-member.json
+qapi-schema += enum-max-member.json
+qapi-schema += enum-missing-data.json
+qapi-schema += enum-wrong-data.json
+qapi-schema += escape-outside-string.json
+qapi-schema += escape-too-big.json
+qapi-schema += escape-too-short.json
+qapi-schema += event-case.json
+qapi-schema += event-max.json
+qapi-schema += event-nest-struct.json
+qapi-schema += flat-union-array-branch.json
+qapi-schema += flat-union-bad-base.json
+qapi-schema += flat-union-bad-discriminator.json
+qapi-schema += flat-union-base-any.json
+qapi-schema += flat-union-base-union.json
+qapi-schema += flat-union-clash-branch.json
+qapi-schema += flat-union-clash-member.json
+qapi-schema += flat-union-clash-type.json
+qapi-schema += flat-union-empty.json
+qapi-schema += flat-union-inline.json
+qapi-schema += flat-union-int-branch.json
+qapi-schema += flat-union-invalid-branch-key.json
+qapi-schema += flat-union-invalid-discriminator.json
+qapi-schema += flat-union-no-base.json
+qapi-schema += flat-union-optional-discriminator.json
+qapi-schema += flat-union-string-discriminator.json
+qapi-schema += funny-char.json
+qapi-schema += ident-with-escape.json
+qapi-schema += include-before-err.json
+qapi-schema += include-cycle.json
+qapi-schema += include-format-err.json
+qapi-schema += include-nested-err.json
+qapi-schema += include-no-file.json
+qapi-schema += include-non-file.json
+qapi-schema += include-relpath.json
+qapi-schema += include-repetition.json
+qapi-schema += include-self-cycle.json
+qapi-schema += include-simple.json
+qapi-schema += indented-expr.json
+qapi-schema += leading-comma-list.json
+qapi-schema += leading-comma-object.json
+qapi-schema += missing-colon.json
+qapi-schema += missing-comma-list.json
+qapi-schema += missing-comma-object.json
+qapi-schema += missing-type.json
+qapi-schema += nested-struct-data.json
+qapi-schema += non-objects.json
+qapi-schema += qapi-schema-test.json
+qapi-schema += quoted-structural-chars.json
+qapi-schema += redefined-builtin.json
+qapi-schema += redefined-command.json
+qapi-schema += redefined-event.json
+qapi-schema += redefined-type.json
+qapi-schema += reserved-command-q.json
+qapi-schema += reserved-member-has.json
+qapi-schema += reserved-member-q.json
+qapi-schema += reserved-member-u.json
+qapi-schema += reserved-type-kind.json
+qapi-schema += reserved-type-list.json
+qapi-schema += returns-alternate.json
+qapi-schema += returns-array-bad.json
+qapi-schema += returns-dict.json
+qapi-schema += returns-unknown.json
+qapi-schema += returns-whitelist.json
+qapi-schema += struct-base-clash-deep.json
+qapi-schema += struct-base-clash.json
+qapi-schema += struct-data-invalid.json
+qapi-schema += struct-member-invalid.json
+qapi-schema += trailing-comma-list.json
+qapi-schema += trailing-comma-object.json
+qapi-schema += type-bypass-bad-gen.json
+qapi-schema += unclosed-list.json
+qapi-schema += unclosed-object.json
+qapi-schema += unclosed-string.json
+qapi-schema += unicode-str.json
+qapi-schema += union-bad-branch.json
+qapi-schema += union-base-no-discriminator.json
+qapi-schema += union-clash-branches.json
+qapi-schema += union-clash-data.json
+qapi-schema += union-clash-type.json
+qapi-schema += union-empty.json
+qapi-schema += union-invalid-base.json
+qapi-schema += union-max.json
+qapi-schema += union-optional-branch.json
+qapi-schema += union-unknown.json
+qapi-schema += unknown-escape.json
+qapi-schema += unknown-expr-key.json
+check-qapi-schema-y := $(addprefix tests/qapi-schema/, $(qapi-schema))
GENERATED_HEADERS += tests/test-qapi-types.h tests/test-qapi-visit.h \
- tests/test-qmp-commands.h tests/test-qapi-event.h
+ tests/test-qmp-commands.h tests/test-qapi-event.h \
+ tests/test-qmp-introspect.h
test-obj-y = tests/check-qint.o tests/check-qstring.o tests/check-qdict.o \
tests/check-qlist.o tests/check-qfloat.o tests/check-qjson.o \
@@ -270,47 +369,53 @@ test-obj-y = tests/check-qint.o tests/check-qstring.o tests/check-qdict.o \
tests/test-opts-visitor.o tests/test-qmp-event.o \
tests/rcutorture.o tests/test-rcu-list.o
-test-qapi-obj-y = tests/test-qapi-visit.o tests/test-qapi-types.o \
- tests/test-qapi-event.o
-
$(test-obj-y): QEMU_INCLUDES += -Itests
QEMU_CFLAGS += -I$(SRC_PATH)/tests
-qom-core-obj = qom/object.o qom/qom-qobject.o qom/container.o qom/object_interfaces.o
-
-tests/check-qint$(EXESUF): tests/check-qint.o libqemuutil.a
-tests/check-qstring$(EXESUF): tests/check-qstring.o libqemuutil.a
-tests/check-qdict$(EXESUF): tests/check-qdict.o libqemuutil.a
-tests/check-qlist$(EXESUF): tests/check-qlist.o libqemuutil.a
-tests/check-qfloat$(EXESUF): tests/check-qfloat.o libqemuutil.a
-tests/check-qjson$(EXESUF): tests/check-qjson.o libqemuutil.a libqemustub.a
-tests/check-qom-interface$(EXESUF): tests/check-qom-interface.o $(qom-core-obj) libqemuutil.a libqemustub.a
-tests/check-qom-proplist$(EXESUF): tests/check-qom-proplist.o $(qom-core-obj) libqemuutil.a libqemustub.a
-tests/test-coroutine$(EXESUF): tests/test-coroutine.o $(block-obj-y) libqemuutil.a libqemustub.a
-tests/test-aio$(EXESUF): tests/test-aio.o $(block-obj-y) libqemuutil.a libqemustub.a
-tests/test-rfifolock$(EXESUF): tests/test-rfifolock.o libqemuutil.a libqemustub.a
-tests/test-throttle$(EXESUF): tests/test-throttle.o $(block-obj-y) libqemuutil.a libqemustub.a
-tests/test-thread-pool$(EXESUF): tests/test-thread-pool.o $(block-obj-y) libqemuutil.a libqemustub.a
-tests/test-iov$(EXESUF): tests/test-iov.o libqemuutil.a
-tests/test-hbitmap$(EXESUF): tests/test-hbitmap.o libqemuutil.a libqemustub.a
+
+
+# Deps that are common to various different sets of tests below
+test-util-obj-y = libqemuutil.a libqemustub.a
+test-qom-obj-y = $(qom-obj-y) $(test-util-obj-y)
+test-qapi-obj-y = tests/test-qapi-visit.o tests/test-qapi-types.o \
+ tests/test-qapi-event.o tests/test-qmp-introspect.o \
+ $(test-qom-obj-y)
+test-crypto-obj-y = $(crypto-obj-y) $(test-qom-obj-y)
+test-block-obj-y = $(block-obj-y) $(test-crypto-obj-y)
+
+tests/check-qint$(EXESUF): tests/check-qint.o $(test-util-obj-y)
+tests/check-qstring$(EXESUF): tests/check-qstring.o $(test-util-obj-y)
+tests/check-qdict$(EXESUF): tests/check-qdict.o $(test-util-obj-y)
+tests/check-qlist$(EXESUF): tests/check-qlist.o $(test-util-obj-y)
+tests/check-qfloat$(EXESUF): tests/check-qfloat.o $(test-util-obj-y)
+tests/check-qjson$(EXESUF): tests/check-qjson.o $(test-util-obj-y)
+tests/check-qom-interface$(EXESUF): tests/check-qom-interface.o $(test-qom-obj-y)
+tests/check-qom-proplist$(EXESUF): tests/check-qom-proplist.o $(test-qom-obj-y)
+tests/test-coroutine$(EXESUF): tests/test-coroutine.o $(test-block-obj-y)
+tests/test-aio$(EXESUF): tests/test-aio.o $(test-block-obj-y)
+tests/test-rfifolock$(EXESUF): tests/test-rfifolock.o $(test-util-obj-y)
+tests/test-throttle$(EXESUF): tests/test-throttle.o $(test-block-obj-y)
+tests/test-blockjob-txn$(EXESUF): tests/test-blockjob-txn.o $(test-block-obj-y) $(test-util-obj-y)
+tests/test-thread-pool$(EXESUF): tests/test-thread-pool.o $(test-block-obj-y)
+tests/test-iov$(EXESUF): tests/test-iov.o $(test-util-obj-y)
+tests/test-hbitmap$(EXESUF): tests/test-hbitmap.o $(test-util-obj-y)
tests/test-x86-cpuid$(EXESUF): tests/test-x86-cpuid.o
-tests/test-xbzrle$(EXESUF): tests/test-xbzrle.o migration/xbzrle.o page_cache.o libqemuutil.a
+tests/test-xbzrle$(EXESUF): tests/test-xbzrle.o migration/xbzrle.o page_cache.o $(test-util-obj-y)
tests/test-cutils$(EXESUF): tests/test-cutils.o util/cutils.o
tests/test-int128$(EXESUF): tests/test-int128.o
-tests/rcutorture$(EXESUF): tests/rcutorture.o libqemuutil.a libqemustub.a
-tests/test-rcu-list$(EXESUF): tests/test-rcu-list.o libqemuutil.a libqemustub.a
+tests/rcutorture$(EXESUF): tests/rcutorture.o $(test-util-obj-y)
+tests/test-rcu-list$(EXESUF): tests/test-rcu-list.o $(test-util-obj-y)
tests/test-qdev-global-props$(EXESUF): tests/test-qdev-global-props.o \
hw/core/qdev.o hw/core/qdev-properties.o hw/core/hotplug.o\
hw/core/irq.o \
hw/core/fw-path-provider.o \
- $(qom-core-obj) \
- $(test-qapi-obj-y) \
- libqemuutil.a libqemustub.a
+ $(test-qapi-obj-y)
tests/test-vmstate$(EXESUF): tests/test-vmstate.o \
migration/vmstate.o migration/qemu-file.o migration/qemu-file-buf.o \
migration/qemu-file-unix.o qjson.o \
- $(qom-core-obj) \
- libqemuutil.a libqemustub.a
+ $(test-qom-obj-y)
+tests/test-timed-average$(EXESUF): tests/test-timed-average.o qemu-timer.o \
+ $(test-util-obj-y)
tests/test-qapi-types.c tests/test-qapi-types.h :\
$(SRC_PATH)/tests/qapi-schema/qapi-schema-test.json $(SRC_PATH)/scripts/qapi-types.py $(qapi-py)
@@ -332,21 +437,38 @@ $(SRC_PATH)/tests/qapi-schema/qapi-schema-test.json $(SRC_PATH)/scripts/qapi-eve
$(call quiet-command,$(PYTHON) $(SRC_PATH)/scripts/qapi-event.py \
$(gen-out-type) -o tests -p "test-" $<, \
" GEN $@")
+tests/test-qmp-introspect.c tests/test-qmp-introspect.h :\
+$(SRC_PATH)/tests/qapi-schema/qapi-schema-test.json $(SRC_PATH)/scripts/qapi-introspect.py $(qapi-py)
+ $(call quiet-command,$(PYTHON) $(SRC_PATH)/scripts/qapi-introspect.py \
+ $(gen-out-type) -o tests -p "test-" $<, \
+ " GEN $@")
-tests/test-string-output-visitor$(EXESUF): tests/test-string-output-visitor.o $(test-qapi-obj-y) libqemuutil.a libqemustub.a
-tests/test-string-input-visitor$(EXESUF): tests/test-string-input-visitor.o $(test-qapi-obj-y) libqemuutil.a libqemustub.a
-tests/test-qmp-event$(EXESUF): tests/test-qmp-event.o $(test-qapi-obj-y) libqemuutil.a libqemustub.a
-tests/test-qmp-output-visitor$(EXESUF): tests/test-qmp-output-visitor.o $(test-qapi-obj-y) libqemuutil.a libqemustub.a
-tests/test-qmp-input-visitor$(EXESUF): tests/test-qmp-input-visitor.o $(test-qapi-obj-y) libqemuutil.a libqemustub.a
-tests/test-qmp-input-strict$(EXESUF): tests/test-qmp-input-strict.o $(test-qapi-obj-y) libqemuutil.a libqemustub.a
-tests/test-qmp-commands$(EXESUF): tests/test-qmp-commands.o tests/test-qmp-marshal.o $(test-qapi-obj-y) libqemuutil.a libqemustub.a
-tests/test-visitor-serialization$(EXESUF): tests/test-visitor-serialization.o $(test-qapi-obj-y) libqemuutil.a libqemustub.a
-tests/test-opts-visitor$(EXESUF): tests/test-opts-visitor.o $(test-qapi-obj-y) libqemuutil.a libqemustub.a
-
-tests/test-mul64$(EXESUF): tests/test-mul64.o libqemuutil.a
-tests/test-bitops$(EXESUF): tests/test-bitops.o libqemuutil.a
-tests/test-crypto-hash$(EXESUF): tests/test-crypto-hash.o libqemuutil.a libqemustub.a
-tests/test-crypto-cipher$(EXESUF): tests/test-crypto-cipher.o libqemuutil.a libqemustub.a
+tests/test-string-output-visitor$(EXESUF): tests/test-string-output-visitor.o $(test-qapi-obj-y)
+tests/test-string-input-visitor$(EXESUF): tests/test-string-input-visitor.o $(test-qapi-obj-y)
+tests/test-qmp-event$(EXESUF): tests/test-qmp-event.o $(test-qapi-obj-y)
+tests/test-qmp-output-visitor$(EXESUF): tests/test-qmp-output-visitor.o $(test-qapi-obj-y)
+tests/test-qmp-input-visitor$(EXESUF): tests/test-qmp-input-visitor.o $(test-qapi-obj-y)
+tests/test-qmp-input-strict$(EXESUF): tests/test-qmp-input-strict.o $(test-qapi-obj-y)
+tests/test-qmp-commands$(EXESUF): tests/test-qmp-commands.o tests/test-qmp-marshal.o $(test-qapi-obj-y)
+tests/test-visitor-serialization$(EXESUF): tests/test-visitor-serialization.o $(test-qapi-obj-y)
+tests/test-opts-visitor$(EXESUF): tests/test-opts-visitor.o $(test-qapi-obj-y)
+
+tests/test-mul64$(EXESUF): tests/test-mul64.o $(test-util-obj-y)
+tests/test-bitops$(EXESUF): tests/test-bitops.o $(test-util-obj-y)
+tests/test-crypto-hash$(EXESUF): tests/test-crypto-hash.o $(test-crypto-obj-y)
+tests/test-crypto-cipher$(EXESUF): tests/test-crypto-cipher.o $(test-crypto-obj-y)
+
+tests/crypto-tls-x509-helpers.o-cflags := $(TASN1_CFLAGS)
+tests/crypto-tls-x509-helpers.o-libs := $(TASN1_LIBS)
+tests/pkix_asn1_tab.o-cflags := $(TASN1_CFLAGS)
+
+tests/test-crypto-tlscredsx509.o-cflags := $(TASN1_CFLAGS)
+tests/test-crypto-tlscredsx509$(EXESUF): tests/test-crypto-tlscredsx509.o \
+ tests/crypto-tls-x509-helpers.o tests/pkix_asn1_tab.o $(test-crypto-obj-y)
+
+tests/test-crypto-tlssession.o-cflags := $(TASN1_CFLAGS)
+tests/test-crypto-tlssession$(EXESUF): tests/test-crypto-tlssession.o \
+ tests/crypto-tls-x509-helpers.o tests/pkix_asn1_tab.o $(test-crypto-obj-y)
libqos-obj-y = tests/libqos/pci.o tests/libqos/fw_cfg.o tests/libqos/malloc.o
libqos-obj-y += tests/libqos/i2c.o tests/libqos/libqos.o
@@ -354,6 +476,7 @@ libqos-pc-obj-y = $(libqos-obj-y) tests/libqos/pci-pc.o
libqos-pc-obj-y += tests/libqos/malloc-pc.o tests/libqos/libqos-pc.o
libqos-pc-obj-y += tests/libqos/ahci.o
libqos-omap-obj-y = $(libqos-obj-y) tests/libqos/i2c-omap.o
+libqos-imx-obj-y = $(libqos-obj-y) tests/libqos/i2c-imx.o
libqos-usb-obj-y = $(libqos-pc-obj-y) tests/libqos/usb.o
libqos-virtio-obj-y = $(libqos-pc-obj-y) tests/libqos/virtio.o tests/libqos/virtio-pci.o tests/libqos/virtio-mmio.o tests/libqos/malloc-generic.o
@@ -369,6 +492,7 @@ tests/hd-geo-test$(EXESUF): tests/hd-geo-test.o
tests/boot-order-test$(EXESUF): tests/boot-order-test.o $(libqos-obj-y)
tests/bios-tables-test$(EXESUF): tests/bios-tables-test.o $(libqos-obj-y)
tests/tmp105-test$(EXESUF): tests/tmp105-test.o $(libqos-omap-obj-y)
+tests/ds1338-test$(EXESUF): tests/ds1338-test.o $(libqos-imx-obj-y)
tests/i440fx-test$(EXESUF): tests/i440fx-test.o $(libqos-pc-obj-y)
tests/q35-test$(EXESUF): tests/q35-test.o $(libqos-pc-obj-y)
tests/fw_cfg-test$(EXESUF): tests/fw_cfg-test.o $(libqos-pc-obj-y)
@@ -382,7 +506,7 @@ tests/wdt_ib700-test$(EXESUF): tests/wdt_ib700-test.o
tests/tco-test$(EXESUF): tests/tco-test.o $(libqos-pc-obj-y)
tests/virtio-balloon-test$(EXESUF): tests/virtio-balloon-test.o
tests/virtio-blk-test$(EXESUF): tests/virtio-blk-test.o $(libqos-virtio-obj-y)
-tests/virtio-net-test$(EXESUF): tests/virtio-net-test.o $(libqos-pc-obj-y)
+tests/virtio-net-test$(EXESUF): tests/virtio-net-test.o $(libqos-pc-obj-y) $(libqos-virtio-obj-y)
tests/virtio-rng-test$(EXESUF): tests/virtio-rng-test.o $(libqos-pc-obj-y)
tests/virtio-scsi-test$(EXESUF): tests/virtio-scsi-test.o $(libqos-virtio-obj-y)
tests/virtio-9p-test$(EXESUF): tests/virtio-9p-test.o
@@ -408,8 +532,11 @@ tests/usb-hcd-xhci-test$(EXESUF): tests/usb-hcd-xhci-test.o $(libqos-usb-obj-y)
tests/pc-cpu-test$(EXESUF): tests/pc-cpu-test.o
tests/vhost-user-test$(EXESUF): tests/vhost-user-test.o qemu-char.o qemu-timer.o $(qtest-obj-y)
tests/qemu-iotests/socket_scm_helper$(EXESUF): tests/qemu-iotests/socket_scm_helper.o
-tests/test-qemu-opts$(EXESUF): tests/test-qemu-opts.o libqemuutil.a libqemustub.a
-tests/test-write-threshold$(EXESUF): tests/test-write-threshold.o $(block-obj-y) libqemuutil.a libqemustub.a
+tests/test-qemu-opts$(EXESUF): tests/test-qemu-opts.o $(test-util-obj-y)
+tests/test-write-threshold$(EXESUF): tests/test-write-threshold.o $(test-block-obj-y)
+tests/test-netfilter$(EXESUF): tests/test-netfilter.o $(qtest-obj-y)
+tests/ivshmem-test$(EXESUF): tests/ivshmem-test.o contrib/ivshmem-server/ivshmem-server.o $(libqos-pc-obj-y)
+tests/vhost-user-bridge$(EXESUF): tests/vhost-user-bridge.o
ifeq ($(CONFIG_POSIX),y)
LIBS += -lutil
@@ -426,9 +553,11 @@ else
QTEST_TARGETS =
endif
-qtest-obj-y = tests/libqtest.o libqemuutil.a libqemustub.a
+qtest-obj-y = tests/libqtest.o $(test-util-obj-y)
$(check-qtest-y): $(qtest-obj-y)
+tests/test-qga: tests/test-qga.o $(qtest-obj-y)
+
.PHONY: check-help
check-help:
@echo "Regression testing targets:"
@@ -483,7 +612,7 @@ $(patsubst %, check-%, $(check-unit-y)): check-%: %
$(patsubst %, check-report-qtest-%.xml, $(QTEST_TARGETS)): check-report-qtest-%.xml: $(check-qtest-y)
$(call quiet-command,QTEST_QEMU_BINARY=$*-softmmu/qemu-system-$* \
QTEST_QEMU_IMG=qemu-img$(EXESUF) \
- gtester -q $(GTESTER_OPTIONS) -o $@ -m=$(SPEED) $(check-qtest-$*-y),"GTESTER $@")
+ gtester -q $(GTESTER_OPTIONS) -o $@ -m=$(SPEED) $(check-qtest-$*-y) $(check-qtest-generic-y),"GTESTER $@")
check-report-unit.xml: $(check-unit-y)
$(call quiet-command,gtester -q $(GTESTER_OPTIONS) -o $@ -m=$(SPEED) $^, "GTESTER $@")
@@ -531,7 +660,7 @@ check: check-qapi-schema check-unit check-qtest
check-clean:
$(MAKE) -C tests/tcg clean
rm -rf $(check-unit-y) tests/*.o $(QEMU_IOTESTS_HELPERS-y)
- rm -rf $(sort $(foreach target,$(SYSEMU_TARGET_LIST), $(check-qtest-$(target)-y)))
+ rm -rf $(sort $(foreach target,$(SYSEMU_TARGET_LIST), $(check-qtest-$(target)-y)) $(check-qtest-generic-y))
clean: check-clean
diff --git a/tests/ahci-test.c b/tests/ahci-test.c
index 87d769186..088850642 100644
--- a/tests/ahci-test.c
+++ b/tests/ahci-test.c
@@ -39,15 +39,17 @@
#include "hw/pci/pci_ids.h"
#include "hw/pci/pci_regs.h"
-/* Test-specific defines -- in MiB */
-#define TEST_IMAGE_SIZE_MB (200 * 1024)
-#define TEST_IMAGE_SECTORS ((TEST_IMAGE_SIZE_MB / AHCI_SECTOR_SIZE) \
- * 1024 * 1024)
+/* Test images sizes in MB */
+#define TEST_IMAGE_SIZE_MB_LARGE (200 * 1024)
+#define TEST_IMAGE_SIZE_MB_SMALL 64
/*** Globals ***/
static char tmp_path[] = "/tmp/qtest.XXXXXX";
static char debug_path[] = "/tmp/qtest-blkdebug.XXXXXX";
+static char mig_socket[] = "/tmp/qtest-migration.XXXXXX";
static bool ahci_pedantic;
+static const char *imgfmt;
+static unsigned test_image_size_mb;
/*** Function Declarations ***/
static void ahci_test_port_spec(AHCIQState *ahci, uint8_t port);
@@ -60,6 +62,11 @@ static void ahci_test_pmcap(AHCIQState *ahci, uint8_t offset);
/*** Utilities ***/
+static uint64_t mb_to_sectors(uint64_t image_size_mb)
+{
+ return (image_size_mb * 1024 * 1024) / AHCI_SECTOR_SIZE;
+}
+
static void string_bswap16(uint16_t *s, size_t bytes)
{
g_assert_cmphex((bytes & 1), ==, 0);
@@ -71,32 +78,6 @@ static void string_bswap16(uint16_t *s, size_t bytes)
}
}
-static void generate_pattern(void *buffer, size_t len, size_t cycle_len)
-{
- int i, j;
- unsigned char *tx = (unsigned char *)buffer;
- unsigned char p;
- size_t *sx;
-
- /* Write an indicative pattern that varies and is unique per-cycle */
- p = rand() % 256;
- for (i = j = 0; i < len; i++, j++) {
- tx[i] = p;
- if (j % cycle_len == 0) {
- p = rand() % 256;
- }
- }
-
- /* force uniqueness by writing an id per-cycle */
- for (i = 0; i < len / cycle_len; i++) {
- j = i * cycle_len;
- if (j + sizeof(*sx) <= len) {
- sx = (size_t *)&tx[j];
- *sx = i;
- }
- }
-}
-
/**
* Verify that the transfer did not corrupt our state at all.
*/
@@ -140,8 +121,11 @@ static void ahci_migrate(AHCIQState *from, AHCIQState *to, const char *uri)
{
QOSState *tmp = to->parent;
QPCIDevice *dev = to->dev;
+ char *uri_local = NULL;
+
if (uri == NULL) {
- uri = "tcp:127.0.0.1:1234";
+ uri_local = g_strdup_printf("%s%s", "unix:", mig_socket);
+ uri = uri_local;
}
/* context will be 'to' after completion. */
@@ -161,6 +145,7 @@ static void ahci_migrate(AHCIQState *from, AHCIQState *to, const char *uri)
from->dev = dev;
verify_state(to);
+ g_free(uri_local);
}
/*** Test Setup & Teardown ***/
@@ -196,11 +181,11 @@ static AHCIQState *ahci_boot(const char *cli, ...)
va_end(ap);
} else {
cli = "-drive if=none,id=drive0,file=%s,cache=writeback,serial=%s"
- ",format=qcow2"
+ ",format=%s"
" -M q35 "
"-device ide-hd,drive=drive0 "
"-global ide-hd.ver=%s";
- s = ahci_boot(cli, tmp_path, "testdisk", "version");
+ s = ahci_boot(cli, tmp_path, "testdisk", imgfmt, "version");
}
return s;
@@ -926,7 +911,7 @@ static void ahci_test_max(AHCIQState *ahci)
uint64_t nsect;
uint8_t port;
uint8_t cmd;
- uint64_t config_sect = TEST_IMAGE_SECTORS - 1;
+ uint64_t config_sect = mb_to_sectors(test_image_size_mb) - 1;
if (config_sect > 0xFFFFFF) {
cmd = CMD_READ_MAX_EXT;
@@ -1099,12 +1084,12 @@ static void test_flush_retry(void)
prepare_blkdebug_script(debug_path, "flush_to_disk");
ahci = ahci_boot_and_enable("-drive file=blkdebug:%s:%s,if=none,id=drive0,"
- "format=qcow2,cache=writeback,"
+ "format=%s,cache=writeback,"
"rerror=stop,werror=stop "
"-M q35 "
"-device ide-hd,drive=drive0 ",
debug_path,
- tmp_path);
+ tmp_path, imgfmt);
/* Issue Flush Command and wait for error */
port = ahci_port_select(ahci);
@@ -1131,18 +1116,19 @@ static void test_flush_retry(void)
static void test_migrate_sanity(void)
{
AHCIQState *src, *dst;
- const char *uri = "tcp:127.0.0.1:1234";
+ char *uri = g_strdup_printf("unix:%s", mig_socket);
src = ahci_boot("-m 1024 -M q35 "
- "-hda %s ", tmp_path);
+ "-drive if=ide,file=%s,format=%s ", tmp_path, imgfmt);
dst = ahci_boot("-m 1024 -M q35 "
- "-hda %s "
- "-incoming %s", tmp_path, uri);
+ "-drive if=ide,file=%s,format=%s "
+ "-incoming %s", tmp_path, imgfmt, uri);
ahci_migrate(src, dst, uri);
ahci_shutdown(src);
ahci_shutdown(dst);
+ g_free(uri);
}
/**
@@ -1155,14 +1141,14 @@ static void ahci_migrate_simple(uint8_t cmd_read, uint8_t cmd_write)
size_t bufsize = 4096;
unsigned char *tx = g_malloc(bufsize);
unsigned char *rx = g_malloc0(bufsize);
- unsigned i;
- const char *uri = "tcp:127.0.0.1:1234";
+ char *uri = g_strdup_printf("unix:%s", mig_socket);
src = ahci_boot_and_enable("-m 1024 -M q35 "
- "-hda %s ", tmp_path);
+ "-drive if=ide,format=%s,file=%s ",
+ imgfmt, tmp_path);
dst = ahci_boot("-m 1024 -M q35 "
- "-hda %s "
- "-incoming %s", tmp_path, uri);
+ "-drive if=ide,format=%s,file=%s "
+ "-incoming %s", imgfmt, tmp_path, uri);
set_context(src->parent);
@@ -1171,9 +1157,7 @@ static void ahci_migrate_simple(uint8_t cmd_read, uint8_t cmd_write)
ahci_port_clear(src, px);
/* create pattern */
- for (i = 0; i < bufsize; i++) {
- tx[i] = (bufsize - i);
- }
+ generate_pattern(tx, bufsize, AHCI_SECTOR_SIZE);
/* Write, migrate, then read. */
ahci_io(src, px, cmd_write, tx, bufsize, 0);
@@ -1187,6 +1171,7 @@ static void ahci_migrate_simple(uint8_t cmd_read, uint8_t cmd_write)
ahci_shutdown(dst);
g_free(rx);
g_free(tx);
+ g_free(uri);
}
static void test_migrate_dma(void)
@@ -1213,29 +1198,25 @@ static void ahci_halted_io_test(uint8_t cmd_read, uint8_t cmd_write)
size_t bufsize = 4096;
unsigned char *tx = g_malloc(bufsize);
unsigned char *rx = g_malloc0(bufsize);
- unsigned i;
uint64_t ptr;
AHCICommand *cmd;
prepare_blkdebug_script(debug_path, "write_aio");
ahci = ahci_boot_and_enable("-drive file=blkdebug:%s:%s,if=none,id=drive0,"
- "format=qcow2,cache=writeback,"
+ "format=%s,cache=writeback,"
"rerror=stop,werror=stop "
"-M q35 "
"-device ide-hd,drive=drive0 ",
debug_path,
- tmp_path);
+ tmp_path, imgfmt);
/* Initialize and prepare */
port = ahci_port_select(ahci);
ahci_port_clear(ahci, port);
- for (i = 0; i < bufsize; i++) {
- tx[i] = (bufsize - i);
- }
-
/* create DMA source buffer and write pattern */
+ generate_pattern(tx, bufsize, AHCI_SECTOR_SIZE);
ptr = ahci_alloc(ahci, bufsize);
g_assert(ptr);
memwrite(ptr, tx, bufsize);
@@ -1282,38 +1263,34 @@ static void ahci_migrate_halted_io(uint8_t cmd_read, uint8_t cmd_write)
size_t bufsize = 4096;
unsigned char *tx = g_malloc(bufsize);
unsigned char *rx = g_malloc0(bufsize);
- unsigned i;
uint64_t ptr;
AHCICommand *cmd;
- const char *uri = "tcp:127.0.0.1:1234";
+ char *uri = g_strdup_printf("unix:%s", mig_socket);
prepare_blkdebug_script(debug_path, "write_aio");
src = ahci_boot_and_enable("-drive file=blkdebug:%s:%s,if=none,id=drive0,"
- "format=qcow2,cache=writeback,"
+ "format=%s,cache=writeback,"
"rerror=stop,werror=stop "
"-M q35 "
"-device ide-hd,drive=drive0 ",
debug_path,
- tmp_path);
+ tmp_path, imgfmt);
dst = ahci_boot("-drive file=%s,if=none,id=drive0,"
- "format=qcow2,cache=writeback,"
+ "format=%s,cache=writeback,"
"rerror=stop,werror=stop "
"-M q35 "
"-device ide-hd,drive=drive0 "
"-incoming %s",
- tmp_path, uri);
+ tmp_path, imgfmt, uri);
set_context(src->parent);
/* Initialize and prepare */
port = ahci_port_select(src);
ahci_port_clear(src, port);
-
- for (i = 0; i < bufsize; i++) {
- tx[i] = (bufsize - i);
- }
+ generate_pattern(tx, bufsize, AHCI_SECTOR_SIZE);
/* create DMA source buffer and write pattern */
ptr = ahci_alloc(src, bufsize);
@@ -1338,6 +1315,7 @@ static void ahci_migrate_halted_io(uint8_t cmd_read, uint8_t cmd_write)
ahci_shutdown(dst);
g_free(rx);
g_free(tx);
+ g_free(uri);
}
static void test_migrate_halted_dma(void)
@@ -1359,20 +1337,22 @@ static void test_flush_migrate(void)
AHCICommand *cmd;
uint8_t px;
const char *s;
- const char *uri = "tcp:127.0.0.1:1234";
+ char *uri = g_strdup_printf("unix:%s", mig_socket);
prepare_blkdebug_script(debug_path, "flush_to_disk");
src = ahci_boot_and_enable("-drive file=blkdebug:%s:%s,if=none,id=drive0,"
- "cache=writeback,rerror=stop,werror=stop "
+ "cache=writeback,rerror=stop,werror=stop,"
+ "format=%s "
"-M q35 "
"-device ide-hd,drive=drive0 ",
- debug_path, tmp_path);
+ debug_path, tmp_path, imgfmt);
dst = ahci_boot("-drive file=%s,if=none,id=drive0,"
- "cache=writeback,rerror=stop,werror=stop "
+ "cache=writeback,rerror=stop,werror=stop,"
+ "format=%s "
"-M q35 "
"-device ide-hd,drive=drive0 "
- "-incoming %s", tmp_path, uri);
+ "-incoming %s", tmp_path, imgfmt, uri);
set_context(src->parent);
@@ -1397,6 +1377,7 @@ static void test_flush_migrate(void)
ahci_command_free(cmd);
ahci_shutdown(src);
ahci_shutdown(dst);
+ g_free(uri);
}
static void test_max(void)
@@ -1513,7 +1494,7 @@ static uint64_t offset_sector(enum OffsetType ofst,
return 1;
case OFFSET_HIGH:
ceil = (addr_type == ADDR_MODE_LBA28) ? 0xfffffff : 0xffffffffffff;
- ceil = MIN(ceil, TEST_IMAGE_SECTORS - 1);
+ ceil = MIN(ceil, mb_to_sectors(test_image_size_mb) - 1);
nsectors = buffsize / AHCI_SECTOR_SIZE;
return ceil - nsectors + 1;
default:
@@ -1595,8 +1576,9 @@ static void create_ahci_io_test(enum IOMode type, enum AddrMode addr,
enum BuffLen len, enum OffsetType offset)
{
char *name;
- AHCIIOTestOptions *opts = g_malloc(sizeof(AHCIIOTestOptions));
+ AHCIIOTestOptions *opts;
+ opts = g_malloc(sizeof(AHCIIOTestOptions));
opts->length = len;
opts->address_type = addr;
opts->io_type = type;
@@ -1608,6 +1590,13 @@ static void create_ahci_io_test(enum IOMode type, enum AddrMode addr,
buff_len_str[len],
offset_str[offset]);
+ if ((addr == ADDR_MODE_LBA48) && (offset == OFFSET_HIGH) &&
+ (mb_to_sectors(test_image_size_mb) <= 0xFFFFFFF)) {
+ g_test_message("%s: skipped; test image too small", name);
+ g_free(name);
+ return;
+ }
+
qtest_add_data_func(name, opts, test_io_interface);
g_free(name);
}
@@ -1654,15 +1643,33 @@ int main(int argc, char **argv)
return 0;
}
- /* Create a temporary qcow2 image */
- close(mkstemp(tmp_path));
- mkqcow2(tmp_path, TEST_IMAGE_SIZE_MB);
+ /* Create a temporary image */
+ fd = mkstemp(tmp_path);
+ g_assert(fd >= 0);
+ if (have_qemu_img()) {
+ imgfmt = "qcow2";
+ test_image_size_mb = TEST_IMAGE_SIZE_MB_LARGE;
+ mkqcow2(tmp_path, TEST_IMAGE_SIZE_MB_LARGE);
+ } else {
+ g_test_message("QTEST_QEMU_IMG not set or qemu-img missing; "
+ "skipping LBA48 high-sector tests");
+ imgfmt = "raw";
+ test_image_size_mb = TEST_IMAGE_SIZE_MB_SMALL;
+ ret = ftruncate(fd, test_image_size_mb * 1024 * 1024);
+ g_assert(ret == 0);
+ }
+ close(fd);
/* Create temporary blkdebug instructions */
fd = mkstemp(debug_path);
g_assert(fd >= 0);
close(fd);
+ /* Reserve a hollow file to use as a socket for migration tests */
+ fd = mkstemp(mig_socket);
+ g_assert(fd >= 0);
+ close(fd);
+
/* Run the tests */
qtest_add_func("/ahci/sanity", test_sanity);
qtest_add_func("/ahci/pci_spec", test_pci_spec);
@@ -1705,6 +1712,7 @@ int main(int argc, char **argv)
/* Cleanup */
unlink(tmp_path);
unlink(debug_path);
+ unlink(mig_socket);
return ret;
}
diff --git a/tests/bios-tables-test.c b/tests/bios-tables-test.c
index 0de1742d7..6d37332a6 100644
--- a/tests/bios-tables-test.c
+++ b/tests/bios-tables-test.c
@@ -18,7 +18,7 @@
#include "libqtest.h"
#include "qemu/compiler.h"
#include "hw/acpi/acpi-defs.h"
-#include "hw/i386/smbios.h"
+#include "hw/smbios/smbios.h"
#include "qemu/bitmap.h"
#define MACHINE_PC "pc"
@@ -50,7 +50,7 @@ typedef struct {
int rsdt_tables_nr;
GArray *tables;
uint32_t smbios_ep_addr;
- struct smbios_entry_point smbios_ep_table;
+ struct smbios_21_entry_point smbios_ep_table;
} test_data;
#define LOW(x) ((x) & 0xff)
@@ -161,31 +161,23 @@ static void free_test_data(test_data *data)
AcpiSdtTable *temp;
int i;
- if (data->rsdt_tables_addr) {
- g_free(data->rsdt_tables_addr);
- }
+ g_free(data->rsdt_tables_addr);
for (i = 0; i < data->tables->len; ++i) {
temp = &g_array_index(data->tables, AcpiSdtTable, i);
- if (temp->aml) {
- g_free(temp->aml);
- }
- if (temp->aml_file) {
- if (!temp->tmp_files_retain &&
- g_strstr_len(temp->aml_file, -1, "aml-")) {
- unlink(temp->aml_file);
- }
- g_free(temp->aml_file);
+ g_free(temp->aml);
+ if (temp->aml_file &&
+ !temp->tmp_files_retain &&
+ g_strstr_len(temp->aml_file, -1, "aml-")) {
+ unlink(temp->aml_file);
}
- if (temp->asl) {
- g_free(temp->asl);
- }
- if (temp->asl_file) {
- if (!temp->tmp_files_retain) {
- unlink(temp->asl_file);
- }
- g_free(temp->asl_file);
+ g_free(temp->aml_file);
+ g_free(temp->asl);
+ if (temp->asl_file &&
+ !temp->tmp_files_retain) {
+ unlink(temp->asl_file);
}
+ g_free(temp->asl_file);
}
g_array_free(data->tables, false);
@@ -420,9 +412,7 @@ static void dump_aml_files(test_data *data, bool rebuild)
close(fd);
- if (aml_file) {
- g_free(aml_file);
- }
+ g_free(aml_file);
}
}
@@ -601,7 +591,7 @@ static void test_acpi_asl(test_data *data)
static bool smbios_ep_table_ok(test_data *data)
{
- struct smbios_entry_point *ep_table = &data->smbios_ep_table;
+ struct smbios_21_entry_point *ep_table = &data->smbios_ep_table;
uint32_t addr = data->smbios_ep_addr;
ACPI_READ_ARRAY(ep_table->anchor_string, addr);
@@ -681,7 +671,7 @@ static inline bool smbios_single_instance(uint8_t type)
static void test_smbios_structs(test_data *data)
{
DECLARE_BITMAP(struct_bitmap, SMBIOS_MAX_TYPE+1) = { 0 };
- struct smbios_entry_point *ep_table = &data->smbios_ep_table;
+ struct smbios_21_entry_point *ep_table = &data->smbios_ep_table;
uint32_t addr = ep_table->structure_table_address;
int i, len, max_len = 0;
uint8_t type, prv, crt;
diff --git a/tests/check-qjson.c b/tests/check-qjson.c
index 1cfffa593..61e9bfbab 100644
--- a/tests/check-qjson.c
+++ b/tests/check-qjson.c
@@ -1484,6 +1484,30 @@ static void unterminated_literal(void)
g_assert(obj == NULL);
}
+static char *make_nest(char *buf, size_t cnt)
+{
+ memset(buf, '[', cnt - 1);
+ buf[cnt - 1] = '{';
+ buf[cnt] = '}';
+ memset(buf + cnt + 1, ']', cnt - 1);
+ buf[2 * cnt] = 0;
+ return buf;
+}
+
+static void limits_nesting(void)
+{
+ enum { max_nesting = 1024 }; /* see qobject/json-streamer.c */
+ char buf[2 * (max_nesting + 1) + 1];
+ QObject *obj;
+
+ obj = qobject_from_json(make_nest(buf, max_nesting));
+ g_assert(obj != NULL);
+ qobject_decref(obj);
+
+ obj = qobject_from_json(make_nest(buf, max_nesting + 1));
+ g_assert(obj == NULL);
+}
+
int main(int argc, char **argv)
{
g_test_init(&argc, &argv, NULL);
@@ -1519,6 +1543,7 @@ int main(int argc, char **argv)
g_test_add_func("/errors/invalid_array_comma", invalid_array_comma);
g_test_add_func("/errors/invalid_dict_comma", invalid_dict_comma);
g_test_add_func("/errors/unterminated/literal", unterminated_literal);
+ g_test_add_func("/errors/limits/nesting", limits_nesting);
return g_test_run();
}
diff --git a/tests/check-qom-proplist.c b/tests/check-qom-proplist.c
index 7400b1fce..e674c0fa8 100644
--- a/tests/check-qom-proplist.c
+++ b/tests/check-qom-proplist.c
@@ -152,6 +152,148 @@ static const TypeInfo dummy_info = {
.class_size = sizeof(DummyObjectClass),
};
+
+/*
+ * The following 3 object classes are used to
+ * simulate the kind of relationships seen in
+ * qdev, which result in complex object
+ * property destruction ordering.
+ *
+ * DummyDev has a 'bus' child to a DummyBus
+ * DummyBus has a 'backend' child to a DummyBackend
+ * DummyDev has a 'backend' link to DummyBackend
+ *
+ * When DummyDev is finalized, it unparents the
+ * DummyBackend, which unparents the DummyDev
+ * which deletes the 'backend' link from DummyDev
+ * to DummyBackend. This illustrates that the
+ * object_property_del_all() method needs to
+ * cope with the list of properties being changed
+ * while it iterates over them.
+ */
+typedef struct DummyDev DummyDev;
+typedef struct DummyDevClass DummyDevClass;
+typedef struct DummyBus DummyBus;
+typedef struct DummyBusClass DummyBusClass;
+typedef struct DummyBackend DummyBackend;
+typedef struct DummyBackendClass DummyBackendClass;
+
+#define TYPE_DUMMY_DEV "qemu-dummy-dev"
+#define TYPE_DUMMY_BUS "qemu-dummy-bus"
+#define TYPE_DUMMY_BACKEND "qemu-dummy-backend"
+
+#define DUMMY_DEV(obj) \
+ OBJECT_CHECK(DummyDev, (obj), TYPE_DUMMY_DEV)
+#define DUMMY_BUS(obj) \
+ OBJECT_CHECK(DummyBus, (obj), TYPE_DUMMY_BUS)
+#define DUMMY_BACKEND(obj) \
+ OBJECT_CHECK(DummyBackend, (obj), TYPE_DUMMY_BACKEND)
+
+struct DummyDev {
+ Object parent_obj;
+
+ DummyBus *bus;
+};
+
+struct DummyDevClass {
+ ObjectClass parent_class;
+};
+
+struct DummyBus {
+ Object parent_obj;
+
+ DummyBackend *backend;
+};
+
+struct DummyBusClass {
+ ObjectClass parent_class;
+};
+
+struct DummyBackend {
+ Object parent_obj;
+};
+
+struct DummyBackendClass {
+ ObjectClass parent_class;
+};
+
+
+static void dummy_dev_init(Object *obj)
+{
+ DummyDev *dev = DUMMY_DEV(obj);
+ DummyBus *bus = DUMMY_BUS(object_new(TYPE_DUMMY_BUS));
+ DummyBackend *backend = DUMMY_BACKEND(object_new(TYPE_DUMMY_BACKEND));
+
+ object_property_add_child(obj, "bus", OBJECT(bus), NULL);
+ dev->bus = bus;
+ object_property_add_child(OBJECT(bus), "backend", OBJECT(backend), NULL);
+ bus->backend = backend;
+
+ object_property_add_link(obj, "backend", TYPE_DUMMY_BACKEND,
+ (Object **)&bus->backend, NULL, 0, NULL);
+}
+
+static void dummy_dev_unparent(Object *obj)
+{
+ DummyDev *dev = DUMMY_DEV(obj);
+ object_unparent(OBJECT(dev->bus));
+}
+
+static void dummy_dev_class_init(ObjectClass *klass, void *opaque)
+{
+ klass->unparent = dummy_dev_unparent;
+}
+
+
+static void dummy_bus_init(Object *obj)
+{
+}
+
+static void dummy_bus_unparent(Object *obj)
+{
+ DummyBus *bus = DUMMY_BUS(obj);
+ object_property_del(obj->parent, "backend", NULL);
+ object_unparent(OBJECT(bus->backend));
+}
+
+static void dummy_bus_class_init(ObjectClass *klass, void *opaque)
+{
+ klass->unparent = dummy_bus_unparent;
+}
+
+static void dummy_backend_init(Object *obj)
+{
+}
+
+
+static const TypeInfo dummy_dev_info = {
+ .name = TYPE_DUMMY_DEV,
+ .parent = TYPE_OBJECT,
+ .instance_size = sizeof(DummyDev),
+ .instance_init = dummy_dev_init,
+ .class_size = sizeof(DummyDevClass),
+ .class_init = dummy_dev_class_init,
+};
+
+static const TypeInfo dummy_bus_info = {
+ .name = TYPE_DUMMY_BUS,
+ .parent = TYPE_OBJECT,
+ .instance_size = sizeof(DummyBus),
+ .instance_init = dummy_bus_init,
+ .class_size = sizeof(DummyBusClass),
+ .class_init = dummy_bus_class_init,
+};
+
+static const TypeInfo dummy_backend_info = {
+ .name = TYPE_DUMMY_BACKEND,
+ .parent = TYPE_OBJECT,
+ .instance_size = sizeof(DummyBackend),
+ .instance_init = dummy_backend_init,
+ .class_size = sizeof(DummyBackendClass),
+};
+
+
+
static void test_dummy_createv(void)
{
Error *err = NULL;
@@ -283,20 +425,83 @@ static void test_dummy_getenum(void)
&err);
g_assert(err != NULL);
error_free(err);
+
+ object_unparent(OBJECT(dobj));
}
+static void test_dummy_iterator(void)
+{
+ Object *parent = object_get_objects_root();
+ DummyObject *dobj = DUMMY_OBJECT(
+ object_new_with_props(TYPE_DUMMY,
+ parent,
+ "dummy0",
+ &error_abort,
+ "bv", "yes",
+ "sv", "Hiss hiss hiss",
+ "av", "platypus",
+ NULL));
+
+ ObjectProperty *prop;
+ ObjectPropertyIterator *iter;
+ bool seenbv = false, seensv = false, seenav = false, seentype;
+
+ iter = object_property_iter_init(OBJECT(dobj));
+ while ((prop = object_property_iter_next(iter))) {
+ if (g_str_equal(prop->name, "bv")) {
+ seenbv = true;
+ } else if (g_str_equal(prop->name, "sv")) {
+ seensv = true;
+ } else if (g_str_equal(prop->name, "av")) {
+ seenav = true;
+ } else if (g_str_equal(prop->name, "type")) {
+ /* This prop comes from the base Object class */
+ seentype = true;
+ } else {
+ g_printerr("Found prop '%s'\n", prop->name);
+ g_assert_not_reached();
+ }
+ }
+ object_property_iter_free(iter);
+ g_assert(seenbv);
+ g_assert(seenav);
+ g_assert(seensv);
+ g_assert(seentype);
+
+ object_unparent(OBJECT(dobj));
+}
+
+
+static void test_dummy_delchild(void)
+{
+ Object *parent = object_get_objects_root();
+ DummyDev *dev = DUMMY_DEV(
+ object_new_with_props(TYPE_DUMMY_DEV,
+ parent,
+ "dev0",
+ &error_abort,
+ NULL));
+
+ object_unparent(OBJECT(dev));
+}
+
int main(int argc, char **argv)
{
g_test_init(&argc, &argv, NULL);
module_call_init(MODULE_INIT_QOM);
type_register_static(&dummy_info);
+ type_register_static(&dummy_dev_info);
+ type_register_static(&dummy_bus_info);
+ type_register_static(&dummy_backend_info);
g_test_add_func("/qom/proplist/createlist", test_dummy_createlist);
g_test_add_func("/qom/proplist/createv", test_dummy_createv);
g_test_add_func("/qom/proplist/badenum", test_dummy_badenum);
g_test_add_func("/qom/proplist/getenum", test_dummy_getenum);
+ g_test_add_func("/qom/proplist/iterator", test_dummy_iterator);
+ g_test_add_func("/qom/proplist/delchild", test_dummy_delchild);
return g_test_run();
}
diff --git a/tests/crypto-tls-x509-helpers.c b/tests/crypto-tls-x509-helpers.c
new file mode 100644
index 000000000..47b4c7ba5
--- /dev/null
+++ b/tests/crypto-tls-x509-helpers.c
@@ -0,0 +1,487 @@
+/*
+ * Copyright (C) 2015 Red Hat, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library. If not, see
+ * <http://www.gnu.org/licenses/>.
+ *
+ * Author: Daniel P. Berrange <berrange@redhat.com>
+ */
+
+#include <stdlib.h>
+#include <fcntl.h>
+
+#include "config-host.h"
+#include "crypto-tls-x509-helpers.h"
+#include "qemu/sockets.h"
+
+#ifdef QCRYPTO_HAVE_TLS_TEST_SUPPORT
+
+/*
+ * This stores some static data that is needed when
+ * encoding extensions in the x509 certs
+ */
+ASN1_TYPE pkix_asn1;
+
+/*
+ * To avoid consuming random entropy to generate keys,
+ * here's one we prepared earlier :-)
+ */
+gnutls_x509_privkey_t privkey;
+# define PRIVATE_KEY \
+ "-----BEGIN PRIVATE KEY-----\n" \
+ "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBALVcr\n" \
+ "BL40Tm6yq88FBhJNw1aaoCjmtg0l4dWQZ/e9Fimx4ARxFpT+ji4FE\n" \
+ "Cgl9s/SGqC+1nvlkm9ViSo0j7MKDbnDB+VRHDvMAzQhA2X7e8M0n9\n" \
+ "rPolUY2lIVC83q0BBaOBkCj2RSmT2xTEbbC2xLukSrg2WP/ihVOxc\n" \
+ "kXRuyFtzAgMBAAECgYB7slBexDwXrtItAMIH6m/U+LUpNe0Xx48OL\n" \
+ "IOn4a4whNgO/o84uIwygUK27ZGFZT0kAGAk8CdF9hA6ArcbQ62s1H\n" \
+ "myxrUbF9/mrLsQw1NEqpuUk9Ay2Tx5U/wPx35S3W/X2AvR/ZpTnCn\n" \
+ "2q/7ym9fyiSoj86drD7BTvmKXlOnOwQJBAPOFMp4mMa9NGpGuEssO\n" \
+ "m3Uwbp6lhcP0cA9MK+iOmeANpoKWfBdk5O34VbmeXnGYWEkrnX+9J\n" \
+ "bM4wVhnnBWtgBMCQQC+qAEmvwcfhauERKYznMVUVksyeuhxhCe7EK\n" \
+ "mPh+U2+g0WwdKvGDgO0PPt1gq0ILEjspMDeMHVdTwkaVBo/uMhAkA\n" \
+ "Z5SsZyCP2aTOPFDypXRdI4eqRcjaEPOUBq27r3uYb/jeboVb2weLa\n" \
+ "L1MmVuHiIHoa5clswPdWVI2y0em2IGoDAkBPSp/v9VKJEZabk9Frd\n" \
+ "a+7u4fanrM9QrEjY3KhduslSilXZZSxrWjjAJPyPiqFb3M8XXA26W\n" \
+ "nz1KYGnqYKhLcBAkB7dt57n9xfrhDpuyVEv+Uv1D3VVAhZlsaZ5Pp\n" \
+ "dcrhrkJn2sa/+O8OKvdrPSeeu/N5WwYhJf61+CPoenMp7IFci\n" \
+ "-----END PRIVATE KEY-----\n"
+
+/*
+ * This loads the private key we defined earlier
+ */
+static gnutls_x509_privkey_t test_tls_load_key(void)
+{
+ gnutls_x509_privkey_t key;
+ const gnutls_datum_t data = { (unsigned char *)PRIVATE_KEY,
+ strlen(PRIVATE_KEY) };
+ int err;
+
+ err = gnutls_x509_privkey_init(&key);
+ if (err < 0) {
+ g_critical("Failed to init key %s", gnutls_strerror(err));
+ abort();
+ }
+
+ err = gnutls_x509_privkey_import(key, &data,
+ GNUTLS_X509_FMT_PEM);
+ if (err < 0) {
+ if (err != GNUTLS_E_BASE64_UNEXPECTED_HEADER_ERROR &&
+ err != GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) {
+ g_critical("Failed to import key %s", gnutls_strerror(err));
+ abort();
+ }
+
+ err = gnutls_x509_privkey_import_pkcs8(
+ key, &data, GNUTLS_X509_FMT_PEM, NULL, 0);
+ if (err < 0) {
+ g_critical("Failed to import PKCS8 key %s", gnutls_strerror(err));
+ abort();
+ }
+ }
+
+ return key;
+}
+
+
+void test_tls_init(const char *keyfile)
+{
+ gnutls_global_init();
+
+ if (asn1_array2tree(pkix_asn1_tab, &pkix_asn1, NULL) != ASN1_SUCCESS) {
+ abort();
+ }
+
+ privkey = test_tls_load_key();
+ if (!g_file_set_contents(keyfile, PRIVATE_KEY, -1, NULL)) {
+ abort();
+ }
+}
+
+
+void test_tls_cleanup(const char *keyfile)
+{
+ asn1_delete_structure(&pkix_asn1);
+ unlink(keyfile);
+}
+
+/*
+ * Turns an ASN1 object into a DER encoded byte array
+ */
+static void test_tls_der_encode(ASN1_TYPE src,
+ const char *src_name,
+ gnutls_datum_t *res)
+{
+ int size;
+ char *data = NULL;
+
+ size = 0;
+ asn1_der_coding(src, src_name, NULL, &size, NULL);
+
+ data = g_new0(char, size);
+
+ asn1_der_coding(src, src_name, data, &size, NULL);
+
+ res->data = (unsigned char *)data;
+ res->size = size;
+}
+
+
+static void
+test_tls_get_ipaddr(const char *addrstr,
+ char **data,
+ int *datalen)
+{
+ struct addrinfo *res;
+ struct addrinfo hints;
+
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_flags = AI_NUMERICHOST;
+ g_assert(getaddrinfo(addrstr, NULL, &hints, &res) == 0);
+
+ *datalen = res->ai_addrlen;
+ *data = g_new(char, *datalen);
+ memcpy(*data, res->ai_addr, *datalen);
+ freeaddrinfo(res);
+}
+
+/*
+ * This is a fairly lame x509 certificate generator.
+ *
+ * Do not copy/use this code for generating real certificates
+ * since it leaves out many things that you would want in
+ * certificates for real world usage.
+ *
+ * This is good enough only for doing tests of the QEMU
+ * TLS certificate code
+ */
+void
+test_tls_generate_cert(QCryptoTLSTestCertReq *req,
+ gnutls_x509_crt_t ca)
+{
+ gnutls_x509_crt_t crt;
+ int err;
+ static char buffer[1024 * 1024];
+ size_t size = sizeof(buffer);
+ char serial[5] = { 1, 2, 3, 4, 0 };
+ gnutls_datum_t der;
+ time_t start = time(NULL) + (60 * 60 * req->start_offset);
+ time_t expire = time(NULL) + (60 * 60 * (req->expire_offset
+ ? req->expire_offset : 24));
+
+ /*
+ * Prepare our new certificate object
+ */
+ err = gnutls_x509_crt_init(&crt);
+ if (err < 0) {
+ g_critical("Failed to initialize certificate %s", gnutls_strerror(err));
+ abort();
+ }
+ err = gnutls_x509_crt_set_key(crt, privkey);
+ if (err < 0) {
+ g_critical("Failed to set certificate key %s", gnutls_strerror(err));
+ abort();
+ }
+
+ /*
+ * A v3 certificate is required in order to be able
+ * set any of the basic constraints, key purpose and
+ * key usage data
+ */
+ gnutls_x509_crt_set_version(crt, 3);
+
+ if (req->country) {
+ err = gnutls_x509_crt_set_dn_by_oid(
+ crt, GNUTLS_OID_X520_COUNTRY_NAME, 0,
+ req->country, strlen(req->country));
+ if (err < 0) {
+ g_critical("Failed to set certificate country name %s",
+ gnutls_strerror(err));
+ abort();
+ }
+ }
+ if (req->cn) {
+ err = gnutls_x509_crt_set_dn_by_oid(
+ crt, GNUTLS_OID_X520_COMMON_NAME, 0,
+ req->cn, strlen(req->cn));
+ if (err < 0) {
+ g_critical("Failed to set certificate common name %s",
+ gnutls_strerror(err));
+ abort();
+ }
+ }
+
+ /*
+ * Setup the subject altnames, which are used
+ * for hostname checks in live sessions
+ */
+ if (req->altname1) {
+ err = gnutls_x509_crt_set_subject_alt_name(
+ crt, GNUTLS_SAN_DNSNAME,
+ req->altname1,
+ strlen(req->altname1),
+ GNUTLS_FSAN_APPEND);
+ if (err < 0) {
+ g_critical("Failed to set certificate alt name %s",
+ gnutls_strerror(err));
+ abort();
+ }
+ }
+ if (req->altname2) {
+ err = gnutls_x509_crt_set_subject_alt_name(
+ crt, GNUTLS_SAN_DNSNAME,
+ req->altname2,
+ strlen(req->altname2),
+ GNUTLS_FSAN_APPEND);
+ if (err < 0) {
+ g_critical("Failed to set certificate %s alt name",
+ gnutls_strerror(err));
+ abort();
+ }
+ }
+
+ /*
+ * IP address need to be put into the cert in their
+ * raw byte form, not strings, hence this is a little
+ * more complicated
+ */
+ if (req->ipaddr1) {
+ char *data;
+ int len;
+
+ test_tls_get_ipaddr(req->ipaddr1, &data, &len);
+
+ err = gnutls_x509_crt_set_subject_alt_name(
+ crt, GNUTLS_SAN_IPADDRESS,
+ data, len, GNUTLS_FSAN_APPEND);
+ if (err < 0) {
+ g_critical("Failed to set certificate alt name %s",
+ gnutls_strerror(err));
+ abort();
+ }
+ g_free(data);
+ }
+ if (req->ipaddr2) {
+ char *data;
+ int len;
+
+ test_tls_get_ipaddr(req->ipaddr2, &data, &len);
+
+ err = gnutls_x509_crt_set_subject_alt_name(
+ crt, GNUTLS_SAN_IPADDRESS,
+ data, len, GNUTLS_FSAN_APPEND);
+ if (err < 0) {
+ g_critical("Failed to set certificate alt name %s",
+ gnutls_strerror(err));
+ abort();
+ }
+ g_free(data);
+ }
+
+
+ /*
+ * Basic constraints are used to decide if the cert
+ * is for a CA or not. We can't use the convenient
+ * gnutls API for setting this, since it hardcodes
+ * the 'critical' field which we want control over
+ */
+ if (req->basicConstraintsEnable) {
+ ASN1_TYPE ext = ASN1_TYPE_EMPTY;
+
+ asn1_create_element(pkix_asn1, "PKIX1.BasicConstraints", &ext);
+ asn1_write_value(ext, "cA",
+ req->basicConstraintsIsCA ? "TRUE" : "FALSE", 1);
+ asn1_write_value(ext, "pathLenConstraint", NULL, 0);
+ test_tls_der_encode(ext, "", &der);
+ err = gnutls_x509_crt_set_extension_by_oid(
+ crt, "2.5.29.19",
+ der.data, der.size,
+ req->basicConstraintsCritical);
+ if (err < 0) {
+ g_critical("Failed to set certificate basic constraints %s",
+ gnutls_strerror(err));
+ g_free(der.data);
+ abort();
+ }
+ asn1_delete_structure(&ext);
+ g_free(der.data);
+ }
+
+ /*
+ * Next up the key usage extension. Again we can't
+ * use the gnutls API since it hardcodes the extension
+ * to be 'critical'
+ */
+ if (req->keyUsageEnable) {
+ ASN1_TYPE ext = ASN1_TYPE_EMPTY;
+ char str[2];
+
+ str[0] = req->keyUsageValue & 0xff;
+ str[1] = (req->keyUsageValue >> 8) & 0xff;
+
+ asn1_create_element(pkix_asn1, "PKIX1.KeyUsage", &ext);
+ asn1_write_value(ext, "", str, 9);
+ test_tls_der_encode(ext, "", &der);
+ err = gnutls_x509_crt_set_extension_by_oid(
+ crt, "2.5.29.15",
+ der.data, der.size,
+ req->keyUsageCritical);
+ if (err < 0) {
+ g_critical("Failed to set certificate key usage %s",
+ gnutls_strerror(err));
+ g_free(der.data);
+ abort();
+ }
+ asn1_delete_structure(&ext);
+ g_free(der.data);
+ }
+
+ /*
+ * Finally the key purpose extension. This time
+ * gnutls has the opposite problem, always hardcoding
+ * it to be non-critical. So once again we have to
+ * set this the hard way building up ASN1 data ourselves
+ */
+ if (req->keyPurposeEnable) {
+ ASN1_TYPE ext = ASN1_TYPE_EMPTY;
+
+ asn1_create_element(pkix_asn1, "PKIX1.ExtKeyUsageSyntax", &ext);
+ if (req->keyPurposeOID1) {
+ asn1_write_value(ext, "", "NEW", 1);
+ asn1_write_value(ext, "?LAST", req->keyPurposeOID1, 1);
+ }
+ if (req->keyPurposeOID2) {
+ asn1_write_value(ext, "", "NEW", 1);
+ asn1_write_value(ext, "?LAST", req->keyPurposeOID2, 1);
+ }
+ test_tls_der_encode(ext, "", &der);
+ err = gnutls_x509_crt_set_extension_by_oid(
+ crt, "2.5.29.37",
+ der.data, der.size,
+ req->keyPurposeCritical);
+ if (err < 0) {
+ g_critical("Failed to set certificate key purpose %s",
+ gnutls_strerror(err));
+ g_free(der.data);
+ abort();
+ }
+ asn1_delete_structure(&ext);
+ g_free(der.data);
+ }
+
+ /*
+ * Any old serial number will do, so lets pick 5
+ */
+ err = gnutls_x509_crt_set_serial(crt, serial, 5);
+ if (err < 0) {
+ g_critical("Failed to set certificate serial %s",
+ gnutls_strerror(err));
+ abort();
+ }
+
+ err = gnutls_x509_crt_set_activation_time(crt, start);
+ if (err < 0) {
+ g_critical("Failed to set certificate activation %s",
+ gnutls_strerror(err));
+ abort();
+ }
+ err = gnutls_x509_crt_set_expiration_time(crt, expire);
+ if (err < 0) {
+ g_critical("Failed to set certificate expiration %s",
+ gnutls_strerror(err));
+ abort();
+ }
+
+
+ /*
+ * If no 'ca' is set then we are self signing
+ * the cert. This is done for the root CA certs
+ */
+ err = gnutls_x509_crt_sign(crt, ca ? ca : crt, privkey);
+ if (err < 0) {
+ g_critical("Failed to sign certificate %s",
+ gnutls_strerror(err));
+ abort();
+ }
+
+ /*
+ * Finally write the new cert out to disk
+ */
+ err = gnutls_x509_crt_export(
+ crt, GNUTLS_X509_FMT_PEM, buffer, &size);
+ if (err < 0) {
+ g_critical("Failed to export certificate %s: %d",
+ gnutls_strerror(err), err);
+ abort();
+ }
+
+ if (!g_file_set_contents(req->filename, buffer, -1, NULL)) {
+ g_critical("Failed to write certificate %s",
+ req->filename);
+ abort();
+ }
+
+ req->crt = crt;
+}
+
+
+void test_tls_write_cert_chain(const char *filename,
+ gnutls_x509_crt_t *certs,
+ size_t ncerts)
+{
+ size_t i;
+ size_t capacity = 1024, offset = 0;
+ char *buffer = g_new0(char, capacity);
+ int err;
+
+ for (i = 0; i < ncerts; i++) {
+ size_t len = capacity - offset;
+ retry:
+ err = gnutls_x509_crt_export(certs[i], GNUTLS_X509_FMT_PEM,
+ buffer + offset, &len);
+ if (err < 0) {
+ if (err == GNUTLS_E_SHORT_MEMORY_BUFFER) {
+ buffer = g_renew(char, buffer, offset + len);
+ capacity = offset + len;
+ goto retry;
+ }
+ g_critical("Failed to export certificate chain %s: %d",
+ gnutls_strerror(err), err);
+ abort();
+ }
+ offset += len;
+ }
+
+ if (!g_file_set_contents(filename, buffer, offset, NULL)) {
+ abort();
+ }
+ g_free(buffer);
+}
+
+
+void test_tls_discard_cert(QCryptoTLSTestCertReq *req)
+{
+ if (!req->crt) {
+ return;
+ }
+
+ gnutls_x509_crt_deinit(req->crt);
+ req->crt = NULL;
+
+ if (getenv("QEMU_TEST_DEBUG_CERTS") == NULL) {
+ unlink(req->filename);
+ }
+}
+
+#endif /* QCRYPTO_HAVE_TLS_TEST_SUPPORT */
diff --git a/tests/crypto-tls-x509-helpers.h b/tests/crypto-tls-x509-helpers.h
new file mode 100644
index 000000000..356b49cd5
--- /dev/null
+++ b/tests/crypto-tls-x509-helpers.h
@@ -0,0 +1,133 @@
+/*
+ * Copyright (C) 2015 Red Hat, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library. If not, see
+ * <http://www.gnu.org/licenses/>.
+ *
+ * Author: Daniel P. Berrange <berrange@redhat.com>
+ */
+
+#include <gnutls/gnutls.h>
+#include <gnutls/x509.h>
+
+#include <gnutls/gnutls.h>
+#include <gnutls/x509.h>
+
+#if !(defined WIN32) && \
+ defined(CONFIG_TASN1) && \
+ defined(LIBGNUTLS_VERSION_NUMBER) && \
+ (LIBGNUTLS_VERSION_NUMBER >= 0x020600)
+# define QCRYPTO_HAVE_TLS_TEST_SUPPORT
+#endif
+
+#ifdef QCRYPTO_HAVE_TLS_TEST_SUPPORT
+# include <libtasn1.h>
+
+# include "qemu-common.h"
+
+/*
+ * This contains parameter about how to generate
+ * certificates.
+ */
+typedef struct QCryptoTLSTestCertReq QCryptoTLSTestCertReq;
+struct QCryptoTLSTestCertReq {
+ gnutls_x509_crt_t crt;
+
+ const char *filename;
+
+ /* Identifying information */
+ const char *country;
+ const char *cn;
+ const char *altname1;
+ const char *altname2;
+ const char *ipaddr1;
+ const char *ipaddr2;
+
+ /* Basic constraints */
+ bool basicConstraintsEnable;
+ bool basicConstraintsCritical;
+ bool basicConstraintsIsCA;
+
+ /* Key usage */
+ bool keyUsageEnable;
+ bool keyUsageCritical;
+ int keyUsageValue;
+
+ /* Key purpose (aka Extended key usage) */
+ bool keyPurposeEnable;
+ bool keyPurposeCritical;
+ const char *keyPurposeOID1;
+ const char *keyPurposeOID2;
+
+ /* zero for current time, or non-zero for hours from now */
+ int start_offset;
+ /* zero for 24 hours from now, or non-zero for hours from now */
+ int expire_offset;
+};
+
+void test_tls_generate_cert(QCryptoTLSTestCertReq *req,
+ gnutls_x509_crt_t ca);
+void test_tls_write_cert_chain(const char *filename,
+ gnutls_x509_crt_t *certs,
+ size_t ncerts);
+void test_tls_discard_cert(QCryptoTLSTestCertReq *req);
+
+void test_tls_init(const char *keyfile);
+void test_tls_cleanup(const char *keyfile);
+
+# define TLS_CERT_REQ(varname, cavarname, \
+ country, commonname, \
+ altname1, altname2, \
+ ipaddr1, ipaddr2, \
+ basicconsenable, basicconscritical, basicconsca, \
+ keyusageenable, keyusagecritical, keyusagevalue, \
+ keypurposeenable, keypurposecritical, \
+ keypurposeoid1, keypurposeoid2, \
+ startoffset, endoffset) \
+ static QCryptoTLSTestCertReq varname = { \
+ NULL, WORKDIR #varname "-ctx.pem", \
+ country, commonname, altname1, altname2, \
+ ipaddr1, ipaddr2, \
+ basicconsenable, basicconscritical, basicconsca, \
+ keyusageenable, keyusagecritical, keyusagevalue, \
+ keypurposeenable, keypurposecritical, \
+ keypurposeoid1, keypurposeoid2, \
+ startoffset, endoffset \
+ }; \
+ test_tls_generate_cert(&varname, cavarname.crt)
+
+# define TLS_ROOT_REQ(varname, \
+ country, commonname, \
+ altname1, altname2, \
+ ipaddr1, ipaddr2, \
+ basicconsenable, basicconscritical, basicconsca, \
+ keyusageenable, keyusagecritical, keyusagevalue, \
+ keypurposeenable, keypurposecritical, \
+ keypurposeoid1, keypurposeoid2, \
+ startoffset, endoffset) \
+ static QCryptoTLSTestCertReq varname = { \
+ NULL, WORKDIR #varname "-ctx.pem", \
+ country, commonname, altname1, altname2, \
+ ipaddr1, ipaddr2, \
+ basicconsenable, basicconscritical, basicconsca, \
+ keyusageenable, keyusagecritical, keyusagevalue, \
+ keypurposeenable, keypurposecritical, \
+ keypurposeoid1, keypurposeoid2, \
+ startoffset, endoffset \
+ }; \
+ test_tls_generate_cert(&varname, NULL)
+
+extern const ASN1_ARRAY_TYPE pkix_asn1_tab[];
+
+#endif /* QCRYPTO_HAVE_TLS_TEST_SUPPORT */
diff --git a/tests/device-introspect-test.c b/tests/device-introspect-test.c
index f240b5c82..11d5fea3e 100644
--- a/tests/device-introspect-test.c
+++ b/tests/device-introspect-test.c
@@ -45,17 +45,10 @@ static void test_one_device(const char *type)
QDict *resp;
char *help, *qom_tree;
- /*
- * Skip this part for the abstract device test case, because
- * device-list-properties crashes for such devices.
- * FIXME fix it not to crash
- */
- if (strcmp(type, "device")) {
- resp = qmp("{'execute': 'device-list-properties',"
- " 'arguments': {'typename': %s}}",
- type);
- QDECREF(resp);
- }
+ resp = qmp("{'execute': 'device-list-properties',"
+ " 'arguments': {'typename': %s}}",
+ type);
+ QDECREF(resp);
help = hmp("device_add \"%s,help\"", type);
g_free(help);
@@ -98,30 +91,6 @@ static void test_device_intro_abstract(void)
qtest_end();
}
-static bool blacklisted(const char *type)
-{
- static const char *blacklist[] = {
- /* hang in object_unref(): */
- "realview_pci", "versatile_pci",
- /* create a CPU, thus use after free (see below): */
- "allwinner-a10", "digic", "fsl,imx25", "fsl,imx31", "xlnx,zynqmp",
- };
- size_t len = strlen(type);
- int i;
-
- if (len >= 4 && !strcmp(type + len - 4, "-cpu")) {
- /* use after free: cpu_exec_init() saves CPUState in cpus */
- return true;
- }
-
- for (i = 0; i < ARRAY_SIZE(blacklist); i++) {
- if (!strcmp(blacklist[i], type)) {
- return true;
- }
- }
- return false;
-}
-
static void test_device_intro_concrete(void)
{
QList *types;
@@ -135,9 +104,6 @@ static void test_device_intro_concrete(void)
type = qdict_get_try_str(qobject_to_qdict(qlist_entry_obj(entry)),
"name");
g_assert(type);
- if (blacklisted(type)) {
- continue; /* FIXME broken device, skip */
- }
test_one_device(type);
}
diff --git a/tests/ds1338-test.c b/tests/ds1338-test.c
new file mode 100644
index 000000000..7d513d897
--- /dev/null
+++ b/tests/ds1338-test.c
@@ -0,0 +1,78 @@
+/*
+ * QTest testcase for the DS1338 RTC
+ *
+ * Copyright (c) 2013 Jean-Christophe Dubois
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the
+ * Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "libqtest.h"
+#include "libqos/i2c.h"
+
+#include <glib.h>
+
+#define IMX25_I2C_0_BASE 0x43F80000
+
+#define DS1338_ADDR 0x68
+
+static I2CAdapter *i2c;
+static uint8_t addr;
+
+static inline uint8_t bcd2bin(uint8_t x)
+{
+ return ((x) & 0x0f) + ((x) >> 4) * 10;
+}
+
+static void send_and_receive(void)
+{
+ uint8_t cmd[1];
+ uint8_t resp[7];
+ time_t now = time(NULL);
+ struct tm *tm_ptr = gmtime(&now);
+
+ /* reset the index in the RTC memory */
+ cmd[0] = 0;
+ i2c_send(i2c, addr, cmd, 1);
+
+ /* retrieve the date */
+ i2c_recv(i2c, addr, resp, 7);
+
+ /* check retrieved time againt local time */
+ g_assert_cmpuint(bcd2bin(resp[4]), == , tm_ptr->tm_mday);
+ g_assert_cmpuint(bcd2bin(resp[5]), == , 1 + tm_ptr->tm_mon);
+ g_assert_cmpuint(2000 + bcd2bin(resp[6]), == , 1900 + tm_ptr->tm_year);
+}
+
+int main(int argc, char **argv)
+{
+ QTestState *s = NULL;
+ int ret;
+
+ g_test_init(&argc, &argv, NULL);
+
+ s = qtest_start("-display none -machine imx25-pdk");
+ i2c = imx_i2c_create(IMX25_I2C_0_BASE);
+ addr = DS1338_ADDR;
+
+ qtest_add_func("/ds1338/tx-rx", send_and_receive);
+
+ ret = g_test_run();
+
+ if (s) {
+ qtest_quit(s);
+ }
+ g_free(i2c);
+
+ return ret;
+}
diff --git a/tests/fdc-test.c b/tests/fdc-test.c
index 416394fc7..b5a4696d8 100644
--- a/tests/fdc-test.c
+++ b/tests/fdc-test.c
@@ -304,9 +304,7 @@ static void test_media_insert(void)
qmp_discard_response("{'execute':'change', 'arguments':{"
" 'device':'floppy0', 'target': %s, 'arg': 'raw' }}",
test_image);
- qmp_discard_response(""); /* ignore event
- (FIXME open -> open transition?!) */
- qmp_discard_response(""); /* ignore event */
+ qmp_discard_response(""); /* ignore event (open -> close) */
dir = inb(FLOPPY_BASE + reg_dir);
assert_bit_set(dir, DSKCHG);
diff --git a/tests/fw_cfg-test.c b/tests/fw_cfg-test.c
index 9be78e956..b7d4007e3 100644
--- a/tests/fw_cfg-test.c
+++ b/tests/fw_cfg-test.c
@@ -37,7 +37,9 @@ static void test_fw_cfg_signature(void)
static void test_fw_cfg_id(void)
{
- g_assert_cmpint(qfw_cfg_get_u32(fw_cfg, FW_CFG_ID), ==, 1);
+ uint32_t id = qfw_cfg_get_u32(fw_cfg, FW_CFG_ID);
+ g_assert((id == 1) ||
+ (id == 3));
}
static void test_fw_cfg_uuid(void)
diff --git a/tests/i440fx-test.c b/tests/i440fx-test.c
index d0bc8de25..7fa170990 100644
--- a/tests/i440fx-test.c
+++ b/tests/i440fx-test.c
@@ -191,7 +191,7 @@ static void write_area(uint32_t start, uint32_t end, uint8_t value)
uint32_t size = end - start + 1;
uint8_t *data;
- data = g_malloc0(size);
+ data = g_malloc(size);
memset(data, value, size);
memwrite(start, data, size);
diff --git a/tests/ide-test.c b/tests/ide-test.c
index ef0a47343..b86470135 100644
--- a/tests/ide-test.c
+++ b/tests/ide-test.c
@@ -45,8 +45,15 @@
#define IDE_BASE 0x1f0
#define IDE_PRIMARY_IRQ 14
+#define ATAPI_BLOCK_SIZE 2048
+
+/* How many bytes to receive via ATAPI PIO at one time.
+ * Must be less than 0xFFFF. */
+#define BYTE_COUNT_LIMIT 5120
+
enum {
reg_data = 0x0,
+ reg_feature = 0x1,
reg_nsectors = 0x2,
reg_lba_low = 0x3,
reg_lba_middle = 0x4,
@@ -80,6 +87,7 @@ enum {
CMD_WRITE_DMA = 0xca,
CMD_FLUSH_CACHE = 0xe7,
CMD_IDENTIFY = 0xec,
+ CMD_PACKET = 0xa0,
CMDF_ABORT = 0x100,
CMDF_NO_BM = 0x200,
@@ -172,7 +180,8 @@ typedef struct PrdtEntry {
#define assert_bit_clear(data, mask) g_assert_cmphex((data) & (mask), ==, 0)
static int send_dma_request(int cmd, uint64_t sector, int nb_sectors,
- PrdtEntry *prdt, int prdt_entries)
+ PrdtEntry *prdt, int prdt_entries,
+ void(*post_exec)(uint64_t sector, int nb_sectors))
{
QPCIDevice *dev;
uint16_t bmdma_base;
@@ -189,6 +198,9 @@ static int send_dma_request(int cmd, uint64_t sector, int nb_sectors,
switch (cmd) {
case CMD_READ_DMA:
+ case CMD_PACKET:
+ /* Assuming we only test data reads w/ ATAPI, otherwise we need to know
+ * the SCSI command being sent in the packet, too. */
from_dev = true;
break;
case CMD_WRITE_DMA:
@@ -217,14 +229,22 @@ static int send_dma_request(int cmd, uint64_t sector, int nb_sectors,
outl(bmdma_base + bmreg_prdt, guest_prdt);
/* ATA DMA command */
- outb(IDE_BASE + reg_nsectors, nb_sectors);
-
- outb(IDE_BASE + reg_lba_low, sector & 0xff);
- outb(IDE_BASE + reg_lba_middle, (sector >> 8) & 0xff);
- outb(IDE_BASE + reg_lba_high, (sector >> 16) & 0xff);
+ if (cmd == CMD_PACKET) {
+ /* Enables ATAPI DMA; otherwise PIO is attempted */
+ outb(IDE_BASE + reg_feature, 0x01);
+ } else {
+ outb(IDE_BASE + reg_nsectors, nb_sectors);
+ outb(IDE_BASE + reg_lba_low, sector & 0xff);
+ outb(IDE_BASE + reg_lba_middle, (sector >> 8) & 0xff);
+ outb(IDE_BASE + reg_lba_high, (sector >> 16) & 0xff);
+ }
outb(IDE_BASE + reg_command, cmd);
+ if (post_exec) {
+ post_exec(sector, nb_sectors);
+ }
+
/* Start DMA transfer */
outb(bmdma_base + bmreg_cmd, BM_CMD_START | (from_dev ? BM_CMD_WRITE : 0));
@@ -278,7 +298,8 @@ static void test_bmdma_simple_rw(void)
memset(buf, 0x55, len);
memwrite(guest_buf, buf, len);
- status = send_dma_request(CMD_WRITE_DMA, 0, 1, prdt, ARRAY_SIZE(prdt));
+ status = send_dma_request(CMD_WRITE_DMA, 0, 1, prdt,
+ ARRAY_SIZE(prdt), NULL);
g_assert_cmphex(status, ==, BM_STS_INTR);
assert_bit_clear(inb(IDE_BASE + reg_status), DF | ERR);
@@ -286,14 +307,15 @@ static void test_bmdma_simple_rw(void)
memset(buf, 0xaa, len);
memwrite(guest_buf, buf, len);
- status = send_dma_request(CMD_WRITE_DMA, 1, 1, prdt, ARRAY_SIZE(prdt));
+ status = send_dma_request(CMD_WRITE_DMA, 1, 1, prdt,
+ ARRAY_SIZE(prdt), NULL);
g_assert_cmphex(status, ==, BM_STS_INTR);
assert_bit_clear(inb(IDE_BASE + reg_status), DF | ERR);
/* Read and verify 0x55 pattern in sector 0 */
memset(cmpbuf, 0x55, len);
- status = send_dma_request(CMD_READ_DMA, 0, 1, prdt, ARRAY_SIZE(prdt));
+ status = send_dma_request(CMD_READ_DMA, 0, 1, prdt, ARRAY_SIZE(prdt), NULL);
g_assert_cmphex(status, ==, BM_STS_INTR);
assert_bit_clear(inb(IDE_BASE + reg_status), DF | ERR);
@@ -303,7 +325,7 @@ static void test_bmdma_simple_rw(void)
/* Read and verify 0xaa pattern in sector 1 */
memset(cmpbuf, 0xaa, len);
- status = send_dma_request(CMD_READ_DMA, 1, 1, prdt, ARRAY_SIZE(prdt));
+ status = send_dma_request(CMD_READ_DMA, 1, 1, prdt, ARRAY_SIZE(prdt), NULL);
g_assert_cmphex(status, ==, BM_STS_INTR);
assert_bit_clear(inb(IDE_BASE + reg_status), DF | ERR);
@@ -328,13 +350,13 @@ static void test_bmdma_short_prdt(void)
/* Normal request */
status = send_dma_request(CMD_READ_DMA, 0, 1,
- prdt, ARRAY_SIZE(prdt));
+ prdt, ARRAY_SIZE(prdt), NULL);
g_assert_cmphex(status, ==, 0);
assert_bit_clear(inb(IDE_BASE + reg_status), DF | ERR);
/* Abort the request before it completes */
status = send_dma_request(CMD_READ_DMA | CMDF_ABORT, 0, 1,
- prdt, ARRAY_SIZE(prdt));
+ prdt, ARRAY_SIZE(prdt), NULL);
g_assert_cmphex(status, ==, 0);
assert_bit_clear(inb(IDE_BASE + reg_status), DF | ERR);
}
@@ -353,13 +375,13 @@ static void test_bmdma_one_sector_short_prdt(void)
/* Normal request */
status = send_dma_request(CMD_READ_DMA, 0, 2,
- prdt, ARRAY_SIZE(prdt));
+ prdt, ARRAY_SIZE(prdt), NULL);
g_assert_cmphex(status, ==, 0);
assert_bit_clear(inb(IDE_BASE + reg_status), DF | ERR);
/* Abort the request before it completes */
status = send_dma_request(CMD_READ_DMA | CMDF_ABORT, 0, 2,
- prdt, ARRAY_SIZE(prdt));
+ prdt, ARRAY_SIZE(prdt), NULL);
g_assert_cmphex(status, ==, 0);
assert_bit_clear(inb(IDE_BASE + reg_status), DF | ERR);
}
@@ -377,13 +399,13 @@ static void test_bmdma_long_prdt(void)
/* Normal request */
status = send_dma_request(CMD_READ_DMA, 0, 1,
- prdt, ARRAY_SIZE(prdt));
+ prdt, ARRAY_SIZE(prdt), NULL);
g_assert_cmphex(status, ==, BM_STS_ACTIVE | BM_STS_INTR);
assert_bit_clear(inb(IDE_BASE + reg_status), DF | ERR);
/* Abort the request before it completes */
status = send_dma_request(CMD_READ_DMA | CMDF_ABORT, 0, 1,
- prdt, ARRAY_SIZE(prdt));
+ prdt, ARRAY_SIZE(prdt), NULL);
g_assert_cmphex(status, ==, BM_STS_INTR);
assert_bit_clear(inb(IDE_BASE + reg_status), DF | ERR);
}
@@ -399,7 +421,7 @@ static void test_bmdma_no_busmaster(void)
PrdtEntry prdt[4096] = { };
status = send_dma_request(CMD_READ_DMA | CMDF_NO_BM, 0, 512,
- prdt, ARRAY_SIZE(prdt));
+ prdt, ARRAY_SIZE(prdt), NULL);
/* Not entirely clear what the expected result is, but this is what we get
* in practice. At least we want to be aware of any changes. */
@@ -571,16 +593,215 @@ static void test_flush_nodev(void)
ide_test_quit();
}
-static void test_pci_retry_flush(const char *machine)
+static void test_pci_retry_flush(void)
{
test_retry_flush("pc");
}
-static void test_isa_retry_flush(const char *machine)
+static void test_isa_retry_flush(void)
{
test_retry_flush("isapc");
}
+typedef struct Read10CDB {
+ uint8_t opcode;
+ uint8_t flags;
+ uint32_t lba;
+ uint8_t reserved;
+ uint16_t nblocks;
+ uint8_t control;
+ uint16_t padding;
+} __attribute__((__packed__)) Read10CDB;
+
+static void send_scsi_cdb_read10(uint64_t lba, int nblocks)
+{
+ Read10CDB pkt = { .padding = 0 };
+ int i;
+
+ g_assert_cmpint(lba, <=, UINT32_MAX);
+ g_assert_cmpint(nblocks, <=, UINT16_MAX);
+ g_assert_cmpint(nblocks, >=, 0);
+
+ /* Construct SCSI CDB packet */
+ pkt.opcode = 0x28;
+ pkt.lba = cpu_to_be32(lba);
+ pkt.nblocks = cpu_to_be16(nblocks);
+
+ /* Send Packet */
+ for (i = 0; i < sizeof(Read10CDB)/2; i++) {
+ outw(IDE_BASE + reg_data, cpu_to_le16(((uint16_t *)&pkt)[i]));
+ }
+}
+
+static void nsleep(int64_t nsecs)
+{
+ const struct timespec val = { .tv_nsec = nsecs };
+ nanosleep(&val, NULL);
+ clock_set(nsecs);
+}
+
+static uint8_t ide_wait_clear(uint8_t flag)
+{
+ uint8_t data;
+ time_t st;
+
+ /* Wait with a 5 second timeout */
+ time(&st);
+ while (true) {
+ data = inb(IDE_BASE + reg_status);
+ if (!(data & flag)) {
+ return data;
+ }
+ if (difftime(time(NULL), st) > 5.0) {
+ break;
+ }
+ nsleep(400);
+ }
+ g_assert_not_reached();
+}
+
+static void ide_wait_intr(int irq)
+{
+ time_t st;
+ bool intr;
+
+ time(&st);
+ while (true) {
+ intr = get_irq(irq);
+ if (intr) {
+ return;
+ }
+ if (difftime(time(NULL), st) > 5.0) {
+ break;
+ }
+ nsleep(400);
+ }
+
+ g_assert_not_reached();
+}
+
+static void cdrom_pio_impl(int nblocks)
+{
+ FILE *fh;
+ int patt_blocks = MAX(16, nblocks);
+ size_t patt_len = ATAPI_BLOCK_SIZE * patt_blocks;
+ char *pattern = g_malloc(patt_len);
+ size_t rxsize = ATAPI_BLOCK_SIZE * nblocks;
+ uint16_t *rx = g_malloc0(rxsize);
+ int i, j;
+ uint8_t data;
+ uint16_t limit;
+
+ /* Prepopulate the CDROM with an interesting pattern */
+ generate_pattern(pattern, patt_len, ATAPI_BLOCK_SIZE);
+ fh = fopen(tmp_path, "w+");
+ fwrite(pattern, ATAPI_BLOCK_SIZE, patt_blocks, fh);
+ fclose(fh);
+
+ ide_test_start("-drive if=none,file=%s,media=cdrom,format=raw,id=sr0,index=0 "
+ "-device ide-cd,drive=sr0,bus=ide.0", tmp_path);
+ qtest_irq_intercept_in(global_qtest, "ioapic");
+
+ /* PACKET command on device 0 */
+ outb(IDE_BASE + reg_device, 0);
+ outb(IDE_BASE + reg_lba_middle, BYTE_COUNT_LIMIT & 0xFF);
+ outb(IDE_BASE + reg_lba_high, (BYTE_COUNT_LIMIT >> 8 & 0xFF));
+ outb(IDE_BASE + reg_command, CMD_PACKET);
+ /* HP0: Check_Status_A State */
+ nsleep(400);
+ data = ide_wait_clear(BSY);
+ /* HP1: Send_Packet State */
+ assert_bit_set(data, DRQ | DRDY);
+ assert_bit_clear(data, ERR | DF | BSY);
+
+ /* SCSI CDB (READ10) -- read n*2048 bytes from block 0 */
+ send_scsi_cdb_read10(0, nblocks);
+
+ /* Read data back: occurs in bursts of 'BYTE_COUNT_LIMIT' bytes.
+ * If BYTE_COUNT_LIMIT is odd, we transfer BYTE_COUNT_LIMIT - 1 bytes.
+ * We allow an odd limit only when the remaining transfer size is
+ * less than BYTE_COUNT_LIMIT. However, SCSI's read10 command can only
+ * request n blocks, so our request size is always even.
+ * For this reason, we assume there is never a hanging byte to fetch. */
+ g_assert(!(rxsize & 1));
+ limit = BYTE_COUNT_LIMIT & ~1;
+ for (i = 0; i < DIV_ROUND_UP(rxsize, limit); i++) {
+ size_t offset = i * (limit / 2);
+ size_t rem = (rxsize / 2) - offset;
+
+ /* HP3: INTRQ_Wait */
+ ide_wait_intr(IDE_PRIMARY_IRQ);
+
+ /* HP2: Check_Status_B (and clear IRQ) */
+ data = ide_wait_clear(BSY);
+ assert_bit_set(data, DRQ | DRDY);
+ assert_bit_clear(data, ERR | DF | BSY);
+
+ /* HP4: Transfer_Data */
+ for (j = 0; j < MIN((limit / 2), rem); j++) {
+ rx[offset + j] = le16_to_cpu(inw(IDE_BASE + reg_data));
+ }
+ }
+
+ /* Check for final completion IRQ */
+ ide_wait_intr(IDE_PRIMARY_IRQ);
+
+ /* Sanity check final state */
+ data = ide_wait_clear(DRQ);
+ assert_bit_set(data, DRDY);
+ assert_bit_clear(data, DRQ | ERR | DF | BSY);
+
+ g_assert_cmpint(memcmp(pattern, rx, rxsize), ==, 0);
+ g_free(pattern);
+ g_free(rx);
+ test_bmdma_teardown();
+}
+
+static void test_cdrom_pio(void)
+{
+ cdrom_pio_impl(1);
+}
+
+static void test_cdrom_pio_large(void)
+{
+ /* Test a few loops of the PIO DRQ mechanism. */
+ cdrom_pio_impl(BYTE_COUNT_LIMIT * 4 / ATAPI_BLOCK_SIZE);
+}
+
+
+static void test_cdrom_dma(void)
+{
+ static const size_t len = ATAPI_BLOCK_SIZE;
+ char *pattern = g_malloc(ATAPI_BLOCK_SIZE * 16);
+ char *rx = g_malloc0(len);
+ uintptr_t guest_buf;
+ PrdtEntry prdt[1];
+ FILE *fh;
+
+ ide_test_start("-drive if=none,file=%s,media=cdrom,format=raw,id=sr0,index=0 "
+ "-device ide-cd,drive=sr0,bus=ide.0", tmp_path);
+ qtest_irq_intercept_in(global_qtest, "ioapic");
+
+ guest_buf = guest_alloc(guest_malloc, len);
+ prdt[0].addr = cpu_to_le32(guest_buf);
+ prdt[0].size = cpu_to_le32(len | PRDT_EOT);
+
+ generate_pattern(pattern, ATAPI_BLOCK_SIZE * 16, ATAPI_BLOCK_SIZE);
+ fh = fopen(tmp_path, "w+");
+ fwrite(pattern, ATAPI_BLOCK_SIZE, 16, fh);
+ fclose(fh);
+
+ send_dma_request(CMD_PACKET, 0, 1, prdt, 1, send_scsi_cdb_read10);
+
+ /* Read back data from guest memory into local qtest memory */
+ memread(guest_buf, rx, len);
+ g_assert_cmpint(memcmp(pattern, rx, len), ==, 0);
+
+ g_free(pattern);
+ g_free(rx);
+ test_bmdma_teardown();
+}
+
int main(int argc, char **argv)
{
const char *arch = qtest_get_arch();
@@ -624,6 +845,10 @@ int main(int argc, char **argv)
qtest_add_func("/ide/flush/retry_pci", test_pci_retry_flush);
qtest_add_func("/ide/flush/retry_isa", test_isa_retry_flush);
+ qtest_add_func("/ide/cdrom/pio", test_cdrom_pio);
+ qtest_add_func("/ide/cdrom/pio_large", test_cdrom_pio_large);
+ qtest_add_func("/ide/cdrom/dma", test_cdrom_dma);
+
ret = g_test_run();
/* Cleanup */
diff --git a/tests/image-fuzzer/runner.py b/tests/image-fuzzer/runner.py
index 0a8743ef4..be7e283dd 100755
--- a/tests/image-fuzzer/runner.py
+++ b/tests/image-fuzzer/runner.py
@@ -301,7 +301,7 @@ if __name__ == '__main__':
JSON:
'--command' accepts a JSON array of commands. Each command presents
- an application under test with all its paramaters as a list of strings,
+ an application under test with all its parameters as a list of strings,
e.g. ["qemu-io", "$test_img", "-c", "write $off $len"].
Supported application aliases: 'qemu-img' and 'qemu-io'.
diff --git a/tests/ivshmem-test.c b/tests/ivshmem-test.c
new file mode 100644
index 000000000..03c7b962a
--- /dev/null
+++ b/tests/ivshmem-test.c
@@ -0,0 +1,494 @@
+/*
+ * QTest testcase for ivshmem
+ *
+ * Copyright (c) 2014 SUSE LINUX Products GmbH
+ * Copyright (c) 2015 Red Hat, Inc.
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
+ * See the COPYING file in the top-level directory.
+ */
+
+#include <errno.h>
+#include <fcntl.h>
+#include <glib.h>
+#include <glib/gstdio.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <unistd.h>
+#include "contrib/ivshmem-server/ivshmem-server.h"
+#include "libqos/pci-pc.h"
+#include "libqtest.h"
+#include "qemu/osdep.h"
+#include "qemu-common.h"
+
+#define TMPSHMSIZE (1 << 20)
+static char *tmpshm;
+static void *tmpshmem;
+static char *tmpdir;
+static char *tmpserver;
+
+static void save_fn(QPCIDevice *dev, int devfn, void *data)
+{
+ QPCIDevice **pdev = (QPCIDevice **) data;
+
+ *pdev = dev;
+}
+
+static QPCIDevice *get_device(void)
+{
+ QPCIDevice *dev;
+ QPCIBus *pcibus;
+
+ pcibus = qpci_init_pc();
+ dev = NULL;
+ qpci_device_foreach(pcibus, 0x1af4, 0x1110, save_fn, &dev);
+ g_assert(dev != NULL);
+
+ return dev;
+}
+
+typedef struct _IVState {
+ QTestState *qtest;
+ void *reg_base, *mem_base;
+ QPCIDevice *dev;
+} IVState;
+
+enum Reg {
+ INTRMASK = 0,
+ INTRSTATUS = 4,
+ IVPOSITION = 8,
+ DOORBELL = 12,
+};
+
+static const char* reg2str(enum Reg reg) {
+ switch (reg) {
+ case INTRMASK:
+ return "IntrMask";
+ case INTRSTATUS:
+ return "IntrStatus";
+ case IVPOSITION:
+ return "IVPosition";
+ case DOORBELL:
+ return "DoorBell";
+ default:
+ return NULL;
+ }
+}
+
+static inline unsigned in_reg(IVState *s, enum Reg reg)
+{
+ const char *name = reg2str(reg);
+ QTestState *qtest = global_qtest;
+ unsigned res;
+
+ global_qtest = s->qtest;
+ res = qpci_io_readl(s->dev, s->reg_base + reg);
+ g_test_message("*%s -> %x\n", name, res);
+ global_qtest = qtest;
+
+ return res;
+}
+
+static inline void out_reg(IVState *s, enum Reg reg, unsigned v)
+{
+ const char *name = reg2str(reg);
+ QTestState *qtest = global_qtest;
+
+ global_qtest = s->qtest;
+ g_test_message("%x -> *%s\n", v, name);
+ qpci_io_writel(s->dev, s->reg_base + reg, v);
+ global_qtest = qtest;
+}
+
+static void setup_vm_cmd(IVState *s, const char *cmd, bool msix)
+{
+ uint64_t barsize;
+
+ s->qtest = qtest_start(cmd);
+
+ s->dev = get_device();
+
+ /* FIXME: other bar order fails, mappings changes */
+ s->mem_base = qpci_iomap(s->dev, 2, &barsize);
+ g_assert_nonnull(s->mem_base);
+ g_assert_cmpuint(barsize, ==, TMPSHMSIZE);
+
+ if (msix) {
+ qpci_msix_enable(s->dev);
+ }
+
+ s->reg_base = qpci_iomap(s->dev, 0, &barsize);
+ g_assert_nonnull(s->reg_base);
+ g_assert_cmpuint(barsize, ==, 256);
+
+ qpci_device_enable(s->dev);
+}
+
+static void setup_vm(IVState *s)
+{
+ char *cmd = g_strdup_printf("-device ivshmem,shm=%s,size=1M", tmpshm);
+
+ setup_vm_cmd(s, cmd, false);
+
+ g_free(cmd);
+}
+
+static void test_ivshmem_single(void)
+{
+ IVState state, *s;
+ uint32_t data[1024];
+ int i;
+
+ setup_vm(&state);
+ s = &state;
+
+ /* valid io */
+ out_reg(s, INTRMASK, 0);
+ in_reg(s, INTRSTATUS);
+ in_reg(s, IVPOSITION);
+
+ out_reg(s, INTRMASK, 0xffffffff);
+ g_assert_cmpuint(in_reg(s, INTRMASK), ==, 0xffffffff);
+ out_reg(s, INTRSTATUS, 1);
+ /* XXX: intercept IRQ, not seen in resp */
+ g_assert_cmpuint(in_reg(s, INTRSTATUS), ==, 1);
+
+ /* invalid io */
+ out_reg(s, IVPOSITION, 1);
+ out_reg(s, DOORBELL, 8 << 16);
+
+ for (i = 0; i < G_N_ELEMENTS(data); i++) {
+ data[i] = i;
+ }
+ qtest_memwrite(s->qtest, (uintptr_t)s->mem_base, data, sizeof(data));
+
+ for (i = 0; i < G_N_ELEMENTS(data); i++) {
+ g_assert_cmpuint(((uint32_t *)tmpshmem)[i], ==, i);
+ }
+
+ memset(data, 0, sizeof(data));
+
+ qtest_memread(s->qtest, (uintptr_t)s->mem_base, data, sizeof(data));
+ for (i = 0; i < G_N_ELEMENTS(data); i++) {
+ g_assert_cmpuint(data[i], ==, i);
+ }
+
+ qtest_quit(s->qtest);
+}
+
+static void test_ivshmem_pair(void)
+{
+ IVState state1, state2, *s1, *s2;
+ char *data;
+ int i;
+
+ setup_vm(&state1);
+ s1 = &state1;
+ setup_vm(&state2);
+ s2 = &state2;
+
+ data = g_malloc0(TMPSHMSIZE);
+
+ /* host write, guest 1 & 2 read */
+ memset(tmpshmem, 0x42, TMPSHMSIZE);
+ qtest_memread(s1->qtest, (uintptr_t)s1->mem_base, data, TMPSHMSIZE);
+ for (i = 0; i < TMPSHMSIZE; i++) {
+ g_assert_cmpuint(data[i], ==, 0x42);
+ }
+ qtest_memread(s2->qtest, (uintptr_t)s2->mem_base, data, TMPSHMSIZE);
+ for (i = 0; i < TMPSHMSIZE; i++) {
+ g_assert_cmpuint(data[i], ==, 0x42);
+ }
+
+ /* guest 1 write, guest 2 read */
+ memset(data, 0x43, TMPSHMSIZE);
+ qtest_memwrite(s1->qtest, (uintptr_t)s1->mem_base, data, TMPSHMSIZE);
+ memset(data, 0, TMPSHMSIZE);
+ qtest_memread(s2->qtest, (uintptr_t)s2->mem_base, data, TMPSHMSIZE);
+ for (i = 0; i < TMPSHMSIZE; i++) {
+ g_assert_cmpuint(data[i], ==, 0x43);
+ }
+
+ /* guest 2 write, guest 1 read */
+ memset(data, 0x44, TMPSHMSIZE);
+ qtest_memwrite(s2->qtest, (uintptr_t)s2->mem_base, data, TMPSHMSIZE);
+ memset(data, 0, TMPSHMSIZE);
+ qtest_memread(s1->qtest, (uintptr_t)s2->mem_base, data, TMPSHMSIZE);
+ for (i = 0; i < TMPSHMSIZE; i++) {
+ g_assert_cmpuint(data[i], ==, 0x44);
+ }
+
+ qtest_quit(s1->qtest);
+ qtest_quit(s2->qtest);
+ g_free(data);
+}
+
+typedef struct ServerThread {
+ GThread *thread;
+ IvshmemServer *server;
+ int pipe[2]; /* to handle quit */
+} ServerThread;
+
+static void *server_thread(void *data)
+{
+ ServerThread *t = data;
+ IvshmemServer *server = t->server;
+
+ while (true) {
+ fd_set fds;
+ int maxfd, ret;
+
+ FD_ZERO(&fds);
+ FD_SET(t->pipe[0], &fds);
+ maxfd = t->pipe[0] + 1;
+
+ ivshmem_server_get_fds(server, &fds, &maxfd);
+
+ ret = select(maxfd, &fds, NULL, NULL, NULL);
+
+ if (ret < 0) {
+ if (errno == EINTR) {
+ continue;
+ }
+
+ g_critical("select error: %s\n", strerror(errno));
+ break;
+ }
+ if (ret == 0) {
+ continue;
+ }
+
+ if (FD_ISSET(t->pipe[0], &fds)) {
+ break;
+ }
+
+ if (ivshmem_server_handle_fds(server, &fds, maxfd) < 0) {
+ g_critical("ivshmem_server_handle_fds() failed\n");
+ break;
+ }
+ }
+
+ return NULL;
+}
+
+static void setup_vm_with_server(IVState *s, int nvectors)
+{
+ char *cmd = g_strdup_printf("-chardev socket,id=chr0,path=%s,nowait "
+ "-device ivshmem,size=1M,chardev=chr0,vectors=%d",
+ tmpserver, nvectors);
+
+ setup_vm_cmd(s, cmd, true);
+
+ g_free(cmd);
+}
+
+static void test_ivshmem_server(void)
+{
+ IVState state1, state2, *s1, *s2;
+ ServerThread thread;
+ IvshmemServer server;
+ int ret, vm1, vm2;
+ int nvectors = 2;
+ guint64 end_time = g_get_monotonic_time() + 5 * G_TIME_SPAN_SECOND;
+
+ memset(tmpshmem, 0x42, TMPSHMSIZE);
+ ret = ivshmem_server_init(&server, tmpserver, tmpshm,
+ TMPSHMSIZE, nvectors,
+ g_test_verbose());
+ g_assert_cmpint(ret, ==, 0);
+
+ ret = ivshmem_server_start(&server);
+ g_assert_cmpint(ret, ==, 0);
+
+ setup_vm_with_server(&state1, nvectors);
+ s1 = &state1;
+ setup_vm_with_server(&state2, nvectors);
+ s2 = &state2;
+
+ g_assert_cmpuint(in_reg(s1, IVPOSITION), ==, 0xffffffff);
+ g_assert_cmpuint(in_reg(s2, IVPOSITION), ==, 0xffffffff);
+
+ g_assert_cmpuint(qtest_readb(s1->qtest, (uintptr_t)s1->mem_base), ==, 0x00);
+
+ thread.server = &server;
+ ret = pipe(thread.pipe);
+ g_assert_cmpint(ret, ==, 0);
+ thread.thread = g_thread_new("ivshmem-server", server_thread, &thread);
+ g_assert(thread.thread != NULL);
+
+ /* waiting until mapping is done */
+ while (g_get_monotonic_time() < end_time) {
+ g_usleep(1000);
+
+ if (qtest_readb(s1->qtest, (uintptr_t)s1->mem_base) == 0x42 &&
+ qtest_readb(s2->qtest, (uintptr_t)s2->mem_base) == 0x42) {
+ break;
+ }
+ }
+
+ /* check got different VM ids */
+ vm1 = in_reg(s1, IVPOSITION);
+ vm2 = in_reg(s2, IVPOSITION);
+ g_assert_cmpuint(vm1, !=, vm2);
+
+ global_qtest = s1->qtest;
+ ret = qpci_msix_table_size(s1->dev);
+ g_assert_cmpuint(ret, ==, nvectors);
+
+ /* ping vm2 -> vm1 */
+ ret = qpci_msix_pending(s1->dev, 0);
+ g_assert_cmpuint(ret, ==, 0);
+ out_reg(s2, DOORBELL, vm1 << 16);
+ do {
+ g_usleep(10000);
+ ret = qpci_msix_pending(s1->dev, 0);
+ } while (ret == 0 && g_get_monotonic_time() < end_time);
+ g_assert_cmpuint(ret, !=, 0);
+
+ /* ping vm1 -> vm2 */
+ global_qtest = s2->qtest;
+ ret = qpci_msix_pending(s2->dev, 0);
+ g_assert_cmpuint(ret, ==, 0);
+ out_reg(s1, DOORBELL, vm2 << 16);
+ do {
+ g_usleep(10000);
+ ret = qpci_msix_pending(s2->dev, 0);
+ } while (ret == 0 && g_get_monotonic_time() < end_time);
+ g_assert_cmpuint(ret, !=, 0);
+
+ qtest_quit(s2->qtest);
+ qtest_quit(s1->qtest);
+
+ if (qemu_write_full(thread.pipe[1], "q", 1) != 1) {
+ g_error("qemu_write_full: %s", g_strerror(errno));
+ }
+
+ g_thread_join(thread.thread);
+
+ ivshmem_server_close(&server);
+ close(thread.pipe[1]);
+ close(thread.pipe[0]);
+}
+
+#define PCI_SLOT_HP 0x06
+
+static void test_ivshmem_hotplug(void)
+{
+ gchar *opts;
+
+ qtest_start("");
+
+ opts = g_strdup_printf("'shm': '%s', 'size': '1M'", tmpshm);
+
+ qpci_plug_device_test("ivshmem", "iv1", PCI_SLOT_HP, opts);
+ qpci_unplug_acpi_device_test("iv1", PCI_SLOT_HP);
+
+ qtest_end();
+ g_free(opts);
+}
+
+static void test_ivshmem_memdev(void)
+{
+ IVState state;
+
+ /* just for the sake of checking memory-backend property */
+ setup_vm_cmd(&state, "-object memory-backend-ram,size=1M,id=mb1"
+ " -device ivshmem,x-memdev=mb1", false);
+
+ qtest_quit(state.qtest);
+}
+
+static void cleanup(void)
+{
+ if (tmpshmem) {
+ munmap(tmpshmem, TMPSHMSIZE);
+ tmpshmem = NULL;
+ }
+
+ if (tmpshm) {
+ shm_unlink(tmpshm);
+ g_free(tmpshm);
+ tmpshm = NULL;
+ }
+
+ if (tmpserver) {
+ g_unlink(tmpserver);
+ g_free(tmpserver);
+ tmpserver = NULL;
+ }
+
+ if (tmpdir) {
+ g_rmdir(tmpdir);
+ tmpdir = NULL;
+ }
+}
+
+static void abrt_handler(void *data)
+{
+ cleanup();
+}
+
+static gchar *mktempshm(int size, int *fd)
+{
+ while (true) {
+ gchar *name;
+
+ name = g_strdup_printf("/qtest-%u-%u", getpid(), g_random_int());
+ *fd = shm_open(name, O_CREAT|O_RDWR|O_EXCL,
+ S_IRWXU|S_IRWXG|S_IRWXO);
+ if (*fd > 0) {
+ g_assert(ftruncate(*fd, size) == 0);
+ return name;
+ }
+
+ g_free(name);
+
+ if (errno != EEXIST) {
+ perror("shm_open");
+ return NULL;
+ }
+ }
+}
+
+int main(int argc, char **argv)
+{
+ int ret, fd;
+ gchar dir[] = "/tmp/ivshmem-test.XXXXXX";
+
+#if !GLIB_CHECK_VERSION(2, 31, 0)
+ if (!g_thread_supported()) {
+ g_thread_init(NULL);
+ }
+#endif
+
+ g_test_init(&argc, &argv, NULL);
+
+ qtest_add_abrt_handler(abrt_handler, NULL);
+ /* shm */
+ tmpshm = mktempshm(TMPSHMSIZE, &fd);
+ if (!tmpshm) {
+ return 0;
+ }
+ tmpshmem = mmap(0, TMPSHMSIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
+ g_assert(tmpshmem != MAP_FAILED);
+ /* server */
+ if (mkdtemp(dir) == NULL) {
+ g_error("mkdtemp: %s", g_strerror(errno));
+ }
+ tmpdir = dir;
+ tmpserver = g_strconcat(tmpdir, "/server", NULL);
+
+ qtest_add_func("/ivshmem/single", test_ivshmem_single);
+ qtest_add_func("/ivshmem/hotplug", test_ivshmem_hotplug);
+ qtest_add_func("/ivshmem/memdev", test_ivshmem_memdev);
+ if (g_test_slow()) {
+ qtest_add_func("/ivshmem/pair", test_ivshmem_pair);
+ qtest_add_func("/ivshmem/server", test_ivshmem_server);
+ }
+
+ ret = g_test_run();
+
+ cleanup();
+
+ return ret;
+}
diff --git a/tests/libqos/ahci.c b/tests/libqos/ahci.c
index cf66b3e32..adb2665c6 100644
--- a/tests/libqos/ahci.c
+++ b/tests/libqos/ahci.c
@@ -742,7 +742,7 @@ AHCICommand *ahci_command_create(uint8_t command_name)
g_assert(!(props->lba28 && props->lba48));
g_assert(!(props->read && props->write));
g_assert(!props->size || props->data);
- g_assert(!props->ncq || (props->ncq && props->lba48));
+ g_assert(!props->ncq || props->lba48);
/* Defaults and book-keeping */
cmd->props = props;
diff --git a/tests/libqos/i2c-imx.c b/tests/libqos/i2c-imx.c
new file mode 100644
index 000000000..b5cef66b9
--- /dev/null
+++ b/tests/libqos/i2c-imx.c
@@ -0,0 +1,209 @@
+/*
+ * QTest i.MX I2C driver
+ *
+ * Copyright (c) 2013 Jean-Christophe Dubois
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the
+ * Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "libqos/i2c.h"
+
+#include <glib.h>
+#include <string.h>
+
+#include "qemu/osdep.h"
+#include "libqtest.h"
+
+#include "hw/i2c/imx_i2c.h"
+
+enum IMXI2CDirection {
+ IMX_I2C_READ,
+ IMX_I2C_WRITE,
+};
+
+typedef struct IMXI2C {
+ I2CAdapter parent;
+
+ uint64_t addr;
+} IMXI2C;
+
+
+static void imx_i2c_set_slave_addr(IMXI2C *s, uint8_t addr,
+ enum IMXI2CDirection direction)
+{
+ writeb(s->addr + I2DR_ADDR, (addr << 1) |
+ (direction == IMX_I2C_READ ? 1 : 0));
+}
+
+static void imx_i2c_send(I2CAdapter *i2c, uint8_t addr,
+ const uint8_t *buf, uint16_t len)
+{
+ IMXI2C *s = (IMXI2C *)i2c;
+ uint8_t data;
+ uint8_t status;
+ uint16_t size = 0;
+
+ if (!len) {
+ return;
+ }
+
+ /* set the bus for write */
+ data = I2CR_IEN |
+ I2CR_IIEN |
+ I2CR_MSTA |
+ I2CR_MTX |
+ I2CR_TXAK;
+
+ writeb(s->addr + I2CR_ADDR, data);
+ status = readb(s->addr + I2SR_ADDR);
+ g_assert((status & I2SR_IBB) != 0);
+
+ /* set the slave address */
+ imx_i2c_set_slave_addr(s, addr, IMX_I2C_WRITE);
+ status = readb(s->addr + I2SR_ADDR);
+ g_assert((status & I2SR_IIF) != 0);
+ g_assert((status & I2SR_RXAK) == 0);
+
+ /* ack the interrupt */
+ writeb(s->addr + I2SR_ADDR, 0);
+ status = readb(s->addr + I2SR_ADDR);
+ g_assert((status & I2SR_IIF) == 0);
+
+ while (size < len) {
+ /* check we are still busy */
+ status = readb(s->addr + I2SR_ADDR);
+ g_assert((status & I2SR_IBB) != 0);
+
+ /* write the data */
+ writeb(s->addr + I2DR_ADDR, buf[size]);
+ status = readb(s->addr + I2SR_ADDR);
+ g_assert((status & I2SR_IIF) != 0);
+ g_assert((status & I2SR_RXAK) == 0);
+
+ /* ack the interrupt */
+ writeb(s->addr + I2SR_ADDR, 0);
+ status = readb(s->addr + I2SR_ADDR);
+ g_assert((status & I2SR_IIF) == 0);
+
+ size++;
+ }
+
+ /* release the bus */
+ data &= ~(I2CR_MSTA | I2CR_MTX);
+ writeb(s->addr + I2CR_ADDR, data);
+ status = readb(s->addr + I2SR_ADDR);
+ g_assert((status & I2SR_IBB) == 0);
+}
+
+static void imx_i2c_recv(I2CAdapter *i2c, uint8_t addr,
+ uint8_t *buf, uint16_t len)
+{
+ IMXI2C *s = (IMXI2C *)i2c;
+ uint8_t data;
+ uint8_t status;
+ uint16_t size = 0;
+
+ if (!len) {
+ return;
+ }
+
+ /* set the bus for write */
+ data = I2CR_IEN |
+ I2CR_IIEN |
+ I2CR_MSTA |
+ I2CR_MTX |
+ I2CR_TXAK;
+
+ writeb(s->addr + I2CR_ADDR, data);
+ status = readb(s->addr + I2SR_ADDR);
+ g_assert((status & I2SR_IBB) != 0);
+
+ /* set the slave address */
+ imx_i2c_set_slave_addr(s, addr, IMX_I2C_READ);
+ status = readb(s->addr + I2SR_ADDR);
+ g_assert((status & I2SR_IIF) != 0);
+ g_assert((status & I2SR_RXAK) == 0);
+
+ /* ack the interrupt */
+ writeb(s->addr + I2SR_ADDR, 0);
+ status = readb(s->addr + I2SR_ADDR);
+ g_assert((status & I2SR_IIF) == 0);
+
+ /* set the bus for read */
+ data &= ~I2CR_MTX;
+ /* if only one byte don't ack */
+ if (len != 1) {
+ data &= ~I2CR_TXAK;
+ }
+ writeb(s->addr + I2CR_ADDR, data);
+ status = readb(s->addr + I2SR_ADDR);
+ g_assert((status & I2SR_IBB) != 0);
+
+ /* dummy read */
+ readb(s->addr + I2DR_ADDR);
+ status = readb(s->addr + I2SR_ADDR);
+ g_assert((status & I2SR_IIF) != 0);
+
+ /* ack the interrupt */
+ writeb(s->addr + I2SR_ADDR, 0);
+ status = readb(s->addr + I2SR_ADDR);
+ g_assert((status & I2SR_IIF) == 0);
+
+ while (size < len) {
+ /* check we are still busy */
+ status = readb(s->addr + I2SR_ADDR);
+ g_assert((status & I2SR_IBB) != 0);
+
+ if (size == (len - 1)) {
+ /* stop the read transaction */
+ data &= ~(I2CR_MSTA | I2CR_MTX);
+ } else {
+ /* ack the data read */
+ data |= I2CR_TXAK;
+ }
+ writeb(s->addr + I2CR_ADDR, data);
+
+ /* read the data */
+ buf[size] = readb(s->addr + I2DR_ADDR);
+
+ if (size != (len - 1)) {
+ status = readb(s->addr + I2SR_ADDR);
+ g_assert((status & I2SR_IIF) != 0);
+
+ /* ack the interrupt */
+ writeb(s->addr + I2SR_ADDR, 0);
+ }
+
+ status = readb(s->addr + I2SR_ADDR);
+ g_assert((status & I2SR_IIF) == 0);
+
+ size++;
+ }
+
+ status = readb(s->addr + I2SR_ADDR);
+ g_assert((status & I2SR_IBB) == 0);
+}
+
+I2CAdapter *imx_i2c_create(uint64_t addr)
+{
+ IMXI2C *s = g_malloc0(sizeof(*s));
+ I2CAdapter *i2c = (I2CAdapter *)s;
+
+ s->addr = addr;
+
+ i2c->send = imx_i2c_send;
+ i2c->recv = imx_i2c_recv;
+
+ return i2c;
+}
diff --git a/tests/libqos/i2c.h b/tests/libqos/i2c.h
index 1ce9af405..c21f1dcbd 100644
--- a/tests/libqos/i2c.h
+++ b/tests/libqos/i2c.h
@@ -27,4 +27,7 @@ void i2c_recv(I2CAdapter *i2c, uint8_t addr,
/* libi2c-omap.c */
I2CAdapter *omap_i2c_create(uint64_t addr);
+/* libi2c-imx.c */
+I2CAdapter *imx_i2c_create(uint64_t addr);
+
#endif
diff --git a/tests/libqos/libqos.c b/tests/libqos/libqos.c
index fce625b18..2d1a802db 100644
--- a/tests/libqos/libqos.c
+++ b/tests/libqos/libqos.c
@@ -147,6 +147,23 @@ void migrate(QOSState *from, QOSState *to, const char *uri)
set_context(to);
}
+bool have_qemu_img(void)
+{
+ char *rpath;
+ const char *path = getenv("QTEST_QEMU_IMG");
+ if (!path) {
+ return false;
+ }
+
+ rpath = realpath(path, NULL);
+ if (!rpath) {
+ return false;
+ } else {
+ free(rpath);
+ return true;
+ }
+}
+
void mkimg(const char *file, const char *fmt, unsigned size_mb)
{
gchar *cli;
@@ -155,13 +172,14 @@ void mkimg(const char *file, const char *fmt, unsigned size_mb)
GError *err = NULL;
char *qemu_img_path;
gchar *out, *out2;
- char *abs_path;
+ char *qemu_img_abs_path;
qemu_img_path = getenv("QTEST_QEMU_IMG");
- abs_path = realpath(qemu_img_path, NULL);
- assert(qemu_img_path);
+ g_assert(qemu_img_path);
+ qemu_img_abs_path = realpath(qemu_img_path, NULL);
+ g_assert(qemu_img_abs_path);
- cli = g_strdup_printf("%s create -f %s %s %uM", abs_path,
+ cli = g_strdup_printf("%s create -f %s %s %uM", qemu_img_abs_path,
fmt, file, size_mb);
ret = g_spawn_command_line_sync(cli, &out, &out2, &rc, &err);
if (err) {
@@ -183,7 +201,7 @@ void mkimg(const char *file, const char *fmt, unsigned size_mb)
g_free(out);
g_free(out2);
g_free(cli);
- free(abs_path);
+ free(qemu_img_abs_path);
}
void mkqcow2(const char *file, unsigned size_mb)
@@ -212,3 +230,29 @@ void prepare_blkdebug_script(const char *debug_fn, const char *event)
ret = fclose(debug_file);
g_assert(ret == 0);
}
+
+void generate_pattern(void *buffer, size_t len, size_t cycle_len)
+{
+ int i, j;
+ unsigned char *tx = (unsigned char *)buffer;
+ unsigned char p;
+ size_t *sx;
+
+ /* Write an indicative pattern that varies and is unique per-cycle */
+ p = rand() % 256;
+ for (i = 0; i < len; i++) {
+ tx[i] = p++ % 256;
+ if (i % cycle_len == 0) {
+ p = rand() % 256;
+ }
+ }
+
+ /* force uniqueness by writing an id per-cycle */
+ for (i = 0; i < len / cycle_len; i++) {
+ j = i * cycle_len;
+ if (j + sizeof(*sx) <= len) {
+ sx = (size_t *)&tx[j];
+ *sx = i;
+ }
+ }
+}
diff --git a/tests/libqos/libqos.h b/tests/libqos/libqos.h
index e1f14ea6f..ca14d2e9f 100644
--- a/tests/libqos/libqos.h
+++ b/tests/libqos/libqos.h
@@ -19,11 +19,13 @@ typedef struct QOSState {
QOSState *qtest_vboot(QOSOps *ops, const char *cmdline_fmt, va_list ap);
QOSState *qtest_boot(QOSOps *ops, const char *cmdline_fmt, ...);
void qtest_shutdown(QOSState *qs);
+bool have_qemu_img(void);
void mkimg(const char *file, const char *fmt, unsigned size_mb);
void mkqcow2(const char *file, unsigned size_mb);
void set_context(QOSState *s);
void migrate(QOSState *from, QOSState *to, const char *uri);
void prepare_blkdebug_script(const char *debug_fn, const char *event);
+void generate_pattern(void *buffer, size_t len, size_t cycle_len);
static inline uint64_t qmalloc(QOSState *q, size_t bytes)
{
diff --git a/tests/libqtest.c b/tests/libqtest.c
index f1b8206c3..fa314e1ee 100644
--- a/tests/libqtest.c
+++ b/tests/libqtest.c
@@ -46,9 +46,9 @@ struct QTestState
bool irq_level[MAX_IRQ];
GString *rx;
pid_t qemu_pid; /* our child QEMU process */
- struct sigaction sigact_old; /* restored on exit */
};
+static GHookList abrt_hooks;
static GList *qtest_instances;
static struct sigaction sigact_old;
@@ -110,12 +110,14 @@ static void kill_qemu(QTestState *s)
}
}
+static void kill_qemu_hook_func(void *s)
+{
+ kill_qemu(s);
+}
+
static void sigabrt_handler(int signo)
{
- GList *elem;
- for (elem = qtest_instances; elem; elem = elem->next) {
- kill_qemu(elem->data);
- }
+ g_hook_list_invoke(&abrt_hooks, FALSE);
}
static void setup_sigabrt_handler(void)
@@ -136,6 +138,23 @@ static void cleanup_sigabrt_handler(void)
sigaction(SIGABRT, &sigact_old, NULL);
}
+void qtest_add_abrt_handler(GHookFunc fn, const void *data)
+{
+ GHook *hook;
+
+ /* Only install SIGABRT handler once */
+ if (!abrt_hooks.is_setup) {
+ g_hook_list_init(&abrt_hooks, sizeof(GHook));
+ setup_sigabrt_handler();
+ }
+
+ hook = g_hook_alloc(&abrt_hooks);
+ hook->func = fn;
+ hook->data = (void *)data;
+
+ g_hook_prepend(&abrt_hooks, hook);
+}
+
QTestState *qtest_init(const char *extra_args)
{
QTestState *s;
@@ -156,12 +175,7 @@ QTestState *qtest_init(const char *extra_args)
sock = init_socket(socket_path);
qmpsock = init_socket(qmp_socket_path);
- /* Only install SIGABRT handler once */
- if (!qtest_instances) {
- setup_sigabrt_handler();
- }
-
- qtest_instances = g_list_prepend(qtest_instances, s);
+ qtest_add_abrt_handler(kill_qemu_hook_func, s);
s->qemu_pid = fork();
if (s->qemu_pid == 0) {
@@ -209,13 +223,14 @@ QTestState *qtest_init(const char *extra_args)
void qtest_quit(QTestState *s)
{
+ qtest_instances = g_list_remove(qtest_instances, s);
+ g_hook_destroy_link(&abrt_hooks, g_hook_find_data(&abrt_hooks, TRUE, s));
+
/* Uninstall SIGABRT handler on last instance */
- if (qtest_instances && !qtest_instances->next) {
+ if (!qtest_instances) {
cleanup_sigabrt_handler();
}
- qtest_instances = g_list_remove(qtest_instances, s);
-
kill_qemu(s);
close(s->fd);
close(s->qmp_fd);
@@ -341,7 +356,7 @@ typedef struct {
QDict *response;
} QMPResponseParser;
-static void qmp_response(JSONMessageParser *parser, QList *tokens)
+static void qmp_response(JSONMessageParser *parser, GQueue *tokens)
{
QMPResponseParser *qmp = container_of(parser, QMPResponseParser, parser);
QObject *obj;
@@ -357,7 +372,7 @@ static void qmp_response(JSONMessageParser *parser, QList *tokens)
qmp->response = (QDict *)obj;
}
-QDict *qtest_qmp_receive(QTestState *s)
+QDict *qmp_fd_receive(int fd)
{
QMPResponseParser qmp;
bool log = getenv("QTEST_LOG") != NULL;
@@ -368,7 +383,7 @@ QDict *qtest_qmp_receive(QTestState *s)
ssize_t len;
char c;
- len = read(s->qmp_fd, &c, 1);
+ len = read(fd, &c, 1);
if (len == -1 && errno == EINTR) {
continue;
}
@@ -388,12 +403,17 @@ QDict *qtest_qmp_receive(QTestState *s)
return qmp.response;
}
+QDict *qtest_qmp_receive(QTestState *s)
+{
+ return qmp_fd_receive(s->qmp_fd);
+}
+
/**
* Allow users to send a message without waiting for the reply,
* in the case that they choose to discard all replies up until
* a particular EVENT is received.
*/
-void qtest_async_qmpv(QTestState *s, const char *fmt, va_list ap)
+void qmp_fd_sendv(int fd, const char *fmt, va_list ap)
{
va_list ap_copy;
QObject *qobj;
@@ -417,13 +437,25 @@ void qtest_async_qmpv(QTestState *s, const char *fmt, va_list ap)
fprintf(stderr, "%s", str);
}
/* Send QMP request */
- socket_send(s->qmp_fd, str, size);
+ socket_send(fd, str, size);
QDECREF(qstr);
qobject_decref(qobj);
}
}
+void qtest_async_qmpv(QTestState *s, const char *fmt, va_list ap)
+{
+ qmp_fd_sendv(s->qmp_fd, fmt, ap);
+}
+
+QDict *qmp_fdv(int fd, const char *fmt, va_list ap)
+{
+ qmp_fd_sendv(fd, fmt, ap);
+
+ return qmp_fd_receive(fd);
+}
+
QDict *qtest_qmpv(QTestState *s, const char *fmt, va_list ap)
{
qtest_async_qmpv(s, fmt, ap);
@@ -432,6 +464,26 @@ QDict *qtest_qmpv(QTestState *s, const char *fmt, va_list ap)
return qtest_qmp_receive(s);
}
+QDict *qmp_fd(int fd, const char *fmt, ...)
+{
+ va_list ap;
+ QDict *response;
+
+ va_start(ap, fmt);
+ response = qmp_fdv(fd, fmt, ap);
+ va_end(ap);
+ return response;
+}
+
+void qmp_fd_send(int fd, const char *fmt, ...)
+{
+ va_list ap;
+
+ va_start(ap, fmt);
+ qmp_fd_sendv(fd, fmt, ap);
+ va_end(ap);
+}
+
QDict *qtest_qmp(QTestState *s, const char *fmt, ...)
{
va_list ap;
@@ -708,14 +760,15 @@ void qtest_memread(QTestState *s, uint64_t addr, void *data, size_t size)
g_strfreev(args);
}
-void qtest_add_func(const char *str, void (*fn))
+void qtest_add_func(const char *str, void (*fn)(void))
{
gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
g_test_add_func(path, fn);
g_free(path);
}
-void qtest_add_data_func(const char *str, const void *data, void (*fn))
+void qtest_add_data_func(const char *str, const void *data,
+ void (*fn)(const void *))
{
gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
g_test_add_data_func(path, data, fn);
diff --git a/tests/libqtest.h b/tests/libqtest.h
index 55bccbf0e..ebdd5bbe5 100644
--- a/tests/libqtest.h
+++ b/tests/libqtest.h
@@ -416,7 +416,7 @@ const char *qtest_get_arch(void);
* The path is prefixed with the architecture under test, as
* returned by qtest_get_arch().
*/
-void qtest_add_func(const char *str, void (*fn));
+void qtest_add_func(const char *str, void (*fn)(void));
/**
* qtest_add_data_func:
@@ -428,7 +428,8 @@ void qtest_add_func(const char *str, void (*fn));
* The path is prefixed with the architecture under test, as
* returned by qtest_get_arch().
*/
-void qtest_add_data_func(const char *str, const void *data, void (*fn));
+void qtest_add_data_func(const char *str, const void *data,
+ void (*fn)(const void *));
/**
* qtest_add:
@@ -450,6 +451,8 @@ void qtest_add_data_func(const char *str, const void *data, void (*fn));
g_free(path); \
} while (0)
+void qtest_add_abrt_handler(GHookFunc fn, const void *data);
+
/**
* qtest_start:
* @args: other arguments to pass to QEMU
@@ -851,4 +854,11 @@ static inline int64_t clock_set(int64_t val)
*/
bool qtest_big_endian(void);
+
+QDict *qmp_fd_receive(int fd);
+void qmp_fd_sendv(int fd, const char *fmt, va_list ap);
+void qmp_fd_send(int fd, const char *fmt, ...);
+QDict *qmp_fdv(int fd, const char *fmt, va_list ap);
+QDict *qmp_fd(int fd, const char *fmt, ...);
+
#endif
diff --git a/tests/pkix_asn1_tab.c b/tests/pkix_asn1_tab.c
new file mode 100644
index 000000000..5b4e6b9e2
--- /dev/null
+++ b/tests/pkix_asn1_tab.c
@@ -0,0 +1,1104 @@
+/*
+ * This file is taken from gnutls 1.6.3 under the GPLv2+
+ * and is under copyright of various GNUTLS contributors.
+ */
+
+#include <libtasn1.h>
+
+const ASN1_ARRAY_TYPE pkix_asn1_tab[] = {
+ {"PKIX1", 536875024, 0},
+ {0, 1073741836, 0},
+ {"id-ce", 1879048204, 0},
+ {"joint-iso-ccitt", 1073741825, "2"},
+ {"ds", 1073741825, "5"},
+ {0, 1, "29"},
+ {"id-ce-authorityKeyIdentifier", 1879048204, 0},
+ {0, 1073741825, "id-ce"},
+ {0, 1, "35"},
+ {"AuthorityKeyIdentifier", 1610612741, 0},
+ {"keyIdentifier", 1610637314, "KeyIdentifier"},
+ {0, 4104, "0"},
+ {"authorityCertIssuer", 1610637314, "GeneralNames"},
+ {0, 4104, "1"},
+ {"authorityCertSerialNumber", 536895490, "CertificateSerialNumber"},
+ {0, 4104, "2"},
+ {"KeyIdentifier", 1073741831, 0},
+ {"id-ce-subjectKeyIdentifier", 1879048204, 0},
+ {0, 1073741825, "id-ce"},
+ {0, 1, "14"},
+ {"SubjectKeyIdentifier", 1073741826, "KeyIdentifier"},
+ {"id-ce-keyUsage", 1879048204, 0},
+ {0, 1073741825, "id-ce"},
+ {0, 1, "15"},
+ {"KeyUsage", 1610874886, 0},
+ {"digitalSignature", 1073741825, "0"},
+ {"nonRepudiation", 1073741825, "1"},
+ {"keyEncipherment", 1073741825, "2"},
+ {"dataEncipherment", 1073741825, "3"},
+ {"keyAgreement", 1073741825, "4"},
+ {"keyCertSign", 1073741825, "5"},
+ {"cRLSign", 1073741825, "6"},
+ {"encipherOnly", 1073741825, "7"},
+ {"decipherOnly", 1, "8"},
+ {"id-ce-privateKeyUsagePeriod", 1879048204, 0},
+ {0, 1073741825, "id-ce"},
+ {0, 1, "16"},
+ {"PrivateKeyUsagePeriod", 1610612741, 0},
+ {"notBefore", 1619025937, 0},
+ {0, 4104, "0"},
+ {"notAfter", 545284113, 0},
+ {0, 4104, "1"},
+ {"id-ce-certificatePolicies", 1879048204, 0},
+ {0, 1073741825, "id-ce"},
+ {0, 1, "32"},
+ {"CertificatePolicies", 1612709899, 0},
+ {"MAX", 1074266122, "1"},
+ {0, 2, "PolicyInformation"},
+ {"PolicyInformation", 1610612741, 0},
+ {"policyIdentifier", 1073741826, "CertPolicyId"},
+ {"policyQualifiers", 538984459, 0},
+ {"MAX", 1074266122, "1"},
+ {0, 2, "PolicyQualifierInfo"},
+ {"CertPolicyId", 1073741836, 0},
+ {"PolicyQualifierInfo", 1610612741, 0},
+ {"policyQualifierId", 1073741826, "PolicyQualifierId"},
+ {"qualifier", 541065229, 0},
+ {"policyQualifierId", 1, 0},
+ {"PolicyQualifierId", 1073741836, 0},
+ {"CPSuri", 1073741826, "IA5String"},
+ {"UserNotice", 1610612741, 0},
+ {"noticeRef", 1073758210, "NoticeReference"},
+ {"explicitText", 16386, "DisplayText"},
+ {"NoticeReference", 1610612741, 0},
+ {"organization", 1073741826, "DisplayText"},
+ {"noticeNumbers", 536870923, 0},
+ {0, 3, 0},
+ {"DisplayText", 1610612754, 0},
+ {"visibleString", 1612709890, "VisibleString"},
+ {"200", 524298, "1"},
+ {"bmpString", 1612709890, "BMPString"},
+ {"200", 524298, "1"},
+ {"utf8String", 538968066, "UTF8String"},
+ {"200", 524298, "1"},
+ {"id-ce-policyMappings", 1879048204, 0},
+ {0, 1073741825, "id-ce"},
+ {0, 1, "33"},
+ {"PolicyMappings", 1612709899, 0},
+ {"MAX", 1074266122, "1"},
+ {0, 536870917, 0},
+ {"issuerDomainPolicy", 1073741826, "CertPolicyId"},
+ {"subjectDomainPolicy", 2, "CertPolicyId"},
+ {"DirectoryString", 1610612754, 0},
+ {"teletexString", 1612709890, "TeletexString"},
+ {"MAX", 524298, "1"},
+ {"printableString", 1612709890, "PrintableString"},
+ {"MAX", 524298, "1"},
+ {"universalString", 1612709890, "UniversalString"},
+ {"MAX", 524298, "1"},
+ {"utf8String", 1612709890, "UTF8String"},
+ {"MAX", 524298, "1"},
+ {"bmpString", 1612709890, "BMPString"},
+ {"MAX", 524298, "1"},
+ {"ia5String", 538968066, "IA5String"},
+ {"MAX", 524298, "1"},
+ {"id-ce-subjectAltName", 1879048204, 0},
+ {0, 1073741825, "id-ce"},
+ {0, 1, "17"},
+ {"SubjectAltName", 1073741826, "GeneralNames"},
+ {"GeneralNames", 1612709899, 0},
+ {"MAX", 1074266122, "1"},
+ {0, 2, "GeneralName"},
+ {"GeneralName", 1610612754, 0},
+ {"otherName", 1610620930, "AnotherName"},
+ {0, 4104, "0"},
+ {"rfc822Name", 1610620930, "IA5String"},
+ {0, 4104, "1"},
+ {"dNSName", 1610620930, "IA5String"},
+ {0, 4104, "2"},
+ {"x400Address", 1610620930, "ORAddress"},
+ {0, 4104, "3"},
+ {"directoryName", 1610620930, "RDNSequence"},
+ {0, 2056, "4"},
+ {"ediPartyName", 1610620930, "EDIPartyName"},
+ {0, 4104, "5"},
+ {"uniformResourceIdentifier", 1610620930, "IA5String"},
+ {0, 4104, "6"},
+ {"iPAddress", 1610620935, 0},
+ {0, 4104, "7"},
+ {"registeredID", 536879116, 0},
+ {0, 4104, "8"},
+ {"AnotherName", 1610612741, 0},
+ {"type-id", 1073741836, 0},
+ {"value", 541073421, 0},
+ {0, 1073743880, "0"},
+ {"type-id", 1, 0},
+ {"EDIPartyName", 1610612741, 0},
+ {"nameAssigner", 1610637314, "DirectoryString"},
+ {0, 4104, "0"},
+ {"partyName", 536879106, "DirectoryString"},
+ {0, 4104, "1"},
+ {"id-ce-issuerAltName", 1879048204, 0},
+ {0, 1073741825, "id-ce"},
+ {0, 1, "18"},
+ {"IssuerAltName", 1073741826, "GeneralNames"},
+ {"id-ce-subjectDirectoryAttributes", 1879048204, 0},
+ {0, 1073741825, "id-ce"},
+ {0, 1, "9"},
+ {"SubjectDirectoryAttributes", 1612709899, 0},
+ {"MAX", 1074266122, "1"},
+ {0, 2, "Attribute"},
+ {"id-ce-basicConstraints", 1879048204, 0},
+ {0, 1073741825, "id-ce"},
+ {0, 1, "19"},
+ {"BasicConstraints", 1610612741, 0},
+ {"cA", 1610645508, 0},
+ {0, 131081, 0},
+ {"pathLenConstraint", 537411587, 0},
+ {"0", 10, "MAX"},
+ {"id-ce-nameConstraints", 1879048204, 0},
+ {0, 1073741825, "id-ce"},
+ {0, 1, "30"},
+ {"NameConstraints", 1610612741, 0},
+ {"permittedSubtrees", 1610637314, "GeneralSubtrees"},
+ {0, 4104, "0"},
+ {"excludedSubtrees", 536895490, "GeneralSubtrees"},
+ {0, 4104, "1"},
+ {"GeneralSubtrees", 1612709899, 0},
+ {"MAX", 1074266122, "1"},
+ {0, 2, "GeneralSubtree"},
+ {"GeneralSubtree", 1610612741, 0},
+ {"base", 1073741826, "GeneralName"},
+ {"minimum", 1610653698, "BaseDistance"},
+ {0, 1073741833, "0"},
+ {0, 4104, "0"},
+ {"maximum", 536895490, "BaseDistance"},
+ {0, 4104, "1"},
+ {"BaseDistance", 1611137027, 0},
+ {"0", 10, "MAX"},
+ {"id-ce-policyConstraints", 1879048204, 0},
+ {0, 1073741825, "id-ce"},
+ {0, 1, "36"},
+ {"PolicyConstraints", 1610612741, 0},
+ {"requireExplicitPolicy", 1610637314, "SkipCerts"},
+ {0, 4104, "0"},
+ {"inhibitPolicyMapping", 536895490, "SkipCerts"},
+ {0, 4104, "1"},
+ {"SkipCerts", 1611137027, 0},
+ {"0", 10, "MAX"},
+ {"id-ce-cRLDistributionPoints", 1879048204, 0},
+ {0, 1073741825, "id-ce"},
+ {0, 1, "31"},
+ {"CRLDistributionPoints", 1612709899, 0},
+ {"MAX", 1074266122, "1"},
+ {0, 2, "DistributionPoint"},
+ {"DistributionPoint", 1610612741, 0},
+ {"distributionPoint", 1610637314, "DistributionPointName"},
+ {0, 2056, "0"},
+ {"reasons", 1610637314, "ReasonFlags"},
+ {0, 4104, "1"},
+ {"cRLIssuer", 536895490, "GeneralNames"},
+ {0, 4104, "2"},
+ {"DistributionPointName", 1610612754, 0},
+ {"fullName", 1610620930, "GeneralNames"},
+ {0, 4104, "0"},
+ {"nameRelativeToCRLIssuer", 536879106, "RelativeDistinguishedName"},
+ {0, 4104, "1"},
+ {"ReasonFlags", 1610874886, 0},
+ {"unused", 1073741825, "0"},
+ {"keyCompromise", 1073741825, "1"},
+ {"cACompromise", 1073741825, "2"},
+ {"affiliationChanged", 1073741825, "3"},
+ {"superseded", 1073741825, "4"},
+ {"cessationOfOperation", 1073741825, "5"},
+ {"certificateHold", 1073741825, "6"},
+ {"privilegeWithdrawn", 1073741825, "7"},
+ {"aACompromise", 1, "8"},
+ {"id-ce-extKeyUsage", 1879048204, 0},
+ {0, 1073741825, "id-ce"},
+ {0, 1, "37"},
+ {"ExtKeyUsageSyntax", 1612709899, 0},
+ {"MAX", 1074266122, "1"},
+ {0, 2, "KeyPurposeId"},
+ {"KeyPurposeId", 1073741836, 0},
+ {"id-kp-serverAuth", 1879048204, 0},
+ {0, 1073741825, "id-kp"},
+ {0, 1, "1"},
+ {"id-kp-clientAuth", 1879048204, 0},
+ {0, 1073741825, "id-kp"},
+ {0, 1, "2"},
+ {"id-kp-codeSigning", 1879048204, 0},
+ {0, 1073741825, "id-kp"},
+ {0, 1, "3"},
+ {"id-kp-emailProtection", 1879048204, 0},
+ {0, 1073741825, "id-kp"},
+ {0, 1, "4"},
+ {"id-kp-ipsecEndSystem", 1879048204, 0},
+ {0, 1073741825, "id-kp"},
+ {0, 1, "5"},
+ {"id-kp-ipsecTunnel", 1879048204, 0},
+ {0, 1073741825, "id-kp"},
+ {0, 1, "6"},
+ {"id-kp-ipsecUser", 1879048204, 0},
+ {0, 1073741825, "id-kp"},
+ {0, 1, "7"},
+ {"id-kp-timeStamping", 1879048204, 0},
+ {0, 1073741825, "id-kp"},
+ {0, 1, "8"},
+ {"id-pe-authorityInfoAccess", 1879048204, 0},
+ {0, 1073741825, "id-pe"},
+ {0, 1, "1"},
+ {"AuthorityInfoAccessSyntax", 1612709899, 0},
+ {"MAX", 1074266122, "1"},
+ {0, 2, "AccessDescription"},
+ {"AccessDescription", 1610612741, 0},
+ {"accessMethod", 1073741836, 0},
+ {"accessLocation", 2, "GeneralName"},
+ {"id-ce-cRLNumber", 1879048204, 0},
+ {0, 1073741825, "id-ce"},
+ {0, 1, "20"},
+ {"CRLNumber", 1611137027, 0},
+ {"0", 10, "MAX"},
+ {"id-ce-issuingDistributionPoint", 1879048204, 0},
+ {0, 1073741825, "id-ce"},
+ {0, 1, "28"},
+ {"IssuingDistributionPoint", 1610612741, 0},
+ {"distributionPoint", 1610637314, "DistributionPointName"},
+ {0, 4104, "0"},
+ {"onlyContainsUserCerts", 1610653700, 0},
+ {0, 1073872905, 0},
+ {0, 4104, "1"},
+ {"onlyContainsCACerts", 1610653700, 0},
+ {0, 1073872905, 0},
+ {0, 4104, "2"},
+ {"onlySomeReasons", 1610637314, "ReasonFlags"},
+ {0, 4104, "3"},
+ {"indirectCRL", 536911876, 0},
+ {0, 1073872905, 0},
+ {0, 4104, "4"},
+ {"id-ce-deltaCRLIndicator", 1879048204, 0},
+ {0, 1073741825, "id-ce"},
+ {0, 1, "27"},
+ {"BaseCRLNumber", 1073741826, "CRLNumber"},
+ {"id-ce-cRLReasons", 1879048204, 0},
+ {0, 1073741825, "id-ce"},
+ {0, 1, "21"},
+ {"CRLReason", 1610874901, 0},
+ {"unspecified", 1073741825, "0"},
+ {"keyCompromise", 1073741825, "1"},
+ {"cACompromise", 1073741825, "2"},
+ {"affiliationChanged", 1073741825, "3"},
+ {"superseded", 1073741825, "4"},
+ {"cessationOfOperation", 1073741825, "5"},
+ {"certificateHold", 1073741825, "6"},
+ {"removeFromCRL", 1, "8"},
+ {"id-ce-certificateIssuer", 1879048204, 0},
+ {0, 1073741825, "id-ce"},
+ {0, 1, "29"},
+ {"CertificateIssuer", 1073741826, "GeneralNames"},
+ {"id-ce-holdInstructionCode", 1879048204, 0},
+ {0, 1073741825, "id-ce"},
+ {0, 1, "23"},
+ {"HoldInstructionCode", 1073741836, 0},
+ {"holdInstruction", 1879048204, 0},
+ {"joint-iso-itu-t", 1073741825, "2"},
+ {"member-body", 1073741825, "2"},
+ {"us", 1073741825, "840"},
+ {"x9cm", 1073741825, "10040"},
+ {0, 1, "2"},
+ {"id-holdinstruction-none", 1879048204, 0},
+ {0, 1073741825, "holdInstruction"},
+ {0, 1, "1"},
+ {"id-holdinstruction-callissuer", 1879048204, 0},
+ {0, 1073741825, "holdInstruction"},
+ {0, 1, "2"},
+ {"id-holdinstruction-reject", 1879048204, 0},
+ {0, 1073741825, "holdInstruction"},
+ {0, 1, "3"},
+ {"id-ce-invalidityDate", 1879048204, 0},
+ {0, 1073741825, "id-ce"},
+ {0, 1, "24"},
+ {"InvalidityDate", 1082130449, 0},
+ {"VisibleString", 1610620935, 0},
+ {0, 4360, "26"},
+ {"NumericString", 1610620935, 0},
+ {0, 4360, "18"},
+ {"IA5String", 1610620935, 0},
+ {0, 4360, "22"},
+ {"TeletexString", 1610620935, 0},
+ {0, 4360, "20"},
+ {"PrintableString", 1610620935, 0},
+ {0, 4360, "19"},
+ {"UniversalString", 1610620935, 0},
+ {0, 4360, "28"},
+ {"BMPString", 1610620935, 0},
+ {0, 4360, "30"},
+ {"UTF8String", 1610620935, 0},
+ {0, 4360, "12"},
+ {"id-pkix", 1879048204, 0},
+ {"iso", 1073741825, "1"},
+ {"identified-organization", 1073741825, "3"},
+ {"dod", 1073741825, "6"},
+ {"internet", 1073741825, "1"},
+ {"security", 1073741825, "5"},
+ {"mechanisms", 1073741825, "5"},
+ {"pkix", 1, "7"},
+ {"id-pe", 1879048204, 0},
+ {0, 1073741825, "id-pkix"},
+ {0, 1, "1"},
+ {"id-qt", 1879048204, 0},
+ {0, 1073741825, "id-pkix"},
+ {0, 1, "2"},
+ {"id-kp", 1879048204, 0},
+ {0, 1073741825, "id-pkix"},
+ {0, 1, "3"},
+ {"id-ad", 1879048204, 0},
+ {0, 1073741825, "id-pkix"},
+ {0, 1, "48"},
+ {"id-qt-cps", 1879048204, 0},
+ {0, 1073741825, "id-qt"},
+ {0, 1, "1"},
+ {"id-qt-unotice", 1879048204, 0},
+ {0, 1073741825, "id-qt"},
+ {0, 1, "2"},
+ {"id-ad-ocsp", 1879048204, 0},
+ {0, 1073741825, "id-ad"},
+ {0, 1, "1"},
+ {"id-ad-caIssuers", 1879048204, 0},
+ {0, 1073741825, "id-ad"},
+ {0, 1, "2"},
+ {"Attribute", 1610612741, 0},
+ {"type", 1073741826, "AttributeType"},
+ {"values", 536870927, 0},
+ {0, 2, "AttributeValue"},
+ {"AttributeType", 1073741836, 0},
+ {"AttributeValue", 1614807053, 0},
+ {"type", 1, 0},
+ {"AttributeTypeAndValue", 1610612741, 0},
+ {"type", 1073741826, "AttributeType"},
+ {"value", 2, "AttributeValue"},
+ {"id-at", 1879048204, 0},
+ {"joint-iso-ccitt", 1073741825, "2"},
+ {"ds", 1073741825, "5"},
+ {0, 1, "4"},
+ {"id-at-initials", 1880096780, "AttributeType"},
+ {0, 1073741825, "id-at"},
+ {0, 1, "43"},
+ {"X520initials", 1073741826, "DirectoryString"},
+ {"id-at-generationQualifier", 1880096780, "AttributeType"},
+ {0, 1073741825, "id-at"},
+ {0, 1, "44"},
+ {"X520generationQualifier", 1073741826, "DirectoryString"},
+ {"id-at-surname", 1880096780, "AttributeType"},
+ {0, 1073741825, "id-at"},
+ {0, 1, "4"},
+ {"X520surName", 1073741826, "DirectoryString"},
+ {"id-at-givenName", 1880096780, "AttributeType"},
+ {0, 1073741825, "id-at"},
+ {0, 1, "42"},
+ {"X520givenName", 1073741826, "DirectoryString"},
+ {"id-at-name", 1880096780, "AttributeType"},
+ {0, 1073741825, "id-at"},
+ {0, 1, "41"},
+ {"X520name", 1073741826, "DirectoryString"},
+ {"id-at-commonName", 1880096780, "AttributeType"},
+ {0, 1073741825, "id-at"},
+ {0, 1, "3"},
+ {"X520CommonName", 1073741826, "DirectoryString"},
+ {"id-at-localityName", 1880096780, "AttributeType"},
+ {0, 1073741825, "id-at"},
+ {0, 1, "7"},
+ {"X520LocalityName", 1073741826, "DirectoryString"},
+ {"id-at-stateOrProvinceName", 1880096780, "AttributeType"},
+ {0, 1073741825, "id-at"},
+ {0, 1, "8"},
+ {"X520StateOrProvinceName", 1073741826, "DirectoryString"},
+ {"id-at-organizationName", 1880096780, "AttributeType"},
+ {0, 1073741825, "id-at"},
+ {0, 1, "10"},
+ {"X520OrganizationName", 1073741826, "DirectoryString"},
+ {"id-at-organizationalUnitName", 1880096780, "AttributeType"},
+ {0, 1073741825, "id-at"},
+ {0, 1, "11"},
+ {"X520OrganizationalUnitName", 1073741826, "DirectoryString"},
+ {"id-at-title", 1880096780, "AttributeType"},
+ {0, 1073741825, "id-at"},
+ {0, 1, "12"},
+ {"X520Title", 1073741826, "DirectoryString"},
+ {"id-at-description", 1880096780, "AttributeType"},
+ {0, 1073741825, "id-at"},
+ {0, 1, "13"},
+ {"X520Description", 1073741826, "DirectoryString"},
+ {"id-at-dnQualifier", 1880096780, "AttributeType"},
+ {0, 1073741825, "id-at"},
+ {0, 1, "46"},
+ {"X520dnQualifier", 1073741826, "PrintableString"},
+ {"id-at-countryName", 1880096780, "AttributeType"},
+ {0, 1073741825, "id-at"},
+ {0, 1, "6"},
+ {"X520countryName", 1612709890, "PrintableString"},
+ {0, 1048586, "2"},
+ {"id-at-serialNumber", 1880096780, "AttributeType"},
+ {0, 1073741825, "id-at"},
+ {0, 1, "5"},
+ {"X520serialNumber", 1073741826, "PrintableString"},
+ {"id-at-telephoneNumber", 1880096780, "AttributeType"},
+ {0, 1073741825, "id-at"},
+ {0, 1, "20"},
+ {"X520telephoneNumber", 1073741826, "PrintableString"},
+ {"id-at-facsimileTelephoneNumber", 1880096780, "AttributeType"},
+ {0, 1073741825, "id-at"},
+ {0, 1, "23"},
+ {"X520facsimileTelephoneNumber", 1073741826, "PrintableString"},
+ {"id-at-pseudonym", 1880096780, "AttributeType"},
+ {0, 1073741825, "id-at"},
+ {0, 1, "65"},
+ {"X520pseudonym", 1073741826, "DirectoryString"},
+ {"id-at-name", 1880096780, "AttributeType"},
+ {0, 1073741825, "id-at"},
+ {0, 1, "41"},
+ {"X520name", 1073741826, "DirectoryString"},
+ {"id-at-streetAddress", 1880096780, "AttributeType"},
+ {0, 1073741825, "id-at"},
+ {0, 1, "9"},
+ {"X520streetAddress", 1073741826, "DirectoryString"},
+ {"id-at-postalAddress", 1880096780, "AttributeType"},
+ {0, 1073741825, "id-at"},
+ {0, 1, "16"},
+ {"X520postalAddress", 1073741826, "PostalAddress"},
+ {"PostalAddress", 1610612747, 0},
+ {0, 2, "DirectoryString"},
+ {"pkcs", 1879048204, 0},
+ {"iso", 1073741825, "1"},
+ {"member-body", 1073741825, "2"},
+ {"us", 1073741825, "840"},
+ {"rsadsi", 1073741825, "113549"},
+ {"pkcs", 1, "1"},
+ {"pkcs-9", 1879048204, 0},
+ {0, 1073741825, "pkcs"},
+ {0, 1, "9"},
+ {"emailAddress", 1880096780, "AttributeType"},
+ {0, 1073741825, "pkcs-9"},
+ {0, 1, "1"},
+ {"Pkcs9email", 1612709890, "IA5String"},
+ {"ub-emailaddress-length", 524298, "1"},
+ {"Name", 1610612754, 0},
+ {"rdnSequence", 2, "RDNSequence"},
+ {"RDNSequence", 1610612747, 0},
+ {0, 2, "RelativeDistinguishedName"},
+ {"DistinguishedName", 1073741826, "RDNSequence"},
+ {"RelativeDistinguishedName", 1612709903, 0},
+ {"MAX", 1074266122, "1"},
+ {0, 2, "AttributeTypeAndValue"},
+ {"Certificate", 1610612741, 0},
+ {"tbsCertificate", 1073741826, "TBSCertificate"},
+ {"signatureAlgorithm", 1073741826, "AlgorithmIdentifier"},
+ {"signature", 6, 0},
+ {"TBSCertificate", 1610612741, 0},
+ {"version", 1610653698, "Version"},
+ {0, 1073741833, "v1"},
+ {0, 2056, "0"},
+ {"serialNumber", 1073741826, "CertificateSerialNumber"},
+ {"signature", 1073741826, "AlgorithmIdentifier"},
+ {"issuer", 1073741826, "Name"},
+ {"validity", 1073741826, "Validity"},
+ {"subject", 1073741826, "Name"},
+ {"subjectPublicKeyInfo", 1073741826, "SubjectPublicKeyInfo"},
+ {"issuerUniqueID", 1610637314, "UniqueIdentifier"},
+ {0, 4104, "1"},
+ {"subjectUniqueID", 1610637314, "UniqueIdentifier"},
+ {0, 4104, "2"},
+ {"extensions", 536895490, "Extensions"},
+ {0, 2056, "3"},
+ {"Version", 1610874883, 0},
+ {"v1", 1073741825, "0"},
+ {"v2", 1073741825, "1"},
+ {"v3", 1, "2"},
+ {"CertificateSerialNumber", 1073741827, 0},
+ {"Validity", 1610612741, 0},
+ {"notBefore", 1073741826, "Time"},
+ {"notAfter", 2, "Time"},
+ {"Time", 1610612754, 0},
+ {"utcTime", 1090519057, 0},
+ {"generalTime", 8388625, 0},
+ {"UniqueIdentifier", 1073741830, 0},
+ {"SubjectPublicKeyInfo", 1610612741, 0},
+ {"algorithm", 1073741826, "AlgorithmIdentifier"},
+ {"subjectPublicKey", 6, 0},
+ {"Extensions", 1612709899, 0},
+ {"MAX", 1074266122, "1"},
+ {0, 2, "Extension"},
+ {"Extension", 1610612741, 0},
+ {"extnID", 1073741836, 0},
+ {"critical", 1610645508, 0},
+ {0, 131081, 0},
+ {"extnValue", 7, 0},
+ {"CertificateList", 1610612741, 0},
+ {"tbsCertList", 1073741826, "TBSCertList"},
+ {"signatureAlgorithm", 1073741826, "AlgorithmIdentifier"},
+ {"signature", 6, 0},
+ {"TBSCertList", 1610612741, 0},
+ {"version", 1073758210, "Version"},
+ {"signature", 1073741826, "AlgorithmIdentifier"},
+ {"issuer", 1073741826, "Name"},
+ {"thisUpdate", 1073741826, "Time"},
+ {"nextUpdate", 1073758210, "Time"},
+ {"revokedCertificates", 1610629131, 0},
+ {0, 536870917, 0},
+ {"userCertificate", 1073741826, "CertificateSerialNumber"},
+ {"revocationDate", 1073741826, "Time"},
+ {"crlEntryExtensions", 16386, "Extensions"},
+ {"crlExtensions", 536895490, "Extensions"},
+ {0, 2056, "0"},
+ {"AlgorithmIdentifier", 1610612741, 0},
+ {"algorithm", 1073741836, 0},
+ {"parameters", 541081613, 0},
+ {"algorithm", 1, 0},
+ {"pkcs-1", 1879048204, 0},
+ {0, 1073741825, "pkcs"},
+ {0, 1, "1"},
+ {"rsaEncryption", 1879048204, 0},
+ {0, 1073741825, "pkcs-1"},
+ {0, 1, "1"},
+ {"md2WithRSAEncryption", 1879048204, 0},
+ {0, 1073741825, "pkcs-1"},
+ {0, 1, "2"},
+ {"md5WithRSAEncryption", 1879048204, 0},
+ {0, 1073741825, "pkcs-1"},
+ {0, 1, "4"},
+ {"sha1WithRSAEncryption", 1879048204, 0},
+ {0, 1073741825, "pkcs-1"},
+ {0, 1, "5"},
+ {"id-dsa-with-sha1", 1879048204, 0},
+ {"iso", 1073741825, "1"},
+ {"member-body", 1073741825, "2"},
+ {"us", 1073741825, "840"},
+ {"x9-57", 1073741825, "10040"},
+ {"x9algorithm", 1073741825, "4"},
+ {0, 1, "3"},
+ {"Dss-Sig-Value", 1610612741, 0},
+ {"r", 1073741827, 0},
+ {"s", 3, 0},
+ {"dhpublicnumber", 1879048204, 0},
+ {"iso", 1073741825, "1"},
+ {"member-body", 1073741825, "2"},
+ {"us", 1073741825, "840"},
+ {"ansi-x942", 1073741825, "10046"},
+ {"number-type", 1073741825, "2"},
+ {0, 1, "1"},
+ {"DomainParameters", 1610612741, 0},
+ {"p", 1073741827, 0},
+ {"g", 1073741827, 0},
+ {"q", 1073741827, 0},
+ {"j", 1073758211, 0},
+ {"validationParms", 16386, "ValidationParms"},
+ {"ValidationParms", 1610612741, 0},
+ {"seed", 1073741830, 0},
+ {"pgenCounter", 3, 0},
+ {"id-dsa", 1879048204, 0},
+ {"iso", 1073741825, "1"},
+ {"member-body", 1073741825, "2"},
+ {"us", 1073741825, "840"},
+ {"x9-57", 1073741825, "10040"},
+ {"x9algorithm", 1073741825, "4"},
+ {0, 1, "1"},
+ {"Dss-Parms", 1610612741, 0},
+ {"p", 1073741827, 0},
+ {"q", 1073741827, 0},
+ {"g", 3, 0},
+ {"ORAddress", 1610612741, 0},
+ {"built-in-standard-attributes", 1073741826, "BuiltInStandardAttributes"},
+ {"built-in-domain-defined-attributes", 1073758210,
+ "BuiltInDomainDefinedAttributes"},
+ {"extension-attributes", 16386, "ExtensionAttributes"},
+ {"BuiltInStandardAttributes", 1610612741, 0},
+ {"country-name", 1073758210, "CountryName"},
+ {"administration-domain-name", 1073758210, "AdministrationDomainName"},
+ {"network-address", 1610637314, "NetworkAddress"},
+ {0, 2056, "0"},
+ {"terminal-identifier", 1610637314, "TerminalIdentifier"},
+ {0, 2056, "1"},
+ {"private-domain-name", 1610637314, "PrivateDomainName"},
+ {0, 2056, "2"},
+ {"organization-name", 1610637314, "OrganizationName"},
+ {0, 2056, "3"},
+ {"numeric-user-identifier", 1610637314, "NumericUserIdentifier"},
+ {0, 2056, "4"},
+ {"personal-name", 1610637314, "PersonalName"},
+ {0, 2056, "5"},
+ {"organizational-unit-names", 536895490, "OrganizationalUnitNames"},
+ {0, 2056, "6"},
+ {"CountryName", 1610620946, 0},
+ {0, 1073746952, "1"},
+ {"x121-dcc-code", 1612709890, "NumericString"},
+ {0, 1048586, "ub-country-name-numeric-length"},
+ {"iso-3166-alpha2-code", 538968066, "PrintableString"},
+ {0, 1048586, "ub-country-name-alpha-length"},
+ {"AdministrationDomainName", 1610620946, 0},
+ {0, 1073744904, "2"},
+ {"numeric", 1612709890, "NumericString"},
+ {"ub-domain-name-length", 524298, "0"},
+ {"printable", 538968066, "PrintableString"},
+ {"ub-domain-name-length", 524298, "0"},
+ {"NetworkAddress", 1073741826, "X121Address"},
+ {"X121Address", 1612709890, "NumericString"},
+ {"ub-x121-address-length", 524298, "1"},
+ {"TerminalIdentifier", 1612709890, "PrintableString"},
+ {"ub-terminal-id-length", 524298, "1"},
+ {"PrivateDomainName", 1610612754, 0},
+ {"numeric", 1612709890, "NumericString"},
+ {"ub-domain-name-length", 524298, "1"},
+ {"printable", 538968066, "PrintableString"},
+ {"ub-domain-name-length", 524298, "1"},
+ {"OrganizationName", 1612709890, "PrintableString"},
+ {"ub-organization-name-length", 524298, "1"},
+ {"NumericUserIdentifier", 1612709890, "NumericString"},
+ {"ub-numeric-user-id-length", 524298, "1"},
+ {"PersonalName", 1610612750, 0},
+ {"surname", 1814044674, "PrintableString"},
+ {0, 1073745928, "0"},
+ {"ub-surname-length", 524298, "1"},
+ {"given-name", 1814061058, "PrintableString"},
+ {0, 1073745928, "1"},
+ {"ub-given-name-length", 524298, "1"},
+ {"initials", 1814061058, "PrintableString"},
+ {0, 1073745928, "2"},
+ {"ub-initials-length", 524298, "1"},
+ {"generation-qualifier", 740319234, "PrintableString"},
+ {0, 1073745928, "3"},
+ {"ub-generation-qualifier-length", 524298, "1"},
+ {"OrganizationalUnitNames", 1612709899, 0},
+ {"ub-organizational-units", 1074266122, "1"},
+ {0, 2, "OrganizationalUnitName"},
+ {"OrganizationalUnitName", 1612709890, "PrintableString"},
+ {"ub-organizational-unit-name-length", 524298, "1"},
+ {"BuiltInDomainDefinedAttributes", 1612709899, 0},
+ {"ub-domain-defined-attributes", 1074266122, "1"},
+ {0, 2, "BuiltInDomainDefinedAttribute"},
+ {"BuiltInDomainDefinedAttribute", 1610612741, 0},
+ {"type", 1612709890, "PrintableString"},
+ {"ub-domain-defined-attribute-type-length", 524298, "1"},
+ {"value", 538968066, "PrintableString"},
+ {"ub-domain-defined-attribute-value-length", 524298, "1"},
+ {"ExtensionAttributes", 1612709903, 0},
+ {"ub-extension-attributes", 1074266122, "1"},
+ {0, 2, "ExtensionAttribute"},
+ {"ExtensionAttribute", 1610612741, 0},
+ {"extension-attribute-type", 1611145219, 0},
+ {0, 1073743880, "0"},
+ {"0", 10, "ub-extension-attributes"},
+ {"extension-attribute-value", 541073421, 0},
+ {0, 1073743880, "1"},
+ {"extension-attribute-type", 1, 0},
+ {"common-name", 1342177283, "1"},
+ {"CommonName", 1612709890, "PrintableString"},
+ {"ub-common-name-length", 524298, "1"},
+ {"teletex-common-name", 1342177283, "2"},
+ {"TeletexCommonName", 1612709890, "TeletexString"},
+ {"ub-common-name-length", 524298, "1"},
+ {"teletex-organization-name", 1342177283, "3"},
+ {"TeletexOrganizationName", 1612709890, "TeletexString"},
+ {"ub-organization-name-length", 524298, "1"},
+ {"teletex-personal-name", 1342177283, "4"},
+ {"TeletexPersonalName", 1610612750, 0},
+ {"surname", 1814044674, "TeletexString"},
+ {0, 1073743880, "0"},
+ {"ub-surname-length", 524298, "1"},
+ {"given-name", 1814061058, "TeletexString"},
+ {0, 1073743880, "1"},
+ {"ub-given-name-length", 524298, "1"},
+ {"initials", 1814061058, "TeletexString"},
+ {0, 1073743880, "2"},
+ {"ub-initials-length", 524298, "1"},
+ {"generation-qualifier", 740319234, "TeletexString"},
+ {0, 1073743880, "3"},
+ {"ub-generation-qualifier-length", 524298, "1"},
+ {"teletex-organizational-unit-names", 1342177283, "5"},
+ {"TeletexOrganizationalUnitNames", 1612709899, 0},
+ {"ub-organizational-units", 1074266122, "1"},
+ {0, 2, "TeletexOrganizationalUnitName"},
+ {"TeletexOrganizationalUnitName", 1612709890, "TeletexString"},
+ {"ub-organizational-unit-name-length", 524298, "1"},
+ {"pds-name", 1342177283, "7"},
+ {"PDSName", 1612709890, "PrintableString"},
+ {"ub-pds-name-length", 524298, "1"},
+ {"physical-delivery-country-name", 1342177283, "8"},
+ {"PhysicalDeliveryCountryName", 1610612754, 0},
+ {"x121-dcc-code", 1612709890, "NumericString"},
+ {0, 1048586, "ub-country-name-numeric-length"},
+ {"iso-3166-alpha2-code", 538968066, "PrintableString"},
+ {0, 1048586, "ub-country-name-alpha-length"},
+ {"postal-code", 1342177283, "9"},
+ {"PostalCode", 1610612754, 0},
+ {"numeric-code", 1612709890, "NumericString"},
+ {"ub-postal-code-length", 524298, "1"},
+ {"printable-code", 538968066, "PrintableString"},
+ {"ub-postal-code-length", 524298, "1"},
+ {"physical-delivery-office-name", 1342177283, "10"},
+ {"PhysicalDeliveryOfficeName", 1073741826, "PDSParameter"},
+ {"physical-delivery-office-number", 1342177283, "11"},
+ {"PhysicalDeliveryOfficeNumber", 1073741826, "PDSParameter"},
+ {"extension-OR-address-components", 1342177283, "12"},
+ {"ExtensionORAddressComponents", 1073741826, "PDSParameter"},
+ {"physical-delivery-personal-name", 1342177283, "13"},
+ {"PhysicalDeliveryPersonalName", 1073741826, "PDSParameter"},
+ {"physical-delivery-organization-name", 1342177283, "14"},
+ {"PhysicalDeliveryOrganizationName", 1073741826, "PDSParameter"},
+ {"extension-physical-delivery-address-components", 1342177283, "15"},
+ {"ExtensionPhysicalDeliveryAddressComponents", 1073741826, "PDSParameter"},
+ {"unformatted-postal-address", 1342177283, "16"},
+ {"UnformattedPostalAddress", 1610612750, 0},
+ {"printable-address", 1814052875, 0},
+ {"ub-pds-physical-address-lines", 1074266122, "1"},
+ {0, 538968066, "PrintableString"},
+ {"ub-pds-parameter-length", 524298, "1"},
+ {"teletex-string", 740311042, "TeletexString"},
+ {"ub-unformatted-address-length", 524298, "1"},
+ {"street-address", 1342177283, "17"},
+ {"StreetAddress", 1073741826, "PDSParameter"},
+ {"post-office-box-address", 1342177283, "18"},
+ {"PostOfficeBoxAddress", 1073741826, "PDSParameter"},
+ {"poste-restante-address", 1342177283, "19"},
+ {"PosteRestanteAddress", 1073741826, "PDSParameter"},
+ {"unique-postal-name", 1342177283, "20"},
+ {"UniquePostalName", 1073741826, "PDSParameter"},
+ {"local-postal-attributes", 1342177283, "21"},
+ {"LocalPostalAttributes", 1073741826, "PDSParameter"},
+ {"PDSParameter", 1610612750, 0},
+ {"printable-string", 1814052866, "PrintableString"},
+ {"ub-pds-parameter-length", 524298, "1"},
+ {"teletex-string", 740311042, "TeletexString"},
+ {"ub-pds-parameter-length", 524298, "1"},
+ {"extended-network-address", 1342177283, "22"},
+ {"ExtendedNetworkAddress", 1610612754, 0},
+ {"e163-4-address", 1610612741, 0},
+ {"number", 1612718082, "NumericString"},
+ {0, 1073743880, "0"},
+ {"ub-e163-4-number-length", 524298, "1"},
+ {"sub-address", 538992642, "NumericString"},
+ {0, 1073743880, "1"},
+ {"ub-e163-4-sub-address-length", 524298, "1"},
+ {"psap-address", 536879106, "PresentationAddress"},
+ {0, 2056, "0"},
+ {"PresentationAddress", 1610612741, 0},
+ {"pSelector", 1610637319, 0},
+ {0, 2056, "0"},
+ {"sSelector", 1610637319, 0},
+ {0, 2056, "1"},
+ {"tSelector", 1610637319, 0},
+ {0, 2056, "2"},
+ {"nAddresses", 538976271, 0},
+ {0, 1073743880, "3"},
+ {"MAX", 1074266122, "1"},
+ {0, 7, 0},
+ {"terminal-type", 1342177283, "23"},
+ {"TerminalType", 1610874883, 0},
+ {"telex", 1073741825, "3"},
+ {"teletex", 1073741825, "4"},
+ {"g3-facsimile", 1073741825, "5"},
+ {"g4-facsimile", 1073741825, "6"},
+ {"ia5-terminal", 1073741825, "7"},
+ {"videotex", 1, "8"},
+ {"teletex-domain-defined-attributes", 1342177283, "6"},
+ {"TeletexDomainDefinedAttributes", 1612709899, 0},
+ {"ub-domain-defined-attributes", 1074266122, "1"},
+ {0, 2, "TeletexDomainDefinedAttribute"},
+ {"TeletexDomainDefinedAttribute", 1610612741, 0},
+ {"type", 1612709890, "TeletexString"},
+ {"ub-domain-defined-attribute-type-length", 524298, "1"},
+ {"value", 538968066, "TeletexString"},
+ {"ub-domain-defined-attribute-value-length", 524298, "1"},
+ {"ub-name", 1342177283, "32768"},
+ {"ub-common-name", 1342177283, "64"},
+ {"ub-locality-name", 1342177283, "128"},
+ {"ub-state-name", 1342177283, "128"},
+ {"ub-organization-name", 1342177283, "64"},
+ {"ub-organizational-unit-name", 1342177283, "64"},
+ {"ub-title", 1342177283, "64"},
+ {"ub-match", 1342177283, "128"},
+ {"ub-emailaddress-length", 1342177283, "128"},
+ {"ub-common-name-length", 1342177283, "64"},
+ {"ub-country-name-alpha-length", 1342177283, "2"},
+ {"ub-country-name-numeric-length", 1342177283, "3"},
+ {"ub-domain-defined-attributes", 1342177283, "4"},
+ {"ub-domain-defined-attribute-type-length", 1342177283, "8"},
+ {"ub-domain-defined-attribute-value-length", 1342177283, "128"},
+ {"ub-domain-name-length", 1342177283, "16"},
+ {"ub-extension-attributes", 1342177283, "256"},
+ {"ub-e163-4-number-length", 1342177283, "15"},
+ {"ub-e163-4-sub-address-length", 1342177283, "40"},
+ {"ub-generation-qualifier-length", 1342177283, "3"},
+ {"ub-given-name-length", 1342177283, "16"},
+ {"ub-initials-length", 1342177283, "5"},
+ {"ub-integer-options", 1342177283, "256"},
+ {"ub-numeric-user-id-length", 1342177283, "32"},
+ {"ub-organization-name-length", 1342177283, "64"},
+ {"ub-organizational-unit-name-length", 1342177283, "32"},
+ {"ub-organizational-units", 1342177283, "4"},
+ {"ub-pds-name-length", 1342177283, "16"},
+ {"ub-pds-parameter-length", 1342177283, "30"},
+ {"ub-pds-physical-address-lines", 1342177283, "6"},
+ {"ub-postal-code-length", 1342177283, "16"},
+ {"ub-surname-length", 1342177283, "40"},
+ {"ub-terminal-id-length", 1342177283, "24"},
+ {"ub-unformatted-address-length", 1342177283, "180"},
+ {"ub-x121-address-length", 1342177283, "16"},
+ {"pkcs-7-ContentInfo", 1610612741, 0},
+ {"contentType", 1073741826, "pkcs-7-ContentType"},
+ {"content", 541073421, 0},
+ {0, 1073743880, "0"},
+ {"contentType", 1, 0},
+ {"pkcs-7-DigestInfo", 1610612741, 0},
+ {"digestAlgorithm", 1073741826, "pkcs-7-DigestAlgorithmIdentifier"},
+ {"digest", 2, "pkcs-7-Digest"},
+ {"pkcs-7-Digest", 1073741831, 0},
+ {"pkcs-7-ContentType", 1073741836, 0},
+ {"pkcs-7-SignedData", 1610612741, 0},
+ {"version", 1073741826, "pkcs-7-CMSVersion"},
+ {"digestAlgorithms", 1073741826, "pkcs-7-DigestAlgorithmIdentifiers"},
+ {"encapContentInfo", 1073741826, "pkcs-7-EncapsulatedContentInfo"},
+ {"certificates", 1610637314, "pkcs-7-CertificateSet"},
+ {0, 4104, "0"},
+ {"crls", 1610637314, "pkcs-7-CertificateRevocationLists"},
+ {0, 4104, "1"},
+ {"signerInfos", 2, "pkcs-7-SignerInfos"},
+ {"pkcs-7-CMSVersion", 1610874883, 0},
+ {"v0", 1073741825, "0"},
+ {"v1", 1073741825, "1"},
+ {"v2", 1073741825, "2"},
+ {"v3", 1073741825, "3"},
+ {"v4", 1, "4"},
+ {"pkcs-7-DigestAlgorithmIdentifiers", 1610612751, 0},
+ {0, 2, "pkcs-7-DigestAlgorithmIdentifier"},
+ {"pkcs-7-DigestAlgorithmIdentifier", 1073741826, "AlgorithmIdentifier"},
+ {"pkcs-7-EncapsulatedContentInfo", 1610612741, 0},
+ {"eContentType", 1073741826, "pkcs-7-ContentType"},
+ {"eContent", 536895495, 0},
+ {0, 2056, "0"},
+ {"pkcs-7-CertificateRevocationLists", 1610612751, 0},
+ {0, 13, 0},
+ {"pkcs-7-CertificateChoices", 1610612754, 0},
+ {"certificate", 13, 0},
+ {"pkcs-7-CertificateSet", 1610612751, 0},
+ {0, 2, "pkcs-7-CertificateChoices"},
+ {"pkcs-7-SignerInfos", 1610612751, 0},
+ {0, 13, 0},
+ {"pkcs-10-CertificationRequestInfo", 1610612741, 0},
+ {"version", 1610874883, 0},
+ {"v1", 1, "0"},
+ {"subject", 1073741826, "Name"},
+ {"subjectPKInfo", 1073741826, "SubjectPublicKeyInfo"},
+ {"attributes", 536879106, "Attributes"},
+ {0, 4104, "0"},
+ {"Attributes", 1610612751, 0},
+ {0, 2, "Attribute"},
+ {"pkcs-10-CertificationRequest", 1610612741, 0},
+ {"certificationRequestInfo", 1073741826, "pkcs-10-CertificationRequestInfo"},
+ {"signatureAlgorithm", 1073741826, "AlgorithmIdentifier"},
+ {"signature", 6, 0},
+ {"pkcs-9-ub-challengePassword", 1342177283, "255"},
+ {"pkcs-9-certTypes", 1879048204, 0},
+ {0, 1073741825, "pkcs-9"},
+ {0, 1, "22"},
+ {"pkcs-9-crlTypes", 1879048204, 0},
+ {0, 1073741825, "pkcs-9"},
+ {0, 1, "23"},
+ {"pkcs-9-at-challengePassword", 1879048204, 0},
+ {0, 1073741825, "pkcs-9"},
+ {0, 1, "7"},
+ {"pkcs-9-challengePassword", 1610612754, 0},
+ {"printableString", 1612709890, "PrintableString"},
+ {"pkcs-9-ub-challengePassword", 524298, "1"},
+ {"utf8String", 538968066, "UTF8String"},
+ {"pkcs-9-ub-challengePassword", 524298, "1"},
+ {"pkcs-9-at-localKeyId", 1879048204, 0},
+ {0, 1073741825, "pkcs-9"},
+ {0, 1, "21"},
+ {"pkcs-9-localKeyId", 1073741831, 0},
+ {"pkcs-9-at-friendlyName", 1879048204, 0},
+ {0, 1073741825, "pkcs-9"},
+ {0, 1, "20"},
+ {"pkcs-9-friendlyName", 1612709890, "BMPString"},
+ {"255", 524298, "1"},
+ {"pkcs-8-PrivateKeyInfo", 1610612741, 0},
+ {"version", 1073741826, "pkcs-8-Version"},
+ {"privateKeyAlgorithm", 1073741826, "AlgorithmIdentifier"},
+ {"privateKey", 1073741826, "pkcs-8-PrivateKey"},
+ {"attributes", 536895490, "Attributes"},
+ {0, 4104, "0"},
+ {"pkcs-8-Version", 1610874883, 0},
+ {"v1", 1, "0"},
+ {"pkcs-8-PrivateKey", 1073741831, 0},
+ {"pkcs-8-Attributes", 1610612751, 0},
+ {0, 2, "Attribute"},
+ {"pkcs-8-EncryptedPrivateKeyInfo", 1610612741, 0},
+ {"encryptionAlgorithm", 1073741826, "AlgorithmIdentifier"},
+ {"encryptedData", 2, "pkcs-8-EncryptedData"},
+ {"pkcs-8-EncryptedData", 1073741831, 0},
+ {"pkcs-5", 1879048204, 0},
+ {0, 1073741825, "pkcs"},
+ {0, 1, "5"},
+ {"pkcs-5-encryptionAlgorithm", 1879048204, 0},
+ {"iso", 1073741825, "1"},
+ {"member-body", 1073741825, "2"},
+ {"us", 1073741825, "840"},
+ {"rsadsi", 1073741825, "113549"},
+ {0, 1, "3"},
+ {"pkcs-5-des-EDE3-CBC", 1879048204, 0},
+ {0, 1073741825, "pkcs-5-encryptionAlgorithm"},
+ {0, 1, "7"},
+ {"pkcs-5-des-EDE3-CBC-params", 1612709895, 0},
+ {0, 1048586, "8"},
+ {"pkcs-5-id-PBES2", 1879048204, 0},
+ {0, 1073741825, "pkcs-5"},
+ {0, 1, "13"},
+ {"pkcs-5-PBES2-params", 1610612741, 0},
+ {"keyDerivationFunc", 1073741826, "AlgorithmIdentifier"},
+ {"encryptionScheme", 2, "AlgorithmIdentifier"},
+ {"pkcs-5-id-PBKDF2", 1879048204, 0},
+ {0, 1073741825, "pkcs-5"},
+ {0, 1, "12"},
+ {"pkcs-5-PBKDF2-params", 1610612741, 0},
+ {"salt", 1610612754, 0},
+ {"specified", 1073741831, 0},
+ {"otherSource", 2, "AlgorithmIdentifier"},
+ {"iterationCount", 1611137027, 0},
+ {"1", 10, "MAX"},
+ {"keyLength", 1611153411, 0},
+ {"1", 10, "MAX"},
+ {"prf", 16386, "AlgorithmIdentifier"},
+ {"pkcs-12", 1879048204, 0},
+ {0, 1073741825, "pkcs"},
+ {0, 1, "12"},
+ {"pkcs-12-PFX", 1610612741, 0},
+ {"version", 1610874883, 0},
+ {"v3", 1, "3"},
+ {"authSafe", 1073741826, "pkcs-7-ContentInfo"},
+ {"macData", 16386, "pkcs-12-MacData"},
+ {"pkcs-12-PbeParams", 1610612741, 0},
+ {"salt", 1073741831, 0},
+ {"iterations", 3, 0},
+ {"pkcs-12-MacData", 1610612741, 0},
+ {"mac", 1073741826, "pkcs-7-DigestInfo"},
+ {"macSalt", 1073741831, 0},
+ {"iterations", 536903683, 0},
+ {0, 9, "1"},
+ {"pkcs-12-AuthenticatedSafe", 1610612747, 0},
+ {0, 2, "pkcs-7-ContentInfo"},
+ {"pkcs-12-SafeContents", 1610612747, 0},
+ {0, 2, "pkcs-12-SafeBag"},
+ {"pkcs-12-SafeBag", 1610612741, 0},
+ {"bagId", 1073741836, 0},
+ {"bagValue", 1614815245, 0},
+ {0, 1073743880, "0"},
+ {"badId", 1, 0},
+ {"bagAttributes", 536887311, 0},
+ {0, 2, "pkcs-12-PKCS12Attribute"},
+ {"pkcs-12-bagtypes", 1879048204, 0},
+ {0, 1073741825, "pkcs-12"},
+ {0, 1073741825, "10"},
+ {0, 1, "1"},
+ {"pkcs-12-keyBag", 1879048204, 0},
+ {0, 1073741825, "pkcs-12-bagtypes"},
+ {0, 1, "1"},
+ {"pkcs-12-pkcs8ShroudedKeyBag", 1879048204, 0},
+ {0, 1073741825, "pkcs-12-bagtypes"},
+ {0, 1, "2"},
+ {"pkcs-12-certBag", 1879048204, 0},
+ {0, 1073741825, "pkcs-12-bagtypes"},
+ {0, 1, "3"},
+ {"pkcs-12-crlBag", 1879048204, 0},
+ {0, 1073741825, "pkcs-12-bagtypes"},
+ {0, 1, "4"},
+ {"pkcs-12-KeyBag", 1073741826, "pkcs-8-PrivateKeyInfo"},
+ {"pkcs-12-PKCS8ShroudedKeyBag", 1073741826, "pkcs-8-EncryptedPrivateKeyInfo"},
+ {"pkcs-12-CertBag", 1610612741, 0},
+ {"certId", 1073741836, 0},
+ {"certValue", 541073421, 0},
+ {0, 1073743880, "0"},
+ {"certId", 1, 0},
+ {"pkcs-12-CRLBag", 1610612741, 0},
+ {"crlId", 1073741836, 0},
+ {"crlValue", 541073421, 0},
+ {0, 1073743880, "0"},
+ {"crlId", 1, 0},
+ {"pkcs-12-PKCS12Attribute", 1073741826, "Attribute"},
+ {"pkcs-7-data", 1879048204, 0},
+ {"iso", 1073741825, "1"},
+ {"member-body", 1073741825, "2"},
+ {"us", 1073741825, "840"},
+ {"rsadsi", 1073741825, "113549"},
+ {"pkcs", 1073741825, "1"},
+ {"pkcs7", 1073741825, "7"},
+ {0, 1, "1"},
+ {"pkcs-7-encryptedData", 1879048204, 0},
+ {"iso", 1073741825, "1"},
+ {"member-body", 1073741825, "2"},
+ {"us", 1073741825, "840"},
+ {"rsadsi", 1073741825, "113549"},
+ {"pkcs", 1073741825, "1"},
+ {"pkcs7", 1073741825, "7"},
+ {0, 1, "6"},
+ {"pkcs-7-Data", 1073741831, 0},
+ {"pkcs-7-EncryptedData", 1610612741, 0},
+ {"version", 1073741826, "pkcs-7-CMSVersion"},
+ {"encryptedContentInfo", 1073741826, "pkcs-7-EncryptedContentInfo"},
+ {"unprotectedAttrs", 536895490, "pkcs-7-UnprotectedAttributes"},
+ {0, 4104, "1"},
+ {"pkcs-7-EncryptedContentInfo", 1610612741, 0},
+ {"contentType", 1073741826, "pkcs-7-ContentType"},
+ {"contentEncryptionAlgorithm", 1073741826,
+ "pkcs-7-ContentEncryptionAlgorithmIdentifier"},
+ {"encryptedContent", 536895490, "pkcs-7-EncryptedContent"},
+ {0, 4104, "0"},
+ {"pkcs-7-ContentEncryptionAlgorithmIdentifier", 1073741826,
+ "AlgorithmIdentifier"},
+ {"pkcs-7-EncryptedContent", 1073741831, 0},
+ {"pkcs-7-UnprotectedAttributes", 1612709903, 0},
+ {"MAX", 1074266122, "1"},
+ {0, 2, "Attribute"},
+ {"id-at-ldap-DC", 1880096780, "AttributeType"},
+ {0, 1073741825, "0"},
+ {0, 1073741825, "9"},
+ {0, 1073741825, "2342"},
+ {0, 1073741825, "19200300"},
+ {0, 1073741825, "100"},
+ {0, 1073741825, "1"},
+ {0, 1, "25"},
+ {"ldap-DC", 1073741826, "IA5String"},
+ {"id-at-ldap-UID", 1880096780, "AttributeType"},
+ {0, 1073741825, "0"},
+ {0, 1073741825, "9"},
+ {0, 1073741825, "2342"},
+ {0, 1073741825, "19200300"},
+ {0, 1073741825, "100"},
+ {0, 1073741825, "1"},
+ {0, 1, "1"},
+ {"ldap-UID", 1073741826, "DirectoryString"},
+ {"id-pda", 1879048204, 0},
+ {0, 1073741825, "id-pkix"},
+ {0, 1, "9"},
+ {"id-pda-dateOfBirth", 1880096780, "AttributeType"},
+ {0, 1073741825, "id-pda"},
+ {0, 1, "1"},
+ {"DateOfBirth", 1082130449, 0},
+ {"id-pda-placeOfBirth", 1880096780, "AttributeType"},
+ {0, 1073741825, "id-pda"},
+ {0, 1, "2"},
+ {"PlaceOfBirth", 1073741826, "DirectoryString"},
+ {"id-pda-gender", 1880096780, "AttributeType"},
+ {0, 1073741825, "id-pda"},
+ {0, 1, "3"},
+ {"Gender", 1612709890, "PrintableString"},
+ {0, 1048586, "1"},
+ {"id-pda-countryOfCitizenship", 1880096780, "AttributeType"},
+ {0, 1073741825, "id-pda"},
+ {0, 1, "4"},
+ {"CountryOfCitizenship", 1612709890, "PrintableString"},
+ {0, 1048586, "2"},
+ {"id-pda-countryOfResidence", 1880096780, "AttributeType"},
+ {0, 1073741825, "id-pda"},
+ {0, 1, "5"},
+ {"CountryOfResidence", 538968066, "PrintableString"},
+ {0, 1048586, "2"},
+ {0, 0, 0}
+};
diff --git a/tests/qapi-schema/alternate-clash.err b/tests/qapi-schema/alternate-clash.err
index 51bea3e27..a475ab634 100644
--- a/tests/qapi-schema/alternate-clash.err
+++ b/tests/qapi-schema/alternate-clash.err
@@ -1 +1 @@
-tests/qapi-schema/alternate-clash.json:2: Alternate 'Alt1' member 'ONE' clashes with 'one'
+tests/qapi-schema/alternate-clash.json:7: Alternate 'Alt1' member 'a_b' clashes with 'a-b'
diff --git a/tests/qapi-schema/alternate-clash.json b/tests/qapi-schema/alternate-clash.json
index 39479353b..6d73bc527 100644
--- a/tests/qapi-schema/alternate-clash.json
+++ b/tests/qapi-schema/alternate-clash.json
@@ -1,3 +1,8 @@
-# we detect C enum collisions in an alternate
+# Alternate branch name collision
+# Reject an alternate that would result in a collision in generated C
+# names (this would try to generate two enum values 'ALT1_KIND_A_B').
+# TODO: In the future, if alternates are simplified to not generate
+# the implicit Alt1Kind enum, we would still have a collision with the
+# resulting C union trying to have two members named 'a_b'.
{ 'alternate': 'Alt1',
- 'data': { 'one': 'str', 'ONE': 'int' } }
+ 'data': { 'a-b': 'str', 'a_b': 'int' } }
diff --git a/tests/qapi-schema/alternate-good.err b/tests/qapi-schema/alternate-empty.err
index e69de29bb..e69de29bb 100644
--- a/tests/qapi-schema/alternate-good.err
+++ b/tests/qapi-schema/alternate-empty.err
diff --git a/tests/qapi-schema/alternate-good.exit b/tests/qapi-schema/alternate-empty.exit
index 573541ac9..573541ac9 100644
--- a/tests/qapi-schema/alternate-good.exit
+++ b/tests/qapi-schema/alternate-empty.exit
diff --git a/tests/qapi-schema/alternate-empty.json b/tests/qapi-schema/alternate-empty.json
new file mode 100644
index 000000000..db3820f84
--- /dev/null
+++ b/tests/qapi-schema/alternate-empty.json
@@ -0,0 +1,2 @@
+# FIXME - alternates should list at least two types to be useful
+{ 'alternate': 'Alt', 'data': { 'i': 'int' } }
diff --git a/tests/qapi-schema/alternate-empty.out b/tests/qapi-schema/alternate-empty.out
new file mode 100644
index 000000000..0f153b6f6
--- /dev/null
+++ b/tests/qapi-schema/alternate-empty.out
@@ -0,0 +1,4 @@
+object :empty
+alternate Alt
+ case i: int
+enum AltKind ['i']
diff --git a/tests/qapi-schema/alternate-good.json b/tests/qapi-schema/alternate-good.json
deleted file mode 100644
index 33717704c..000000000
--- a/tests/qapi-schema/alternate-good.json
+++ /dev/null
@@ -1,9 +0,0 @@
-# Working example of alternate
-{ 'struct': 'Data',
- 'data': { '*number': 'int', '*name': 'str' } }
-{ 'enum': 'Enum',
- 'data': [ 'hello', 'world' ] }
-{ 'alternate': 'Alt',
- 'data': { 'value': 'int',
- 'string': 'Enum',
- 'struct': 'Data' } }
diff --git a/tests/qapi-schema/alternate-good.out b/tests/qapi-schema/alternate-good.out
deleted file mode 100644
index 99848eefb..000000000
--- a/tests/qapi-schema/alternate-good.out
+++ /dev/null
@@ -1,6 +0,0 @@
-[OrderedDict([('struct', 'Data'), ('data', OrderedDict([('*number', 'int'), ('*name', 'str')]))]),
- OrderedDict([('enum', 'Enum'), ('data', ['hello', 'world'])]),
- OrderedDict([('alternate', 'Alt'), ('data', OrderedDict([('value', 'int'), ('string', 'Enum'), ('struct', 'Data')]))])]
-[{'enum_name': 'Enum', 'enum_values': ['hello', 'world']},
- {'enum_name': 'AltKind', 'enum_values': None}]
-[OrderedDict([('struct', 'Data'), ('data', OrderedDict([('*number', 'int'), ('*name', 'str')]))])]
diff --git a/tests/qapi-schema/alternate-nested.json b/tests/qapi-schema/alternate-nested.json
index c4233b9f3..8e2218649 100644
--- a/tests/qapi-schema/alternate-nested.json
+++ b/tests/qapi-schema/alternate-nested.json
@@ -2,4 +2,4 @@
{ 'alternate': 'Alt1',
'data': { 'name': 'str', 'value': 'int' } }
{ 'alternate': 'Alt2',
- 'data': { 'nested': 'Alt1' } }
+ 'data': { 'nested': 'Alt1', 'b': 'bool' } }
diff --git a/tests/qapi-schema/alternate-unknown.json b/tests/qapi-schema/alternate-unknown.json
index ad5c10302..08c80dced 100644
--- a/tests/qapi-schema/alternate-unknown.json
+++ b/tests/qapi-schema/alternate-unknown.json
@@ -1,3 +1,3 @@
# we reject an alternate with unknown type in branch
{ 'alternate': 'Alt',
- 'data': { 'unknown': 'MissingType' } }
+ 'data': { 'unknown': 'MissingType', 'i': 'int' } }
diff --git a/tests/qapi-schema/args-alternate.err b/tests/qapi-schema/args-alternate.err
new file mode 100644
index 000000000..3086eae56
--- /dev/null
+++ b/tests/qapi-schema/args-alternate.err
@@ -0,0 +1 @@
+tests/qapi-schema/args-alternate.json:3: 'data' for command 'oops' cannot use alternate type 'Alt'
diff --git a/tests/qapi-schema/data-array-empty.exit b/tests/qapi-schema/args-alternate.exit
index d00491fd7..d00491fd7 100644
--- a/tests/qapi-schema/data-array-empty.exit
+++ b/tests/qapi-schema/args-alternate.exit
diff --git a/tests/qapi-schema/args-alternate.json b/tests/qapi-schema/args-alternate.json
new file mode 100644
index 000000000..69e94d481
--- /dev/null
+++ b/tests/qapi-schema/args-alternate.json
@@ -0,0 +1,3 @@
+# we do not allow alternate arguments
+{ 'alternate': 'Alt', 'data': { 'case1': 'int', 'case2': 'str' } }
+{ 'command': 'oops', 'data': 'Alt' }
diff --git a/tests/qapi-schema/data-array-empty.out b/tests/qapi-schema/args-alternate.out
index e69de29bb..e69de29bb 100644
--- a/tests/qapi-schema/data-array-empty.out
+++ b/tests/qapi-schema/args-alternate.out
diff --git a/tests/qapi-schema/args-any.err b/tests/qapi-schema/args-any.err
new file mode 100644
index 000000000..bf9b5e073
--- /dev/null
+++ b/tests/qapi-schema/args-any.err
@@ -0,0 +1 @@
+tests/qapi-schema/args-any.json:2: 'data' for command 'oops' cannot use built-in type 'any'
diff --git a/tests/qapi-schema/data-array-unknown.exit b/tests/qapi-schema/args-any.exit
index d00491fd7..d00491fd7 100644
--- a/tests/qapi-schema/data-array-unknown.exit
+++ b/tests/qapi-schema/args-any.exit
diff --git a/tests/qapi-schema/args-any.json b/tests/qapi-schema/args-any.json
new file mode 100644
index 000000000..58fe5e470
--- /dev/null
+++ b/tests/qapi-schema/args-any.json
@@ -0,0 +1,2 @@
+# we do not allow an 'any' argument
+{ 'command': 'oops', 'data': 'any' }
diff --git a/tests/qapi-schema/data-array-unknown.out b/tests/qapi-schema/args-any.out
index e69de29bb..e69de29bb 100644
--- a/tests/qapi-schema/data-array-unknown.out
+++ b/tests/qapi-schema/args-any.out
diff --git a/tests/qapi-schema/data-array-empty.err b/tests/qapi-schema/args-array-empty.err
index f713f1489..cb7ed33b3 100644
--- a/tests/qapi-schema/data-array-empty.err
+++ b/tests/qapi-schema/args-array-empty.err
@@ -1 +1 @@
-tests/qapi-schema/data-array-empty.json:2: Member 'empty' of 'data' for command 'oops': array type must contain single type name
+tests/qapi-schema/args-array-empty.json:2: Member 'empty' of 'data' for command 'oops': array type must contain single type name
diff --git a/tests/qapi-schema/data-int.exit b/tests/qapi-schema/args-array-empty.exit
index d00491fd7..d00491fd7 100644
--- a/tests/qapi-schema/data-int.exit
+++ b/tests/qapi-schema/args-array-empty.exit
diff --git a/tests/qapi-schema/data-array-empty.json b/tests/qapi-schema/args-array-empty.json
index 652dcfb24..652dcfb24 100644
--- a/tests/qapi-schema/data-array-empty.json
+++ b/tests/qapi-schema/args-array-empty.json
diff --git a/tests/qapi-schema/data-int.out b/tests/qapi-schema/args-array-empty.out
index e69de29bb..e69de29bb 100644
--- a/tests/qapi-schema/data-int.out
+++ b/tests/qapi-schema/args-array-empty.out
diff --git a/tests/qapi-schema/args-array-unknown.err b/tests/qapi-schema/args-array-unknown.err
new file mode 100644
index 000000000..cd7a0f98d
--- /dev/null
+++ b/tests/qapi-schema/args-array-unknown.err
@@ -0,0 +1 @@
+tests/qapi-schema/args-array-unknown.json:2: Member 'array' of 'data' for command 'oops' uses unknown type 'NoSuchType'
diff --git a/tests/qapi-schema/data-member-array-bad.exit b/tests/qapi-schema/args-array-unknown.exit
index d00491fd7..d00491fd7 100644
--- a/tests/qapi-schema/data-member-array-bad.exit
+++ b/tests/qapi-schema/args-array-unknown.exit
diff --git a/tests/qapi-schema/data-array-unknown.json b/tests/qapi-schema/args-array-unknown.json
index 6f3e88331..6f3e88331 100644
--- a/tests/qapi-schema/data-array-unknown.json
+++ b/tests/qapi-schema/args-array-unknown.json
diff --git a/tests/qapi-schema/data-member-array-bad.out b/tests/qapi-schema/args-array-unknown.out
index e69de29bb..e69de29bb 100644
--- a/tests/qapi-schema/data-member-array-bad.out
+++ b/tests/qapi-schema/args-array-unknown.out
diff --git a/tests/qapi-schema/args-int.err b/tests/qapi-schema/args-int.err
new file mode 100644
index 000000000..dc1d2504f
--- /dev/null
+++ b/tests/qapi-schema/args-int.err
@@ -0,0 +1 @@
+tests/qapi-schema/args-int.json:2: 'data' for command 'oops' cannot use built-in type 'int'
diff --git a/tests/qapi-schema/data-member-unknown.exit b/tests/qapi-schema/args-int.exit
index d00491fd7..d00491fd7 100644
--- a/tests/qapi-schema/data-member-unknown.exit
+++ b/tests/qapi-schema/args-int.exit
diff --git a/tests/qapi-schema/data-int.json b/tests/qapi-schema/args-int.json
index a334d92e8..a334d92e8 100644
--- a/tests/qapi-schema/data-int.json
+++ b/tests/qapi-schema/args-int.json
diff --git a/tests/qapi-schema/data-member-array.err b/tests/qapi-schema/args-int.out
index e69de29bb..e69de29bb 100644
--- a/tests/qapi-schema/data-member-array.err
+++ b/tests/qapi-schema/args-int.out
diff --git a/tests/qapi-schema/args-invalid.err b/tests/qapi-schema/args-invalid.err
new file mode 100644
index 000000000..fe1e94975
--- /dev/null
+++ b/tests/qapi-schema/args-invalid.err
@@ -0,0 +1 @@
+tests/qapi-schema/args-invalid.json:1: 'data' for command 'foo' should be a dictionary or type name
diff --git a/tests/qapi-schema/data-unknown.exit b/tests/qapi-schema/args-invalid.exit
index d00491fd7..d00491fd7 100644
--- a/tests/qapi-schema/data-unknown.exit
+++ b/tests/qapi-schema/args-invalid.exit
diff --git a/tests/qapi-schema/args-invalid.json b/tests/qapi-schema/args-invalid.json
new file mode 100644
index 000000000..db0981341
--- /dev/null
+++ b/tests/qapi-schema/args-invalid.json
@@ -0,0 +1,2 @@
+{ 'command': 'foo',
+ 'data': false }
diff --git a/tests/qapi-schema/data-member-unknown.out b/tests/qapi-schema/args-invalid.out
index e69de29bb..e69de29bb 100644
--- a/tests/qapi-schema/data-member-unknown.out
+++ b/tests/qapi-schema/args-invalid.out
diff --git a/tests/qapi-schema/data-member-array-bad.err b/tests/qapi-schema/args-member-array-bad.err
index 2c072d598..881b4d954 100644
--- a/tests/qapi-schema/data-member-array-bad.err
+++ b/tests/qapi-schema/args-member-array-bad.err
@@ -1 +1 @@
-tests/qapi-schema/data-member-array-bad.json:2: Member 'member' of 'data' for command 'oops': array type must contain single type name
+tests/qapi-schema/args-member-array-bad.json:2: Member 'member' of 'data' for command 'oops': array type must contain single type name
diff --git a/tests/qapi-schema/enum-union-clash.exit b/tests/qapi-schema/args-member-array-bad.exit
index d00491fd7..d00491fd7 100644
--- a/tests/qapi-schema/enum-union-clash.exit
+++ b/tests/qapi-schema/args-member-array-bad.exit
diff --git a/tests/qapi-schema/data-member-array-bad.json b/tests/qapi-schema/args-member-array-bad.json
index b2ff144ec..b2ff144ec 100644
--- a/tests/qapi-schema/data-member-array-bad.json
+++ b/tests/qapi-schema/args-member-array-bad.json
diff --git a/tests/qapi-schema/data-unknown.out b/tests/qapi-schema/args-member-array-bad.out
index e69de29bb..e69de29bb 100644
--- a/tests/qapi-schema/data-unknown.out
+++ b/tests/qapi-schema/args-member-array-bad.out
diff --git a/tests/qapi-schema/args-member-unknown.err b/tests/qapi-schema/args-member-unknown.err
new file mode 100644
index 000000000..f6f82828c
--- /dev/null
+++ b/tests/qapi-schema/args-member-unknown.err
@@ -0,0 +1 @@
+tests/qapi-schema/args-member-unknown.json:2: Member 'member' of 'data' for command 'oops' uses unknown type 'NoSuchType'
diff --git a/tests/qapi-schema/flat-union-base-star.exit b/tests/qapi-schema/args-member-unknown.exit
index d00491fd7..d00491fd7 100644
--- a/tests/qapi-schema/flat-union-base-star.exit
+++ b/tests/qapi-schema/args-member-unknown.exit
diff --git a/tests/qapi-schema/data-member-unknown.json b/tests/qapi-schema/args-member-unknown.json
index 342a41ec9..342a41ec9 100644
--- a/tests/qapi-schema/data-member-unknown.json
+++ b/tests/qapi-schema/args-member-unknown.json
diff --git a/tests/qapi-schema/enum-empty.err b/tests/qapi-schema/args-member-unknown.out
index e69de29bb..e69de29bb 100644
--- a/tests/qapi-schema/enum-empty.err
+++ b/tests/qapi-schema/args-member-unknown.out
diff --git a/tests/qapi-schema/enum-union-clash.out b/tests/qapi-schema/args-name-clash.err
index e69de29bb..e69de29bb 100644
--- a/tests/qapi-schema/enum-union-clash.out
+++ b/tests/qapi-schema/args-name-clash.err
diff --git a/tests/qapi-schema/data-member-array.exit b/tests/qapi-schema/args-name-clash.exit
index 573541ac9..573541ac9 100644
--- a/tests/qapi-schema/data-member-array.exit
+++ b/tests/qapi-schema/args-name-clash.exit
diff --git a/tests/qapi-schema/args-name-clash.json b/tests/qapi-schema/args-name-clash.json
new file mode 100644
index 000000000..9e8f88916
--- /dev/null
+++ b/tests/qapi-schema/args-name-clash.json
@@ -0,0 +1,5 @@
+# C member name collision
+# FIXME - This parses, but fails to compile, because the C struct is given
+# two 'a_b' members. Either reject this at parse time, or munge the C names
+# to avoid the collision.
+{ 'command': 'oops', 'data': { 'a-b': 'str', 'a_b': 'str' } }
diff --git a/tests/qapi-schema/args-name-clash.out b/tests/qapi-schema/args-name-clash.out
new file mode 100644
index 000000000..9b2f6e4d5
--- /dev/null
+++ b/tests/qapi-schema/args-name-clash.out
@@ -0,0 +1,6 @@
+object :empty
+object :obj-oops-arg
+ member a-b: str optional=False
+ member a_b: str optional=False
+command oops :obj-oops-arg -> None
+ gen=True success_response=True
diff --git a/tests/qapi-schema/args-union.err b/tests/qapi-schema/args-union.err
new file mode 100644
index 000000000..1d693d74d
--- /dev/null
+++ b/tests/qapi-schema/args-union.err
@@ -0,0 +1 @@
+tests/qapi-schema/args-union.json:4: 'data' for command 'oops' cannot use union type 'Uni'
diff --git a/tests/qapi-schema/flat-union-branch-clash.exit b/tests/qapi-schema/args-union.exit
index d00491fd7..d00491fd7 100644
--- a/tests/qapi-schema/flat-union-branch-clash.exit
+++ b/tests/qapi-schema/args-union.exit
diff --git a/tests/qapi-schema/args-union.json b/tests/qapi-schema/args-union.json
new file mode 100644
index 000000000..7bdcbb7f0
--- /dev/null
+++ b/tests/qapi-schema/args-union.json
@@ -0,0 +1,4 @@
+# we do not allow union arguments
+# TODO should we support this?
+{ 'union': 'Uni', 'data': { 'case1': 'int', 'case2': 'str' } }
+{ 'command': 'oops', 'data': 'Uni' }
diff --git a/tests/qapi-schema/flat-union-base-star.out b/tests/qapi-schema/args-union.out
index e69de29bb..e69de29bb 100644
--- a/tests/qapi-schema/flat-union-base-star.out
+++ b/tests/qapi-schema/args-union.out
diff --git a/tests/qapi-schema/args-unknown.err b/tests/qapi-schema/args-unknown.err
new file mode 100644
index 000000000..4d91ec869
--- /dev/null
+++ b/tests/qapi-schema/args-unknown.err
@@ -0,0 +1 @@
+tests/qapi-schema/args-unknown.json:2: 'data' for command 'oops' uses unknown type 'NoSuchType'
diff --git a/tests/qapi-schema/nested-struct-returns.exit b/tests/qapi-schema/args-unknown.exit
index d00491fd7..d00491fd7 100644
--- a/tests/qapi-schema/nested-struct-returns.exit
+++ b/tests/qapi-schema/args-unknown.exit
diff --git a/tests/qapi-schema/data-unknown.json b/tests/qapi-schema/args-unknown.json
index 32aba43b3..32aba43b3 100644
--- a/tests/qapi-schema/data-unknown.json
+++ b/tests/qapi-schema/args-unknown.json
diff --git a/tests/qapi-schema/flat-union-branch-clash.out b/tests/qapi-schema/args-unknown.out
index e69de29bb..e69de29bb 100644
--- a/tests/qapi-schema/flat-union-branch-clash.out
+++ b/tests/qapi-schema/args-unknown.out
diff --git a/tests/qapi-schema/command-int.json b/tests/qapi-schema/command-int.json
index c90d408ab..9a62554fc 100644
--- a/tests/qapi-schema/command-int.json
+++ b/tests/qapi-schema/command-int.json
@@ -1,3 +1,2 @@
# we reject collisions between commands and types
-{ 'command': 'int', 'data': { 'character': 'str' },
- 'returns': { 'value': 'int' } }
+{ 'command': 'int', 'data': { 'character': 'str' } }
diff --git a/tests/qapi-schema/comments.out b/tests/qapi-schema/comments.out
index 4ce3dcf12..9e2c656fa 100644
--- a/tests/qapi-schema/comments.out
+++ b/tests/qapi-schema/comments.out
@@ -1,3 +1,2 @@
-[OrderedDict([('enum', 'Status'), ('data', ['good', 'bad', 'ugly'])])]
-[{'enum_name': 'Status', 'enum_values': ['good', 'bad', 'ugly']}]
-[]
+object :empty
+enum Status ['good', 'bad', 'ugly']
diff --git a/tests/qapi-schema/data-array-unknown.err b/tests/qapi-schema/data-array-unknown.err
deleted file mode 100644
index 8b731bbcc..000000000
--- a/tests/qapi-schema/data-array-unknown.err
+++ /dev/null
@@ -1 +0,0 @@
-tests/qapi-schema/data-array-unknown.json:2: Member 'array' of 'data' for command 'oops' uses unknown type 'array of NoSuchType'
diff --git a/tests/qapi-schema/data-int.err b/tests/qapi-schema/data-int.err
deleted file mode 100644
index 1a9b077c0..000000000
--- a/tests/qapi-schema/data-int.err
+++ /dev/null
@@ -1 +0,0 @@
-tests/qapi-schema/data-int.json:2: 'data' for command 'oops' cannot use built-in type 'int'
diff --git a/tests/qapi-schema/data-member-array.json b/tests/qapi-schema/data-member-array.json
deleted file mode 100644
index e6f7f5da1..000000000
--- a/tests/qapi-schema/data-member-array.json
+++ /dev/null
@@ -1,4 +0,0 @@
-# valid array members
-{ 'enum': 'abc', 'data': [ 'a', 'b', 'c' ] }
-{ 'struct': 'def', 'data': { 'array': [ 'abc' ] } }
-{ 'command': 'okay', 'data': { 'member1': [ 'int' ], 'member2': [ 'def' ] } }
diff --git a/tests/qapi-schema/data-member-array.out b/tests/qapi-schema/data-member-array.out
deleted file mode 100644
index c39fa2548..000000000
--- a/tests/qapi-schema/data-member-array.out
+++ /dev/null
@@ -1,5 +0,0 @@
-[OrderedDict([('enum', 'abc'), ('data', ['a', 'b', 'c'])]),
- OrderedDict([('struct', 'def'), ('data', OrderedDict([('array', ['abc'])]))]),
- OrderedDict([('command', 'okay'), ('data', OrderedDict([('member1', ['int']), ('member2', ['def'])]))])]
-[{'enum_name': 'abc', 'enum_values': ['a', 'b', 'c']}]
-[OrderedDict([('struct', 'def'), ('data', OrderedDict([('array', ['abc'])]))])]
diff --git a/tests/qapi-schema/data-member-unknown.err b/tests/qapi-schema/data-member-unknown.err
deleted file mode 100644
index ab905db80..000000000
--- a/tests/qapi-schema/data-member-unknown.err
+++ /dev/null
@@ -1 +0,0 @@
-tests/qapi-schema/data-member-unknown.json:2: Member 'member' of 'data' for command 'oops' uses unknown type 'NoSuchType'
diff --git a/tests/qapi-schema/data-unknown.err b/tests/qapi-schema/data-unknown.err
deleted file mode 100644
index 5b07277a9..000000000
--- a/tests/qapi-schema/data-unknown.err
+++ /dev/null
@@ -1 +0,0 @@
-tests/qapi-schema/data-unknown.json:2: 'data' for command 'oops' uses unknown type 'NoSuchType'
diff --git a/tests/qapi-schema/duplicate-key.err b/tests/qapi-schema/duplicate-key.err
index 768b276f8..6d02f8353 100644
--- a/tests/qapi-schema/duplicate-key.err
+++ b/tests/qapi-schema/duplicate-key.err
@@ -1 +1 @@
-tests/qapi-schema/duplicate-key.json:2:10: Duplicate key "key"
+tests/qapi-schema/duplicate-key.json:3:10: Duplicate key "key"
diff --git a/tests/qapi-schema/duplicate-key.json b/tests/qapi-schema/duplicate-key.json
index 1b55d8810..14ac0e8a4 100644
--- a/tests/qapi-schema/duplicate-key.json
+++ b/tests/qapi-schema/duplicate-key.json
@@ -1,2 +1,3 @@
+# QAPI cannot include the same key more than once in any {}
{ 'key': 'value',
'key': 'value' }
diff --git a/tests/qapi-schema/empty.out b/tests/qapi-schema/empty.out
index b7f89a45c..272b1616f 100644
--- a/tests/qapi-schema/empty.out
+++ b/tests/qapi-schema/empty.out
@@ -1,3 +1 @@
-[]
-[]
-[]
+object :empty
diff --git a/tests/qapi-schema/enum-bad-prefix.err b/tests/qapi-schema/enum-bad-prefix.err
new file mode 100644
index 000000000..399f5f7af
--- /dev/null
+++ b/tests/qapi-schema/enum-bad-prefix.err
@@ -0,0 +1 @@
+tests/qapi-schema/enum-bad-prefix.json:2: Enum 'MyEnum' requires a string for 'prefix'
diff --git a/tests/qapi-schema/type-bypass-no-gen.exit b/tests/qapi-schema/enum-bad-prefix.exit
index d00491fd7..d00491fd7 100644
--- a/tests/qapi-schema/type-bypass-no-gen.exit
+++ b/tests/qapi-schema/enum-bad-prefix.exit
diff --git a/tests/qapi-schema/enum-bad-prefix.json b/tests/qapi-schema/enum-bad-prefix.json
new file mode 100644
index 000000000..996f628f6
--- /dev/null
+++ b/tests/qapi-schema/enum-bad-prefix.json
@@ -0,0 +1,2 @@
+# The prefix must be a string type
+{ 'enum': 'MyEnum', 'data': [ 'one' ], 'prefix': [ 'fish' ] }
diff --git a/tests/qapi-schema/flat-union-reverse-define.err b/tests/qapi-schema/enum-bad-prefix.out
index e69de29bb..e69de29bb 100644
--- a/tests/qapi-schema/flat-union-reverse-define.err
+++ b/tests/qapi-schema/enum-bad-prefix.out
diff --git a/tests/qapi-schema/enum-empty.json b/tests/qapi-schema/enum-empty.json
deleted file mode 100644
index 40d4e85a2..000000000
--- a/tests/qapi-schema/enum-empty.json
+++ /dev/null
@@ -1,2 +0,0 @@
-# An empty enum, although unusual, is currently acceptable
-{ 'enum': 'MyEnum', 'data': [ ] }
diff --git a/tests/qapi-schema/enum-empty.out b/tests/qapi-schema/enum-empty.out
deleted file mode 100644
index 3b75c1613..000000000
--- a/tests/qapi-schema/enum-empty.out
+++ /dev/null
@@ -1,3 +0,0 @@
-[OrderedDict([('enum', 'MyEnum'), ('data', [])])]
-[{'enum_name': 'MyEnum', 'enum_values': []}]
-[]
diff --git a/tests/qapi-schema/enum-union-clash.err b/tests/qapi-schema/enum-union-clash.err
deleted file mode 100644
index c04e1a806..000000000
--- a/tests/qapi-schema/enum-union-clash.err
+++ /dev/null
@@ -1 +0,0 @@
-tests/qapi-schema/enum-union-clash.json:2: enum 'UnionKind' should not end in 'Kind'
diff --git a/tests/qapi-schema/event-case.out b/tests/qapi-schema/event-case.out
index 3764bc781..cdfd264f9 100644
--- a/tests/qapi-schema/event-case.out
+++ b/tests/qapi-schema/event-case.out
@@ -1,3 +1,2 @@
-[OrderedDict([('event', 'oops')])]
-[]
-[]
+object :empty
+event oops None
diff --git a/tests/qapi-schema/flat-union-bad-base.err b/tests/qapi-schema/flat-union-bad-base.err
index f9c31b2bf..79b8a71eb 100644
--- a/tests/qapi-schema/flat-union-bad-base.err
+++ b/tests/qapi-schema/flat-union-bad-base.err
@@ -1 +1 @@
-tests/qapi-schema/flat-union-bad-base.json:9: Flat union 'TestUnion' must have a string base field
+tests/qapi-schema/flat-union-bad-base.json:9: 'base' for union 'TestUnion' should be a type name
diff --git a/tests/qapi-schema/flat-union-base-any.err b/tests/qapi-schema/flat-union-base-any.err
new file mode 100644
index 000000000..646f1c9cd
--- /dev/null
+++ b/tests/qapi-schema/flat-union-base-any.err
@@ -0,0 +1 @@
+tests/qapi-schema/flat-union-base-any.json:8: 'base' for union 'TestUnion' cannot use built-in type 'any'
diff --git a/tests/qapi-schema/flat-union-base-any.exit b/tests/qapi-schema/flat-union-base-any.exit
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/tests/qapi-schema/flat-union-base-any.exit
@@ -0,0 +1 @@
+1
diff --git a/tests/qapi-schema/flat-union-base-star.json b/tests/qapi-schema/flat-union-base-any.json
index 5099439a9..fe66b713e 100644
--- a/tests/qapi-schema/flat-union-base-star.json
+++ b/tests/qapi-schema/flat-union-base-any.json
@@ -6,7 +6,7 @@
{ 'struct': 'TestTypeB',
'data': { 'integer': 'int' } }
{ 'union': 'TestUnion',
- 'base': '**',
+ 'base': 'any',
'discriminator': 'enum1',
'data': { 'value1': 'TestTypeA',
'value2': 'TestTypeB' } }
diff --git a/tests/qapi-schema/nested-struct-returns.out b/tests/qapi-schema/flat-union-base-any.out
index e69de29bb..e69de29bb 100644
--- a/tests/qapi-schema/nested-struct-returns.out
+++ b/tests/qapi-schema/flat-union-base-any.out
diff --git a/tests/qapi-schema/flat-union-base-star.err b/tests/qapi-schema/flat-union-base-star.err
deleted file mode 100644
index b7748f08b..000000000
--- a/tests/qapi-schema/flat-union-base-star.err
+++ /dev/null
@@ -1 +0,0 @@
-tests/qapi-schema/flat-union-base-star.json:8: Base '**' is not a valid struct
diff --git a/tests/qapi-schema/flat-union-base-union.err b/tests/qapi-schema/flat-union-base-union.err
index ede9859a3..f138395e4 100644
--- a/tests/qapi-schema/flat-union-base-union.err
+++ b/tests/qapi-schema/flat-union-base-union.err
@@ -1 +1 @@
-tests/qapi-schema/flat-union-base-union.json:11: Base 'UnionBase' is not a valid struct
+tests/qapi-schema/flat-union-base-union.json:14: 'base' for union 'TestUnion' cannot use union type 'UnionBase'
diff --git a/tests/qapi-schema/flat-union-base-union.json b/tests/qapi-schema/flat-union-base-union.json
index 6a8ea687a..98b4eba18 100644
--- a/tests/qapi-schema/flat-union-base-union.json
+++ b/tests/qapi-schema/flat-union-base-union.json
@@ -1,4 +1,7 @@
-# we require the base to be a struct
+# For now, we require the base to be a struct without variants
+# TODO: It would be possible to allow a union as a base, as long as all
+# permutations of QMP names exposed by base do not clash with any QMP
+# member names added by local variants.
{ 'enum': 'TestEnum',
'data': [ 'value1', 'value2' ] }
{ 'struct': 'TestTypeA',
diff --git a/tests/qapi-schema/flat-union-branch-clash.err b/tests/qapi-schema/flat-union-branch-clash.err
deleted file mode 100644
index f11276688..000000000
--- a/tests/qapi-schema/flat-union-branch-clash.err
+++ /dev/null
@@ -1 +0,0 @@
-tests/qapi-schema/flat-union-branch-clash.json:10: Member name 'name' of branch 'value1' clashes with base 'Base'
diff --git a/tests/qapi-schema/returns-int.err b/tests/qapi-schema/flat-union-clash-branch.err
index e69de29bb..e69de29bb 100644
--- a/tests/qapi-schema/returns-int.err
+++ b/tests/qapi-schema/flat-union-clash-branch.err
diff --git a/tests/qapi-schema/enum-empty.exit b/tests/qapi-schema/flat-union-clash-branch.exit
index 573541ac9..573541ac9 100644
--- a/tests/qapi-schema/enum-empty.exit
+++ b/tests/qapi-schema/flat-union-clash-branch.exit
diff --git a/tests/qapi-schema/flat-union-clash-branch.json b/tests/qapi-schema/flat-union-clash-branch.json
new file mode 100644
index 000000000..e59333603
--- /dev/null
+++ b/tests/qapi-schema/flat-union-clash-branch.json
@@ -0,0 +1,18 @@
+# Flat union branch name collision
+# FIXME: this parses, but then fails to compile due to a duplicate 'c_d'
+# (one from the base member, the other from the branch name). We should
+# either reject the collision at parse time, or munge the generated branch
+# name to allow this to compile.
+{ 'enum': 'TestEnum',
+ 'data': [ 'base', 'c-d' ] }
+{ 'struct': 'Base',
+ 'data': { 'enum1': 'TestEnum', '*c_d': 'str' } }
+{ 'struct': 'Branch1',
+ 'data': { 'string': 'str' } }
+{ 'struct': 'Branch2',
+ 'data': { 'value': 'int' } }
+{ 'union': 'TestUnion',
+ 'base': 'Base',
+ 'discriminator': 'enum1',
+ 'data': { 'base': 'Branch1',
+ 'c-d': 'Branch2' } }
diff --git a/tests/qapi-schema/flat-union-clash-branch.out b/tests/qapi-schema/flat-union-clash-branch.out
new file mode 100644
index 000000000..8e0da7360
--- /dev/null
+++ b/tests/qapi-schema/flat-union-clash-branch.out
@@ -0,0 +1,14 @@
+object :empty
+object Base
+ member enum1: TestEnum optional=False
+ member c_d: str optional=True
+object Branch1
+ member string: str optional=False
+object Branch2
+ member value: int optional=False
+enum TestEnum ['base', 'c-d']
+object TestUnion
+ base Base
+ tag enum1
+ case base: Branch1
+ case c-d: Branch2
diff --git a/tests/qapi-schema/flat-union-clash-member.err b/tests/qapi-schema/flat-union-clash-member.err
new file mode 100644
index 000000000..2f0397a8a
--- /dev/null
+++ b/tests/qapi-schema/flat-union-clash-member.err
@@ -0,0 +1 @@
+tests/qapi-schema/flat-union-clash-member.json:11: Member name 'name' of branch 'value1' clashes with base 'Base'
diff --git a/tests/qapi-schema/flat-union-clash-member.exit b/tests/qapi-schema/flat-union-clash-member.exit
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/tests/qapi-schema/flat-union-clash-member.exit
@@ -0,0 +1 @@
+1
diff --git a/tests/qapi-schema/flat-union-branch-clash.json b/tests/qapi-schema/flat-union-clash-member.json
index 8fb054f00..9efc7719b 100644
--- a/tests/qapi-schema/flat-union-branch-clash.json
+++ b/tests/qapi-schema/flat-union-clash-member.json
@@ -1,4 +1,5 @@
-# we check for no duplicate keys between branches and base
+# We check for no duplicate keys between branch members and base
+# base's member 'name' clashes with Branch1's
{ 'enum': 'TestEnum',
'data': [ 'value1', 'value2' ] }
{ 'struct': 'Base',
diff --git a/tests/qapi-schema/type-bypass-no-gen.out b/tests/qapi-schema/flat-union-clash-member.out
index e69de29bb..e69de29bb 100644
--- a/tests/qapi-schema/type-bypass-no-gen.out
+++ b/tests/qapi-schema/flat-union-clash-member.out
diff --git a/tests/qapi-schema/flat-union-clash-type.err b/tests/qapi-schema/flat-union-clash-type.err
new file mode 100644
index 000000000..b44dd4005
--- /dev/null
+++ b/tests/qapi-schema/flat-union-clash-type.err
@@ -0,0 +1 @@
+tests/qapi-schema/flat-union-clash-type.json:11: Discriminator name 'type' collides with enum value in 'TestEnum'
diff --git a/tests/qapi-schema/flat-union-clash-type.exit b/tests/qapi-schema/flat-union-clash-type.exit
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/tests/qapi-schema/flat-union-clash-type.exit
@@ -0,0 +1 @@
+1
diff --git a/tests/qapi-schema/flat-union-clash-type.json b/tests/qapi-schema/flat-union-clash-type.json
new file mode 100644
index 000000000..8f710f08a
--- /dev/null
+++ b/tests/qapi-schema/flat-union-clash-type.json
@@ -0,0 +1,14 @@
+# Flat union branch 'type'
+# Reject this, because we would have a clash in generated C, between the
+# outer tag 'type' and the branch name 'type' within the union.
+# TODO: We could munge the generated C branch name to let it compile.
+{ 'enum': 'TestEnum',
+ 'data': [ 'type' ] }
+{ 'struct': 'Base',
+ 'data': { 'type': 'TestEnum' } }
+{ 'struct': 'Branch1',
+ 'data': { 'string': 'str' } }
+{ 'union': 'TestUnion',
+ 'base': 'Base',
+ 'discriminator': 'type',
+ 'data': { 'type': 'Branch1' } }
diff --git a/tests/qapi-schema/type-bypass.err b/tests/qapi-schema/flat-union-clash-type.out
index e69de29bb..e69de29bb 100644
--- a/tests/qapi-schema/type-bypass.err
+++ b/tests/qapi-schema/flat-union-clash-type.out
diff --git a/tests/qapi-schema/flat-union-empty.err b/tests/qapi-schema/flat-union-empty.err
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/tests/qapi-schema/flat-union-empty.err
diff --git a/tests/qapi-schema/flat-union-reverse-define.exit b/tests/qapi-schema/flat-union-empty.exit
index 573541ac9..573541ac9 100644
--- a/tests/qapi-schema/flat-union-reverse-define.exit
+++ b/tests/qapi-schema/flat-union-empty.exit
diff --git a/tests/qapi-schema/flat-union-empty.json b/tests/qapi-schema/flat-union-empty.json
new file mode 100644
index 000000000..67dd2978e
--- /dev/null
+++ b/tests/qapi-schema/flat-union-empty.json
@@ -0,0 +1,4 @@
+# FIXME - flat unions should not be empty
+{ 'enum': 'Empty', 'data': [ ] }
+{ 'struct': 'Base', 'data': { 'type': 'Empty' } }
+{ 'union': 'Union', 'base': 'Base', 'discriminator': 'type', 'data': { } }
diff --git a/tests/qapi-schema/flat-union-empty.out b/tests/qapi-schema/flat-union-empty.out
new file mode 100644
index 000000000..0e0665af3
--- /dev/null
+++ b/tests/qapi-schema/flat-union-empty.out
@@ -0,0 +1,7 @@
+object :empty
+object Base
+ member type: Empty optional=False
+enum Empty []
+object Union
+ base Base
+ tag type
diff --git a/tests/qapi-schema/flat-union-inline.err b/tests/qapi-schema/flat-union-inline.err
index ec586277b..2333358d2 100644
--- a/tests/qapi-schema/flat-union-inline.err
+++ b/tests/qapi-schema/flat-union-inline.err
@@ -1 +1 @@
-tests/qapi-schema/flat-union-inline.json:7: Flat union 'TestUnion' must have a string base field
+tests/qapi-schema/flat-union-inline.json:7: Member 'value1' of union 'TestUnion' should be a type name
diff --git a/tests/qapi-schema/flat-union-inline.json b/tests/qapi-schema/flat-union-inline.json
index 6bfdd6581..62c7cda61 100644
--- a/tests/qapi-schema/flat-union-inline.json
+++ b/tests/qapi-schema/flat-union-inline.json
@@ -1,11 +1,11 @@
# we require branches to be a struct name
-# TODO: should we allow anonymous inline types?
+# TODO: should we allow anonymous inline branch types?
{ 'enum': 'TestEnum',
'data': [ 'value1', 'value2' ] }
{ 'struct': 'Base',
'data': { 'enum1': 'TestEnum', 'kind': 'str' } }
{ 'union': 'TestUnion',
- 'base': { 'enum1': 'TestEnum', 'kind': 'str' },
+ 'base': 'Base',
'discriminator': 'enum1',
'data': { 'value1': { 'string': 'str' },
'value2': { 'integer': 'int' } } }
diff --git a/tests/qapi-schema/flat-union-no-base.err b/tests/qapi-schema/flat-union-no-base.err
index bb3f70874..841c93b55 100644
--- a/tests/qapi-schema/flat-union-no-base.err
+++ b/tests/qapi-schema/flat-union-no-base.err
@@ -1 +1 @@
-tests/qapi-schema/flat-union-no-base.json:9: Flat union 'TestUnion' must have a string base field
+tests/qapi-schema/flat-union-no-base.json:9: Flat union 'TestUnion' must have a base
diff --git a/tests/qapi-schema/flat-union-reverse-define.json b/tests/qapi-schema/flat-union-reverse-define.json
deleted file mode 100644
index 648bbfe2b..000000000
--- a/tests/qapi-schema/flat-union-reverse-define.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{ 'union': 'TestUnion',
- 'base': 'TestBase',
- 'discriminator': 'enum1',
- 'data': { 'value1': 'TestTypeA',
- 'value2': 'TestTypeB' } }
-
-{ 'struct': 'TestBase',
- 'data': { 'enum1': 'TestEnum' } }
-
-{ 'enum': 'TestEnum',
- 'data': [ 'value1', 'value2' ] }
-
-{ 'struct': 'TestTypeA',
- 'data': { 'string': 'str' } }
-
-{ 'struct': 'TestTypeB',
- 'data': { 'integer': 'int' } }
diff --git a/tests/qapi-schema/flat-union-reverse-define.out b/tests/qapi-schema/flat-union-reverse-define.out
deleted file mode 100644
index 1ed7b8a51..000000000
--- a/tests/qapi-schema/flat-union-reverse-define.out
+++ /dev/null
@@ -1,9 +0,0 @@
-[OrderedDict([('union', 'TestUnion'), ('base', 'TestBase'), ('discriminator', 'enum1'), ('data', OrderedDict([('value1', 'TestTypeA'), ('value2', 'TestTypeB')]))]),
- OrderedDict([('struct', 'TestBase'), ('data', OrderedDict([('enum1', 'TestEnum')]))]),
- OrderedDict([('enum', 'TestEnum'), ('data', ['value1', 'value2'])]),
- OrderedDict([('struct', 'TestTypeA'), ('data', OrderedDict([('string', 'str')]))]),
- OrderedDict([('struct', 'TestTypeB'), ('data', OrderedDict([('integer', 'int')]))])]
-[{'enum_name': 'TestEnum', 'enum_values': ['value1', 'value2']}]
-[OrderedDict([('struct', 'TestBase'), ('data', OrderedDict([('enum1', 'TestEnum')]))]),
- OrderedDict([('struct', 'TestTypeA'), ('data', OrderedDict([('string', 'str')]))]),
- OrderedDict([('struct', 'TestTypeB'), ('data', OrderedDict([('integer', 'int')]))])]
diff --git a/tests/qapi-schema/ident-with-escape.out b/tests/qapi-schema/ident-with-escape.out
index 402843081..f4542b12d 100644
--- a/tests/qapi-schema/ident-with-escape.out
+++ b/tests/qapi-schema/ident-with-escape.out
@@ -1,3 +1,5 @@
-[OrderedDict([('command', 'fooA'), ('data', OrderedDict([('bar1', 'str')]))])]
-[]
-[]
+object :empty
+object :obj-fooA-arg
+ member bar1: str optional=False
+command fooA :obj-fooA-arg -> None
+ gen=True success_response=True
diff --git a/tests/qapi-schema/include-non-file.err b/tests/qapi-schema/include-non-file.err
index 9658c7880..faae1eacf 100644
--- a/tests/qapi-schema/include-non-file.err
+++ b/tests/qapi-schema/include-non-file.err
@@ -1 +1 @@
-tests/qapi-schema/include-non-file.json:1: Expected a file name (string), got: ['foo', 'bar']
+tests/qapi-schema/include-non-file.json:1: Value of 'include' must be a string
diff --git a/tests/qapi-schema/include-non-file.json b/tests/qapi-schema/include-non-file.json
index cd43c3f9d..4711aa42e 100644
--- a/tests/qapi-schema/include-non-file.json
+++ b/tests/qapi-schema/include-non-file.json
@@ -1 +1 @@
-{ 'include': [ 'foo', 'bar' ] }
+{ 'include': {} }
diff --git a/tests/qapi-schema/include-relpath.out b/tests/qapi-schema/include-relpath.out
index 4ce3dcf12..9e2c656fa 100644
--- a/tests/qapi-schema/include-relpath.out
+++ b/tests/qapi-schema/include-relpath.out
@@ -1,3 +1,2 @@
-[OrderedDict([('enum', 'Status'), ('data', ['good', 'bad', 'ugly'])])]
-[{'enum_name': 'Status', 'enum_values': ['good', 'bad', 'ugly']}]
-[]
+object :empty
+enum Status ['good', 'bad', 'ugly']
diff --git a/tests/qapi-schema/include-repetition.out b/tests/qapi-schema/include-repetition.out
index 4ce3dcf12..9e2c656fa 100644
--- a/tests/qapi-schema/include-repetition.out
+++ b/tests/qapi-schema/include-repetition.out
@@ -1,3 +1,2 @@
-[OrderedDict([('enum', 'Status'), ('data', ['good', 'bad', 'ugly'])])]
-[{'enum_name': 'Status', 'enum_values': ['good', 'bad', 'ugly']}]
-[]
+object :empty
+enum Status ['good', 'bad', 'ugly']
diff --git a/tests/qapi-schema/include-simple.out b/tests/qapi-schema/include-simple.out
index 4ce3dcf12..9e2c656fa 100644
--- a/tests/qapi-schema/include-simple.out
+++ b/tests/qapi-schema/include-simple.out
@@ -1,3 +1,2 @@
-[OrderedDict([('enum', 'Status'), ('data', ['good', 'bad', 'ugly'])])]
-[{'enum_name': 'Status', 'enum_values': ['good', 'bad', 'ugly']}]
-[]
+object :empty
+enum Status ['good', 'bad', 'ugly']
diff --git a/tests/qapi-schema/indented-expr.out b/tests/qapi-schema/indented-expr.out
index b5ce9151b..226d30079 100644
--- a/tests/qapi-schema/indented-expr.out
+++ b/tests/qapi-schema/indented-expr.out
@@ -1,3 +1,5 @@
-[OrderedDict([('command', 'eins')]), OrderedDict([('command', 'zwei')])]
-[]
-[]
+object :empty
+command eins None -> None
+ gen=True success_response=True
+command zwei None -> None
+ gen=True success_response=True
diff --git a/tests/qapi-schema/leading-comma-list.err b/tests/qapi-schema/leading-comma-list.err
new file mode 100644
index 000000000..f5c870bb9
--- /dev/null
+++ b/tests/qapi-schema/leading-comma-list.err
@@ -0,0 +1 @@
+tests/qapi-schema/leading-comma-list.json:2:13: Expected "{", "[", "]", string, boolean or "null"
diff --git a/tests/qapi-schema/leading-comma-list.exit b/tests/qapi-schema/leading-comma-list.exit
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/tests/qapi-schema/leading-comma-list.exit
@@ -0,0 +1 @@
+1
diff --git a/tests/qapi-schema/leading-comma-list.json b/tests/qapi-schema/leading-comma-list.json
new file mode 100644
index 000000000..c5ba50159
--- /dev/null
+++ b/tests/qapi-schema/leading-comma-list.json
@@ -0,0 +1,2 @@
+{ 'enum': 'Status',
+ 'data': [ , 'good', 'bad', 'ugly' ] }
diff --git a/tests/qapi-schema/leading-comma-list.out b/tests/qapi-schema/leading-comma-list.out
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/tests/qapi-schema/leading-comma-list.out
diff --git a/tests/qapi-schema/leading-comma-object.err b/tests/qapi-schema/leading-comma-object.err
new file mode 100644
index 000000000..f767b9554
--- /dev/null
+++ b/tests/qapi-schema/leading-comma-object.err
@@ -0,0 +1 @@
+tests/qapi-schema/leading-comma-object.json:1:3: Expected string or "}"
diff --git a/tests/qapi-schema/leading-comma-object.exit b/tests/qapi-schema/leading-comma-object.exit
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/tests/qapi-schema/leading-comma-object.exit
@@ -0,0 +1 @@
+1
diff --git a/tests/qapi-schema/leading-comma-object.json b/tests/qapi-schema/leading-comma-object.json
new file mode 100644
index 000000000..c89023ff3
--- /dev/null
+++ b/tests/qapi-schema/leading-comma-object.json
@@ -0,0 +1,2 @@
+{ , 'enum': 'Status',
+ 'data': [ 'good', 'bad', 'ugly' ] }
diff --git a/tests/qapi-schema/leading-comma-object.out b/tests/qapi-schema/leading-comma-object.out
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/tests/qapi-schema/leading-comma-object.out
diff --git a/tests/qapi-schema/nested-struct-data.json b/tests/qapi-schema/nested-struct-data.json
index 3d52d2b39..efbe773de 100644
--- a/tests/qapi-schema/nested-struct-data.json
+++ b/tests/qapi-schema/nested-struct-data.json
@@ -1,4 +1,3 @@
# inline subtypes collide with our desired future use of defaults
{ 'command': 'foo',
- 'data': { 'a' : { 'string' : 'str', 'integer': 'int' }, 'b' : 'str' },
- 'returns': {} }
+ 'data': { 'a' : { 'string' : 'str', 'integer': 'int' }, 'b' : 'str' } }
diff --git a/tests/qapi-schema/nested-struct-returns.err b/tests/qapi-schema/nested-struct-returns.err
deleted file mode 100644
index 5238d075b..000000000
--- a/tests/qapi-schema/nested-struct-returns.err
+++ /dev/null
@@ -1 +0,0 @@
-tests/qapi-schema/nested-struct-returns.json:2: Member 'a' of 'returns' for command 'foo' should be a type name
diff --git a/tests/qapi-schema/nested-struct-returns.json b/tests/qapi-schema/nested-struct-returns.json
deleted file mode 100644
index d2cd047f0..000000000
--- a/tests/qapi-schema/nested-struct-returns.json
+++ /dev/null
@@ -1,3 +0,0 @@
-# inline subtypes collide with our desired future use of defaults
-{ 'command': 'foo',
- 'returns': { 'a' : { 'string' : 'str', 'integer': 'int' }, 'b' : 'str' } }
diff --git a/tests/qapi-schema/qapi-schema-test.json b/tests/qapi-schema/qapi-schema-test.json
index c7eaa865d..44638da94 100644
--- a/tests/qapi-schema/qapi-schema-test.json
+++ b/tests/qapi-schema/qapi-schema-test.json
@@ -1,19 +1,40 @@
# *-*- Mode: Python -*-*
+# This file is a stress test of supported qapi constructs that must
+# parse and compile correctly.
+
+{ 'struct': 'TestStruct',
+ 'data': { 'integer': 'int', 'boolean': 'bool', 'string': 'str' } }
+
# for testing enums
-{ 'enum': 'EnumOne',
- 'data': [ 'value1', 'value2', 'value3' ] }
{ 'struct': 'NestedEnumsOne',
- 'data': { 'enum1': 'EnumOne', '*enum2': 'EnumOne', 'enum3': 'EnumOne', '*enum4': 'EnumOne' } }
+ 'data': { 'enum1': 'EnumOne', # Intentional forward reference
+ '*enum2': 'EnumOne', 'enum3': 'EnumOne', '*enum4': 'EnumOne' } }
+
+# An empty enum, although unusual, is currently acceptable
+{ 'enum': 'MyEnum', 'data': [ ] }
+
+# Likewise for an empty struct, including an empty base
+{ 'struct': 'Empty1', 'data': { } }
+{ 'struct': 'Empty2', 'base': 'Empty1', 'data': { } }
+
+# for testing override of default naming heuristic
+{ 'enum': 'QEnumTwo',
+ 'prefix': 'QENUM_TWO',
+ 'data': [ 'value1', 'value2' ] }
# for testing nested structs
+{ 'struct': 'UserDefOne',
+ 'base': 'UserDefZero', # intentional forward reference
+ 'data': { 'string': 'str',
+ '*enum1': 'EnumOne' } } # intentional forward reference
+
+{ 'enum': 'EnumOne',
+ 'data': [ 'value1', 'value2', 'value3' ] }
+
{ 'struct': 'UserDefZero',
'data': { 'integer': 'int' } }
-{ 'struct': 'UserDefOne',
- 'base': 'UserDefZero',
- 'data': { 'string': 'str', '*enum1': 'EnumOne' } }
-
{ 'struct': 'UserDefTwoDictDict',
'data': { 'userdef': 'UserDefOne', 'string': 'str' } }
@@ -26,36 +47,55 @@
'data': { 'string0': 'str',
'dict1': 'UserDefTwoDict' } }
+# dummy struct to force generation of array types not otherwise mentioned
+{ 'struct': 'ForceArrays',
+ 'data': { 'unused1':['UserDefOne'], 'unused2':['UserDefTwo'],
+ 'unused3':['TestStruct'] } }
+
# for testing unions
+# Among other things, test that a name collision between branches does
+# not cause any problems (since only one branch can be in use at a time),
+# by intentionally using two branches that both have a C member 'a_b'
{ 'struct': 'UserDefA',
- 'data': { 'boolean': 'bool' } }
+ 'data': { 'boolean': 'bool', '*a_b': 'int' } }
{ 'struct': 'UserDefB',
- 'data': { 'integer': 'int' } }
+ 'data': { 'intb': 'int', '*a-b': 'bool' } }
-{ 'struct': 'UserDefC',
- 'data': { 'string1': 'str', 'string2': 'str' } }
+{ 'union': 'UserDefFlatUnion',
+ 'base': 'UserDefUnionBase', # intentional forward reference
+ 'discriminator': 'enum1',
+ 'data': { 'value1' : 'UserDefA',
+ 'value2' : 'UserDefB',
+ 'value3' : 'UserDefB' } }
{ 'struct': 'UserDefUnionBase',
+ 'base': 'UserDefZero',
'data': { 'string': 'str', 'enum1': 'EnumOne' } }
-{ 'union': 'UserDefFlatUnion',
- 'base': 'UserDefUnionBase',
- 'discriminator': 'enum1',
- 'data': { 'value1' : 'UserDefA', 'value2' : 'UserDefB', 'value3' : 'UserDefB' } }
-# FIXME generated struct UserDefFlatUnion has members for direct base
-# UserDefOne, but lacks members for indirect base UserDefZero
-
# this variant of UserDefFlatUnion defaults to a union that uses fields with
# allocated types to test corner cases in the cleanup/dealloc visitor
{ 'union': 'UserDefFlatUnion2',
'base': 'UserDefUnionBase',
'discriminator': 'enum1',
- 'data': { 'value1' : 'UserDefC', 'value2' : 'UserDefB', 'value3' : 'UserDefA' } }
+ 'data': { 'value1' : 'UserDefC', # intentional forward reference
+ 'value2' : 'UserDefB',
+ 'value3' : 'UserDefA' } }
{ 'alternate': 'UserDefAlternate',
'data': { 'uda': 'UserDefA', 's': 'str', 'i': 'int' } }
+{ 'struct': 'UserDefC',
+ 'data': { 'string1': 'str', 'string2': 'str' } }
+
+# for testing use of 'number' within alternates
+{ 'alternate': 'AltStrBool', 'data': { 's': 'str', 'b': 'bool' } }
+{ 'alternate': 'AltStrNum', 'data': { 's': 'str', 'n': 'number' } }
+{ 'alternate': 'AltNumStr', 'data': { 'n': 'number', 's': 'str' } }
+{ 'alternate': 'AltStrInt', 'data': { 's': 'str', 'i': 'int' } }
+{ 'alternate': 'AltIntNum', 'data': { 'i': 'int', 'n': 'number' } }
+{ 'alternate': 'AltNumInt', 'data': { 'n': 'number', 'i': 'int' } }
+
# for testing native lists
{ 'union': 'UserDefNativeListUnion',
'data': { 'integer': ['int'],
@@ -70,7 +110,8 @@
'number': ['number'],
'boolean': ['bool'],
'string': ['str'],
- 'sizes': ['size'] } }
+ 'sizes': ['size'],
+ 'any': ['any'] } }
# testing commands
{ 'command': 'user_def_cmd', 'data': {} }
@@ -78,8 +119,11 @@
{ 'command': 'user_def_cmd2',
'data': {'ud1a': 'UserDefOne', '*ud1b': 'UserDefOne'},
'returns': 'UserDefTwo' }
-{ 'command': 'user_def_cmd3', 'data': {'a': 'int', '*b': 'int' },
+
+# Returning a non-dictionary requires a name from the whitelist
+{ 'command': 'guest-get-time', 'data': {'a': 'int', '*b': 'int' },
'returns': 'int' }
+{ 'command': 'guest-sync', 'data': { 'arg': 'any' }, 'returns': 'any' }
# For testing integer range flattening in opts-visitor. The following schema
# corresponds to the option format:
diff --git a/tests/qapi-schema/qapi-schema-test.out b/tests/qapi-schema/qapi-schema-test.out
index cf0ccc402..e20a8239a 100644
--- a/tests/qapi-schema/qapi-schema-test.out
+++ b/tests/qapi-schema/qapi-schema-test.out
@@ -1,55 +1,207 @@
-[OrderedDict([('enum', 'EnumOne'), ('data', ['value1', 'value2', 'value3'])]),
- OrderedDict([('struct', 'NestedEnumsOne'), ('data', OrderedDict([('enum1', 'EnumOne'), ('*enum2', 'EnumOne'), ('enum3', 'EnumOne'), ('*enum4', 'EnumOne')]))]),
- OrderedDict([('struct', 'UserDefZero'), ('data', OrderedDict([('integer', 'int')]))]),
- OrderedDict([('struct', 'UserDefOne'), ('base', 'UserDefZero'), ('data', OrderedDict([('string', 'str'), ('*enum1', 'EnumOne')]))]),
- OrderedDict([('struct', 'UserDefTwoDictDict'), ('data', OrderedDict([('userdef', 'UserDefOne'), ('string', 'str')]))]),
- OrderedDict([('struct', 'UserDefTwoDict'), ('data', OrderedDict([('string1', 'str'), ('dict2', 'UserDefTwoDictDict'), ('*dict3', 'UserDefTwoDictDict')]))]),
- OrderedDict([('struct', 'UserDefTwo'), ('data', OrderedDict([('string0', 'str'), ('dict1', 'UserDefTwoDict')]))]),
- OrderedDict([('struct', 'UserDefA'), ('data', OrderedDict([('boolean', 'bool')]))]),
- OrderedDict([('struct', 'UserDefB'), ('data', OrderedDict([('integer', 'int')]))]),
- OrderedDict([('struct', 'UserDefC'), ('data', OrderedDict([('string1', 'str'), ('string2', 'str')]))]),
- OrderedDict([('struct', 'UserDefUnionBase'), ('data', OrderedDict([('string', 'str'), ('enum1', 'EnumOne')]))]),
- OrderedDict([('union', 'UserDefFlatUnion'), ('base', 'UserDefUnionBase'), ('discriminator', 'enum1'), ('data', OrderedDict([('value1', 'UserDefA'), ('value2', 'UserDefB'), ('value3', 'UserDefB')]))]),
- OrderedDict([('union', 'UserDefFlatUnion2'), ('base', 'UserDefUnionBase'), ('discriminator', 'enum1'), ('data', OrderedDict([('value1', 'UserDefC'), ('value2', 'UserDefB'), ('value3', 'UserDefA')]))]),
- OrderedDict([('alternate', 'UserDefAlternate'), ('data', OrderedDict([('uda', 'UserDefA'), ('s', 'str'), ('i', 'int')]))]),
- OrderedDict([('union', 'UserDefNativeListUnion'), ('data', OrderedDict([('integer', ['int']), ('s8', ['int8']), ('s16', ['int16']), ('s32', ['int32']), ('s64', ['int64']), ('u8', ['uint8']), ('u16', ['uint16']), ('u32', ['uint32']), ('u64', ['uint64']), ('number', ['number']), ('boolean', ['bool']), ('string', ['str']), ('sizes', ['size'])]))]),
- OrderedDict([('command', 'user_def_cmd'), ('data', OrderedDict())]),
- OrderedDict([('command', 'user_def_cmd1'), ('data', OrderedDict([('ud1a', 'UserDefOne')]))]),
- OrderedDict([('command', 'user_def_cmd2'), ('data', OrderedDict([('ud1a', 'UserDefOne'), ('*ud1b', 'UserDefOne')])), ('returns', 'UserDefTwo')]),
- OrderedDict([('command', 'user_def_cmd3'), ('data', OrderedDict([('a', 'int'), ('*b', 'int')])), ('returns', 'int')]),
- OrderedDict([('struct', 'UserDefOptions'), ('data', OrderedDict([('*i64', ['int']), ('*u64', ['uint64']), ('*u16', ['uint16']), ('*i64x', 'int'), ('*u64x', 'uint64')]))]),
- OrderedDict([('struct', 'EventStructOne'), ('data', OrderedDict([('struct1', 'UserDefOne'), ('string', 'str'), ('*enum2', 'EnumOne')]))]),
- OrderedDict([('event', 'EVENT_A')]),
- OrderedDict([('event', 'EVENT_B'), ('data', OrderedDict())]),
- OrderedDict([('event', 'EVENT_C'), ('data', OrderedDict([('*a', 'int'), ('*b', 'UserDefOne'), ('c', 'str')]))]),
- OrderedDict([('event', 'EVENT_D'), ('data', OrderedDict([('a', 'EventStructOne'), ('b', 'str'), ('*c', 'str'), ('*enum3', 'EnumOne')]))]),
- OrderedDict([('enum', '__org.qemu_x-Enum'), ('data', ['__org.qemu_x-value'])]),
- OrderedDict([('struct', '__org.qemu_x-Base'), ('data', OrderedDict([('__org.qemu_x-member1', '__org.qemu_x-Enum')]))]),
- OrderedDict([('struct', '__org.qemu_x-Struct'), ('base', '__org.qemu_x-Base'), ('data', OrderedDict([('__org.qemu_x-member2', 'str')]))]),
- OrderedDict([('union', '__org.qemu_x-Union1'), ('data', OrderedDict([('__org.qemu_x-branch', 'str')]))]),
- OrderedDict([('struct', '__org.qemu_x-Struct2'), ('data', OrderedDict([('array', ['__org.qemu_x-Union1'])]))]),
- OrderedDict([('union', '__org.qemu_x-Union2'), ('base', '__org.qemu_x-Base'), ('discriminator', '__org.qemu_x-member1'), ('data', OrderedDict([('__org.qemu_x-value', '__org.qemu_x-Struct2')]))]),
- OrderedDict([('alternate', '__org.qemu_x-Alt'), ('data', OrderedDict([('__org.qemu_x-branch', 'str'), ('b', '__org.qemu_x-Base')]))]),
- OrderedDict([('event', '__ORG.QEMU_X-EVENT'), ('data', '__org.qemu_x-Struct')]),
- OrderedDict([('command', '__org.qemu_x-command'), ('data', OrderedDict([('a', ['__org.qemu_x-Enum']), ('b', ['__org.qemu_x-Struct']), ('c', '__org.qemu_x-Union2'), ('d', '__org.qemu_x-Alt')])), ('returns', '__org.qemu_x-Union1')])]
-[{'enum_name': 'EnumOne', 'enum_values': ['value1', 'value2', 'value3']},
- {'enum_name': '__org.qemu_x-Enum', 'enum_values': ['__org.qemu_x-value']},
- {'enum_name': 'UserDefAlternateKind', 'enum_values': None},
- {'enum_name': 'UserDefNativeListUnionKind', 'enum_values': None},
- {'enum_name': '__org.qemu_x-Union1Kind', 'enum_values': None},
- {'enum_name': '__org.qemu_x-AltKind', 'enum_values': None}]
-[OrderedDict([('struct', 'NestedEnumsOne'), ('data', OrderedDict([('enum1', 'EnumOne'), ('*enum2', 'EnumOne'), ('enum3', 'EnumOne'), ('*enum4', 'EnumOne')]))]),
- OrderedDict([('struct', 'UserDefZero'), ('data', OrderedDict([('integer', 'int')]))]),
- OrderedDict([('struct', 'UserDefOne'), ('base', 'UserDefZero'), ('data', OrderedDict([('string', 'str'), ('*enum1', 'EnumOne')]))]),
- OrderedDict([('struct', 'UserDefTwoDictDict'), ('data', OrderedDict([('userdef', 'UserDefOne'), ('string', 'str')]))]),
- OrderedDict([('struct', 'UserDefTwoDict'), ('data', OrderedDict([('string1', 'str'), ('dict2', 'UserDefTwoDictDict'), ('*dict3', 'UserDefTwoDictDict')]))]),
- OrderedDict([('struct', 'UserDefTwo'), ('data', OrderedDict([('string0', 'str'), ('dict1', 'UserDefTwoDict')]))]),
- OrderedDict([('struct', 'UserDefA'), ('data', OrderedDict([('boolean', 'bool')]))]),
- OrderedDict([('struct', 'UserDefB'), ('data', OrderedDict([('integer', 'int')]))]),
- OrderedDict([('struct', 'UserDefC'), ('data', OrderedDict([('string1', 'str'), ('string2', 'str')]))]),
- OrderedDict([('struct', 'UserDefUnionBase'), ('data', OrderedDict([('string', 'str'), ('enum1', 'EnumOne')]))]),
- OrderedDict([('struct', 'UserDefOptions'), ('data', OrderedDict([('*i64', ['int']), ('*u64', ['uint64']), ('*u16', ['uint16']), ('*i64x', 'int'), ('*u64x', 'uint64')]))]),
- OrderedDict([('struct', 'EventStructOne'), ('data', OrderedDict([('struct1', 'UserDefOne'), ('string', 'str'), ('*enum2', 'EnumOne')]))]),
- OrderedDict([('struct', '__org.qemu_x-Base'), ('data', OrderedDict([('__org.qemu_x-member1', '__org.qemu_x-Enum')]))]),
- OrderedDict([('struct', '__org.qemu_x-Struct'), ('base', '__org.qemu_x-Base'), ('data', OrderedDict([('__org.qemu_x-member2', 'str')]))]),
- OrderedDict([('struct', '__org.qemu_x-Struct2'), ('data', OrderedDict([('array', ['__org.qemu_x-Union1'])]))])]
+object :empty
+object :obj-EVENT_C-arg
+ member a: int optional=True
+ member b: UserDefOne optional=True
+ member c: str optional=False
+object :obj-EVENT_D-arg
+ member a: EventStructOne optional=False
+ member b: str optional=False
+ member c: str optional=True
+ member enum3: EnumOne optional=True
+object :obj-__org.qemu_x-command-arg
+ member a: __org.qemu_x-EnumList optional=False
+ member b: __org.qemu_x-StructList optional=False
+ member c: __org.qemu_x-Union2 optional=False
+ member d: __org.qemu_x-Alt optional=False
+object :obj-anyList-wrapper
+ member data: anyList optional=False
+object :obj-boolList-wrapper
+ member data: boolList optional=False
+object :obj-guest-get-time-arg
+ member a: int optional=False
+ member b: int optional=True
+object :obj-guest-sync-arg
+ member arg: any optional=False
+object :obj-int16List-wrapper
+ member data: int16List optional=False
+object :obj-int32List-wrapper
+ member data: int32List optional=False
+object :obj-int64List-wrapper
+ member data: int64List optional=False
+object :obj-int8List-wrapper
+ member data: int8List optional=False
+object :obj-intList-wrapper
+ member data: intList optional=False
+object :obj-numberList-wrapper
+ member data: numberList optional=False
+object :obj-sizeList-wrapper
+ member data: sizeList optional=False
+object :obj-str-wrapper
+ member data: str optional=False
+object :obj-strList-wrapper
+ member data: strList optional=False
+object :obj-uint16List-wrapper
+ member data: uint16List optional=False
+object :obj-uint32List-wrapper
+ member data: uint32List optional=False
+object :obj-uint64List-wrapper
+ member data: uint64List optional=False
+object :obj-uint8List-wrapper
+ member data: uint8List optional=False
+object :obj-user_def_cmd1-arg
+ member ud1a: UserDefOne optional=False
+object :obj-user_def_cmd2-arg
+ member ud1a: UserDefOne optional=False
+ member ud1b: UserDefOne optional=True
+alternate AltIntNum
+ case i: int
+ case n: number
+enum AltIntNumKind ['i', 'n']
+alternate AltNumInt
+ case n: number
+ case i: int
+enum AltNumIntKind ['n', 'i']
+alternate AltNumStr
+ case n: number
+ case s: str
+enum AltNumStrKind ['n', 's']
+alternate AltStrBool
+ case s: str
+ case b: bool
+enum AltStrBoolKind ['s', 'b']
+alternate AltStrInt
+ case s: str
+ case i: int
+enum AltStrIntKind ['s', 'i']
+alternate AltStrNum
+ case s: str
+ case n: number
+enum AltStrNumKind ['s', 'n']
+event EVENT_A None
+event EVENT_B None
+event EVENT_C :obj-EVENT_C-arg
+event EVENT_D :obj-EVENT_D-arg
+object Empty1
+object Empty2
+ base Empty1
+enum EnumOne ['value1', 'value2', 'value3']
+object EventStructOne
+ member struct1: UserDefOne optional=False
+ member string: str optional=False
+ member enum2: EnumOne optional=True
+object ForceArrays
+ member unused1: UserDefOneList optional=False
+ member unused2: UserDefTwoList optional=False
+ member unused3: TestStructList optional=False
+enum MyEnum []
+object NestedEnumsOne
+ member enum1: EnumOne optional=False
+ member enum2: EnumOne optional=True
+ member enum3: EnumOne optional=False
+ member enum4: EnumOne optional=True
+enum QEnumTwo ['value1', 'value2']
+ prefix QENUM_TWO
+object TestStruct
+ member integer: int optional=False
+ member boolean: bool optional=False
+ member string: str optional=False
+object UserDefA
+ member boolean: bool optional=False
+ member a_b: int optional=True
+alternate UserDefAlternate
+ case uda: UserDefA
+ case s: str
+ case i: int
+enum UserDefAlternateKind ['uda', 's', 'i']
+object UserDefB
+ member intb: int optional=False
+ member a-b: bool optional=True
+object UserDefC
+ member string1: str optional=False
+ member string2: str optional=False
+object UserDefFlatUnion
+ base UserDefUnionBase
+ tag enum1
+ case value1: UserDefA
+ case value2: UserDefB
+ case value3: UserDefB
+object UserDefFlatUnion2
+ base UserDefUnionBase
+ tag enum1
+ case value1: UserDefC
+ case value2: UserDefB
+ case value3: UserDefA
+object UserDefNativeListUnion
+ case integer: :obj-intList-wrapper
+ case s8: :obj-int8List-wrapper
+ case s16: :obj-int16List-wrapper
+ case s32: :obj-int32List-wrapper
+ case s64: :obj-int64List-wrapper
+ case u8: :obj-uint8List-wrapper
+ case u16: :obj-uint16List-wrapper
+ case u32: :obj-uint32List-wrapper
+ case u64: :obj-uint64List-wrapper
+ case number: :obj-numberList-wrapper
+ case boolean: :obj-boolList-wrapper
+ case string: :obj-strList-wrapper
+ case sizes: :obj-sizeList-wrapper
+ case any: :obj-anyList-wrapper
+enum UserDefNativeListUnionKind ['integer', 's8', 's16', 's32', 's64', 'u8', 'u16', 'u32', 'u64', 'number', 'boolean', 'string', 'sizes', 'any']
+object UserDefOne
+ base UserDefZero
+ member string: str optional=False
+ member enum1: EnumOne optional=True
+object UserDefOptions
+ member i64: intList optional=True
+ member u64: uint64List optional=True
+ member u16: uint16List optional=True
+ member i64x: int optional=True
+ member u64x: uint64 optional=True
+object UserDefTwo
+ member string0: str optional=False
+ member dict1: UserDefTwoDict optional=False
+object UserDefTwoDict
+ member string1: str optional=False
+ member dict2: UserDefTwoDictDict optional=False
+ member dict3: UserDefTwoDictDict optional=True
+object UserDefTwoDictDict
+ member userdef: UserDefOne optional=False
+ member string: str optional=False
+object UserDefUnionBase
+ base UserDefZero
+ member string: str optional=False
+ member enum1: EnumOne optional=False
+object UserDefZero
+ member integer: int optional=False
+event __ORG.QEMU_X-EVENT __org.qemu_x-Struct
+alternate __org.qemu_x-Alt
+ case __org.qemu_x-branch: str
+ case b: __org.qemu_x-Base
+enum __org.qemu_x-AltKind ['__org.qemu_x-branch', 'b']
+object __org.qemu_x-Base
+ member __org.qemu_x-member1: __org.qemu_x-Enum optional=False
+enum __org.qemu_x-Enum ['__org.qemu_x-value']
+object __org.qemu_x-Struct
+ base __org.qemu_x-Base
+ member __org.qemu_x-member2: str optional=False
+object __org.qemu_x-Struct2
+ member array: __org.qemu_x-Union1List optional=False
+object __org.qemu_x-Union1
+ case __org.qemu_x-branch: :obj-str-wrapper
+enum __org.qemu_x-Union1Kind ['__org.qemu_x-branch']
+object __org.qemu_x-Union2
+ base __org.qemu_x-Base
+ tag __org.qemu_x-member1
+ case __org.qemu_x-value: __org.qemu_x-Struct2
+command __org.qemu_x-command :obj-__org.qemu_x-command-arg -> __org.qemu_x-Union1
+ gen=True success_response=True
+command guest-get-time :obj-guest-get-time-arg -> int
+ gen=True success_response=True
+command guest-sync :obj-guest-sync-arg -> any
+ gen=True success_response=True
+command user_def_cmd None -> None
+ gen=True success_response=True
+command user_def_cmd1 :obj-user_def_cmd1-arg -> None
+ gen=True success_response=True
+command user_def_cmd2 :obj-user_def_cmd2-arg -> UserDefTwo
+ gen=True success_response=True
diff --git a/tests/qapi-schema/reserved-command-q.err b/tests/qapi-schema/reserved-command-q.err
new file mode 100644
index 000000000..f939e044e
--- /dev/null
+++ b/tests/qapi-schema/reserved-command-q.err
@@ -0,0 +1 @@
+tests/qapi-schema/reserved-command-q.json:5: 'command' uses invalid name 'q-unix'
diff --git a/tests/qapi-schema/reserved-command-q.exit b/tests/qapi-schema/reserved-command-q.exit
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/tests/qapi-schema/reserved-command-q.exit
@@ -0,0 +1 @@
+1
diff --git a/tests/qapi-schema/reserved-command-q.json b/tests/qapi-schema/reserved-command-q.json
new file mode 100644
index 000000000..99f8aae31
--- /dev/null
+++ b/tests/qapi-schema/reserved-command-q.json
@@ -0,0 +1,5 @@
+# C entity name collision
+# We reject names like 'q-unix', because they can collide with the mangled
+# name for 'unix' in generated C.
+{ 'command': 'unix' }
+{ 'command': 'q-unix' }
diff --git a/tests/qapi-schema/reserved-command-q.out b/tests/qapi-schema/reserved-command-q.out
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/tests/qapi-schema/reserved-command-q.out
diff --git a/tests/qapi-schema/reserved-member-has.err b/tests/qapi-schema/reserved-member-has.err
new file mode 100644
index 000000000..e75577144
--- /dev/null
+++ b/tests/qapi-schema/reserved-member-has.err
@@ -0,0 +1 @@
+tests/qapi-schema/reserved-member-has.json:5: Member of 'data' for command 'oops' uses reserved name 'has-a'
diff --git a/tests/qapi-schema/reserved-member-has.exit b/tests/qapi-schema/reserved-member-has.exit
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/tests/qapi-schema/reserved-member-has.exit
@@ -0,0 +1 @@
+1
diff --git a/tests/qapi-schema/reserved-member-has.json b/tests/qapi-schema/reserved-member-has.json
new file mode 100644
index 000000000..45b9109bd
--- /dev/null
+++ b/tests/qapi-schema/reserved-member-has.json
@@ -0,0 +1,5 @@
+# C member name collision
+# We reject names like 'has-a', because they can collide with the flag
+# for an optional 'a' in generated C.
+# TODO we could munge the optional flag name to avoid the collision.
+{ 'command': 'oops', 'data': { '*a': 'str', 'has-a': 'str' } }
diff --git a/tests/qapi-schema/reserved-member-has.out b/tests/qapi-schema/reserved-member-has.out
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/tests/qapi-schema/reserved-member-has.out
diff --git a/tests/qapi-schema/reserved-member-q.err b/tests/qapi-schema/reserved-member-q.err
new file mode 100644
index 000000000..f3d5dd781
--- /dev/null
+++ b/tests/qapi-schema/reserved-member-q.err
@@ -0,0 +1 @@
+tests/qapi-schema/reserved-member-q.json:4: Member of 'data' for struct 'Foo' uses invalid name 'q-unix'
diff --git a/tests/qapi-schema/reserved-member-q.exit b/tests/qapi-schema/reserved-member-q.exit
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/tests/qapi-schema/reserved-member-q.exit
@@ -0,0 +1 @@
+1
diff --git a/tests/qapi-schema/reserved-member-q.json b/tests/qapi-schema/reserved-member-q.json
new file mode 100644
index 000000000..62fed8fdd
--- /dev/null
+++ b/tests/qapi-schema/reserved-member-q.json
@@ -0,0 +1,4 @@
+# C member name collision
+# We reject names like 'q-unix', because they can collide with the mangled
+# name for 'unix' in generated C.
+{ 'struct': 'Foo', 'data': { 'unix':'int', 'q-unix':'bool' } }
diff --git a/tests/qapi-schema/reserved-member-q.out b/tests/qapi-schema/reserved-member-q.out
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/tests/qapi-schema/reserved-member-q.out
diff --git a/tests/qapi-schema/reserved-member-u.err b/tests/qapi-schema/reserved-member-u.err
new file mode 100644
index 000000000..87d42296c
--- /dev/null
+++ b/tests/qapi-schema/reserved-member-u.err
@@ -0,0 +1 @@
+tests/qapi-schema/reserved-member-u.json:7: Member of 'data' for struct 'Oops' uses reserved name 'u'
diff --git a/tests/qapi-schema/reserved-member-u.exit b/tests/qapi-schema/reserved-member-u.exit
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/tests/qapi-schema/reserved-member-u.exit
@@ -0,0 +1 @@
+1
diff --git a/tests/qapi-schema/reserved-member-u.json b/tests/qapi-schema/reserved-member-u.json
new file mode 100644
index 000000000..1eaf0f301
--- /dev/null
+++ b/tests/qapi-schema/reserved-member-u.json
@@ -0,0 +1,7 @@
+# Potential C member name collision
+# We reject use of 'u' as a member name, to allow it for internal use in
+# putting union branch members in a separate namespace from QMP members.
+# This is true even for non-unions, because it is possible to convert a
+# struct to flat union while remaining backwards compatible in QMP.
+# TODO - we could munge the member name to 'q_u' to avoid the collision
+{ 'struct': 'Oops', 'data': { 'u': 'str' } }
diff --git a/tests/qapi-schema/reserved-member-u.out b/tests/qapi-schema/reserved-member-u.out
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/tests/qapi-schema/reserved-member-u.out
diff --git a/tests/qapi-schema/reserved-type-kind.err b/tests/qapi-schema/reserved-type-kind.err
new file mode 100644
index 000000000..0a38efaad
--- /dev/null
+++ b/tests/qapi-schema/reserved-type-kind.err
@@ -0,0 +1 @@
+tests/qapi-schema/reserved-type-kind.json:2: enum 'UnionKind' should not end in 'Kind'
diff --git a/tests/qapi-schema/reserved-type-kind.exit b/tests/qapi-schema/reserved-type-kind.exit
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/tests/qapi-schema/reserved-type-kind.exit
@@ -0,0 +1 @@
+1
diff --git a/tests/qapi-schema/enum-union-clash.json b/tests/qapi-schema/reserved-type-kind.json
index 593282b6c..9ecaba12b 100644
--- a/tests/qapi-schema/enum-union-clash.json
+++ b/tests/qapi-schema/reserved-type-kind.json
@@ -1,4 +1,2 @@
# we reject types that would conflict with implicit union enum
{ 'enum': 'UnionKind', 'data': [ 'oops' ] }
-{ 'union': 'Union',
- 'data': { 'a': 'int' } }
diff --git a/tests/qapi-schema/reserved-type-kind.out b/tests/qapi-schema/reserved-type-kind.out
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/tests/qapi-schema/reserved-type-kind.out
diff --git a/tests/qapi-schema/reserved-type-list.err b/tests/qapi-schema/reserved-type-list.err
new file mode 100644
index 000000000..4510fa6d9
--- /dev/null
+++ b/tests/qapi-schema/reserved-type-list.err
@@ -0,0 +1 @@
+tests/qapi-schema/reserved-type-list.json:5: struct 'FooList' should not end in 'List'
diff --git a/tests/qapi-schema/reserved-type-list.exit b/tests/qapi-schema/reserved-type-list.exit
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/tests/qapi-schema/reserved-type-list.exit
@@ -0,0 +1 @@
+1
diff --git a/tests/qapi-schema/reserved-type-list.json b/tests/qapi-schema/reserved-type-list.json
new file mode 100644
index 000000000..98d53bf80
--- /dev/null
+++ b/tests/qapi-schema/reserved-type-list.json
@@ -0,0 +1,5 @@
+# Potential C name collision
+# We reserve names ending in 'List' for use by array types.
+# TODO - we could choose array names to avoid collision with user types,
+# in order to let this compile
+{ 'struct': 'FooList', 'data': { 's': 'str' } }
diff --git a/tests/qapi-schema/reserved-type-list.out b/tests/qapi-schema/reserved-type-list.out
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/tests/qapi-schema/reserved-type-list.out
diff --git a/tests/qapi-schema/returns-dict.err b/tests/qapi-schema/returns-dict.err
new file mode 100644
index 000000000..eb2d0c466
--- /dev/null
+++ b/tests/qapi-schema/returns-dict.err
@@ -0,0 +1 @@
+tests/qapi-schema/returns-dict.json:2: 'returns' for command 'oops' should be a type name
diff --git a/tests/qapi-schema/returns-dict.exit b/tests/qapi-schema/returns-dict.exit
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/tests/qapi-schema/returns-dict.exit
@@ -0,0 +1 @@
+1
diff --git a/tests/qapi-schema/returns-dict.json b/tests/qapi-schema/returns-dict.json
new file mode 100644
index 000000000..1cfef3ede
--- /dev/null
+++ b/tests/qapi-schema/returns-dict.json
@@ -0,0 +1,2 @@
+# we reject inline struct return type
+{ 'command': 'oops', 'returns': { 'a': 'str' } }
diff --git a/tests/qapi-schema/returns-dict.out b/tests/qapi-schema/returns-dict.out
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/tests/qapi-schema/returns-dict.out
diff --git a/tests/qapi-schema/returns-int.json b/tests/qapi-schema/returns-int.json
deleted file mode 100644
index 870ec6366..000000000
--- a/tests/qapi-schema/returns-int.json
+++ /dev/null
@@ -1,3 +0,0 @@
-# It is okay (although not extensible) to return a non-dictionary
-# But to make it work, the name must be in a whitelist
-{ 'command': 'guest-get-time', 'returns': 'int' }
diff --git a/tests/qapi-schema/returns-int.out b/tests/qapi-schema/returns-int.out
deleted file mode 100644
index 70b3ac5e6..000000000
--- a/tests/qapi-schema/returns-int.out
+++ /dev/null
@@ -1,3 +0,0 @@
-[OrderedDict([('command', 'guest-get-time'), ('returns', 'int')])]
-[]
-[]
diff --git a/tests/qapi-schema/returns-whitelist.err b/tests/qapi-schema/returns-whitelist.err
index a41f019a5..f47c1ee7c 100644
--- a/tests/qapi-schema/returns-whitelist.err
+++ b/tests/qapi-schema/returns-whitelist.err
@@ -1 +1 @@
-tests/qapi-schema/returns-whitelist.json:10: 'returns' for command 'no-way-this-will-get-whitelisted' cannot use built-in type 'array of int'
+tests/qapi-schema/returns-whitelist.json:10: 'returns' for command 'no-way-this-will-get-whitelisted' cannot use built-in type 'int'
diff --git a/tests/qapi-schema/struct-base-clash-deep.err b/tests/qapi-schema/struct-base-clash-deep.err
index e3e9f8d28..f7a25a3b3 100644
--- a/tests/qapi-schema/struct-base-clash-deep.err
+++ b/tests/qapi-schema/struct-base-clash-deep.err
@@ -1 +1 @@
-tests/qapi-schema/struct-base-clash-deep.json:7: Member name 'name' clashes with base 'Base'
+tests/qapi-schema/struct-base-clash-deep.json:10: Member name 'name' clashes with base 'Base'
diff --git a/tests/qapi-schema/struct-base-clash-deep.json b/tests/qapi-schema/struct-base-clash-deep.json
index 552fe9431..fa873ab5d 100644
--- a/tests/qapi-schema/struct-base-clash-deep.json
+++ b/tests/qapi-schema/struct-base-clash-deep.json
@@ -1,4 +1,7 @@
-# we check for no duplicate keys with indirect base
+# Reject attempts to duplicate QMP members
+# Here, 'name' would have to appear twice on the wire, locally and
+# indirectly for the grandparent base; the collision doesn't care that
+# one instance is optional.
{ 'struct': 'Base',
'data': { 'name': 'str' } }
{ 'struct': 'Mid',
diff --git a/tests/qapi-schema/struct-base-clash.err b/tests/qapi-schema/struct-base-clash.err
index 3ac37fb26..3a9f66b04 100644
--- a/tests/qapi-schema/struct-base-clash.err
+++ b/tests/qapi-schema/struct-base-clash.err
@@ -1 +1 @@
-tests/qapi-schema/struct-base-clash.json:4: Member name 'name' clashes with base 'Base'
+tests/qapi-schema/struct-base-clash.json:5: Member name 'name' clashes with base 'Base'
diff --git a/tests/qapi-schema/struct-base-clash.json b/tests/qapi-schema/struct-base-clash.json
index f2afc9b6f..11aec80fe 100644
--- a/tests/qapi-schema/struct-base-clash.json
+++ b/tests/qapi-schema/struct-base-clash.json
@@ -1,4 +1,5 @@
-# we check for no duplicate keys with base
+# Reject attempts to duplicate QMP members
+# Here, 'name' would have to appear twice on the wire, locally and for base.
{ 'struct': 'Base',
'data': { 'name': 'str' } }
{ 'struct': 'Sub',
diff --git a/tests/qapi-schema/struct-data-invalid.err b/tests/qapi-schema/struct-data-invalid.err
new file mode 100644
index 000000000..6644f4c2a
--- /dev/null
+++ b/tests/qapi-schema/struct-data-invalid.err
@@ -0,0 +1 @@
+tests/qapi-schema/struct-data-invalid.json:1: 'data' for struct 'foo' should be a dictionary or type name
diff --git a/tests/qapi-schema/struct-data-invalid.exit b/tests/qapi-schema/struct-data-invalid.exit
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/tests/qapi-schema/struct-data-invalid.exit
@@ -0,0 +1 @@
+1
diff --git a/tests/qapi-schema/struct-data-invalid.json b/tests/qapi-schema/struct-data-invalid.json
new file mode 100644
index 000000000..9adbc3bb6
--- /dev/null
+++ b/tests/qapi-schema/struct-data-invalid.json
@@ -0,0 +1,2 @@
+{ 'struct': 'foo',
+ 'data': false }
diff --git a/tests/qapi-schema/struct-data-invalid.out b/tests/qapi-schema/struct-data-invalid.out
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/tests/qapi-schema/struct-data-invalid.out
diff --git a/tests/qapi-schema/struct-member-invalid.err b/tests/qapi-schema/struct-member-invalid.err
new file mode 100644
index 000000000..69a326d45
--- /dev/null
+++ b/tests/qapi-schema/struct-member-invalid.err
@@ -0,0 +1 @@
+tests/qapi-schema/struct-member-invalid.json:1: Member 'a' of 'data' for struct 'foo' should be a type name
diff --git a/tests/qapi-schema/struct-member-invalid.exit b/tests/qapi-schema/struct-member-invalid.exit
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/tests/qapi-schema/struct-member-invalid.exit
@@ -0,0 +1 @@
+1
diff --git a/tests/qapi-schema/struct-member-invalid.json b/tests/qapi-schema/struct-member-invalid.json
new file mode 100644
index 000000000..8f172f7a8
--- /dev/null
+++ b/tests/qapi-schema/struct-member-invalid.json
@@ -0,0 +1,2 @@
+{ 'struct': 'foo',
+ 'data': { 'a': false } }
diff --git a/tests/qapi-schema/struct-member-invalid.out b/tests/qapi-schema/struct-member-invalid.out
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/tests/qapi-schema/struct-member-invalid.out
diff --git a/tests/qapi-schema/test-qapi.py b/tests/qapi-schema/test-qapi.py
index 634ef2d00..649677e01 100644
--- a/tests/qapi-schema/test-qapi.py
+++ b/tests/qapi-schema/test-qapi.py
@@ -15,11 +15,42 @@ from pprint import pprint
import os
import sys
-try:
- exprs = parse_schema(sys.argv[1])
-except SystemExit:
- raise
-
-pprint(exprs)
-pprint(enum_types)
-pprint(struct_types)
+
+class QAPISchemaTestVisitor(QAPISchemaVisitor):
+ def visit_enum_type(self, name, info, values, prefix):
+ print 'enum %s %s' % (name, values)
+ if prefix:
+ print ' prefix %s' % prefix
+
+ def visit_object_type(self, name, info, base, members, variants):
+ print 'object %s' % name
+ if base:
+ print ' base %s' % base.name
+ for m in members:
+ print ' member %s: %s optional=%s' % \
+ (m.name, m.type.name, m.optional)
+ self._print_variants(variants)
+
+ def visit_alternate_type(self, name, info, variants):
+ print 'alternate %s' % name
+ self._print_variants(variants)
+
+ def visit_command(self, name, info, arg_type, ret_type,
+ gen, success_response):
+ print 'command %s %s -> %s' % \
+ (name, arg_type and arg_type.name, ret_type and ret_type.name)
+ print ' gen=%s success_response=%s' % (gen, success_response)
+
+ def visit_event(self, name, info, arg_type):
+ print 'event %s %s' % (name, arg_type and arg_type.name)
+
+ @staticmethod
+ def _print_variants(variants):
+ if variants:
+ if variants.tag_name:
+ print ' tag %s' % variants.tag_name
+ for v in variants.variants:
+ print ' case %s: %s' % (v.name, v.type.name)
+
+schema = QAPISchema(sys.argv[1])
+schema.visit(QAPISchemaTestVisitor())
diff --git a/tests/qapi-schema/type-bypass-no-gen.err b/tests/qapi-schema/type-bypass-no-gen.err
deleted file mode 100644
index 20cef0a8a..000000000
--- a/tests/qapi-schema/type-bypass-no-gen.err
+++ /dev/null
@@ -1 +0,0 @@
-tests/qapi-schema/type-bypass-no-gen.json:2: Member 'arg' of 'data' for command 'unsafe' uses '**' but did not request 'gen':false
diff --git a/tests/qapi-schema/type-bypass-no-gen.json b/tests/qapi-schema/type-bypass-no-gen.json
deleted file mode 100644
index 4feae3719..000000000
--- a/tests/qapi-schema/type-bypass-no-gen.json
+++ /dev/null
@@ -1,2 +0,0 @@
-# type bypass only works with 'gen':false
-{ 'command': 'unsafe', 'data': { 'arg': '**' }, 'returns': '**' }
diff --git a/tests/qapi-schema/type-bypass.json b/tests/qapi-schema/type-bypass.json
deleted file mode 100644
index 48b213783..000000000
--- a/tests/qapi-schema/type-bypass.json
+++ /dev/null
@@ -1,2 +0,0 @@
-# Use of 'gen':false allows bypassing type system
-{ 'command': 'unsafe', 'data': { 'arg': '**' }, 'returns': '**', 'gen': false }
diff --git a/tests/qapi-schema/type-bypass.out b/tests/qapi-schema/type-bypass.out
deleted file mode 100644
index eaf20f834..000000000
--- a/tests/qapi-schema/type-bypass.out
+++ /dev/null
@@ -1,3 +0,0 @@
-[OrderedDict([('command', 'unsafe'), ('data', OrderedDict([('arg', '**')])), ('returns', '**'), ('gen', False)])]
-[]
-[]
diff --git a/tests/qapi-schema/union-base-no-discriminator.err b/tests/qapi-schema/union-base-no-discriminator.err
index fc8b79c45..8b7a24260 100644
--- a/tests/qapi-schema/union-base-no-discriminator.err
+++ b/tests/qapi-schema/union-base-no-discriminator.err
@@ -1 +1 @@
-tests/qapi-schema/union-base-no-discriminator.json:11: Union 'TestUnion' requires a discriminator to go along with base
+tests/qapi-schema/union-base-no-discriminator.json:11: Simple union 'TestUnion' must not have a base
diff --git a/tests/qapi-schema/union-clash-branches.err b/tests/qapi-schema/union-clash-branches.err
new file mode 100644
index 000000000..005c48d90
--- /dev/null
+++ b/tests/qapi-schema/union-clash-branches.err
@@ -0,0 +1 @@
+tests/qapi-schema/union-clash-branches.json:4: Union 'TestUnion' member 'a_b' clashes with 'a-b'
diff --git a/tests/qapi-schema/union-clash-branches.exit b/tests/qapi-schema/union-clash-branches.exit
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/tests/qapi-schema/union-clash-branches.exit
@@ -0,0 +1 @@
+1
diff --git a/tests/qapi-schema/union-clash-branches.json b/tests/qapi-schema/union-clash-branches.json
new file mode 100644
index 000000000..31d135fb1
--- /dev/null
+++ b/tests/qapi-schema/union-clash-branches.json
@@ -0,0 +1,5 @@
+# Union branch name collision
+# Reject a union that would result in a collision in generated C names (this
+# would try to generate two enum values 'TEST_UNION_KIND_A_B').
+{ 'union': 'TestUnion',
+ 'data': { 'a-b': 'int', 'a_b': 'str' } }
diff --git a/tests/qapi-schema/union-clash-branches.out b/tests/qapi-schema/union-clash-branches.out
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/tests/qapi-schema/union-clash-branches.out
diff --git a/tests/qapi-schema/union-clash-data.err b/tests/qapi-schema/union-clash-data.err
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/tests/qapi-schema/union-clash-data.err
diff --git a/tests/qapi-schema/returns-int.exit b/tests/qapi-schema/union-clash-data.exit
index 573541ac9..573541ac9 100644
--- a/tests/qapi-schema/returns-int.exit
+++ b/tests/qapi-schema/union-clash-data.exit
diff --git a/tests/qapi-schema/union-clash-data.json b/tests/qapi-schema/union-clash-data.json
new file mode 100644
index 000000000..7308e69f9
--- /dev/null
+++ b/tests/qapi-schema/union-clash-data.json
@@ -0,0 +1,7 @@
+# Union branch 'data'
+# FIXME: this parses, but then fails to compile due to a duplicate 'data'
+# (one from the branch name, another as a filler to avoid an empty union).
+# we should either detect the collision at parse time, or change the
+# generated struct to allow this to compile.
+{ 'union': 'TestUnion',
+ 'data': { 'data': 'int' } }
diff --git a/tests/qapi-schema/union-clash-data.out b/tests/qapi-schema/union-clash-data.out
new file mode 100644
index 000000000..6277239d4
--- /dev/null
+++ b/tests/qapi-schema/union-clash-data.out
@@ -0,0 +1,6 @@
+object :empty
+object :obj-int-wrapper
+ member data: int optional=False
+object TestUnion
+ case data: :obj-int-wrapper
+enum TestUnionKind ['data']
diff --git a/tests/qapi-schema/union-clash-type.err b/tests/qapi-schema/union-clash-type.err
new file mode 100644
index 000000000..a5dead128
--- /dev/null
+++ b/tests/qapi-schema/union-clash-type.err
@@ -0,0 +1 @@
+tests/qapi-schema/union-clash-type.json:8: Union 'TestUnion' member 'kind' clashes with '(automatic)'
diff --git a/tests/qapi-schema/union-clash-type.exit b/tests/qapi-schema/union-clash-type.exit
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/tests/qapi-schema/union-clash-type.exit
@@ -0,0 +1 @@
+1
diff --git a/tests/qapi-schema/union-clash-type.json b/tests/qapi-schema/union-clash-type.json
new file mode 100644
index 000000000..cfc256b04
--- /dev/null
+++ b/tests/qapi-schema/union-clash-type.json
@@ -0,0 +1,9 @@
+# Union branch 'type'
+# Reject this, because we would have a clash in generated C, between the
+# simple union's implicit tag member 'kind' and the branch name 'kind'
+# within the union.
+# TODO: Even when the generated C is switched to use 'type' rather than
+# 'kind', to match the QMP spelling, the collision should still be detected.
+# Or, we could munge the branch name to allow compilation.
+{ 'union': 'TestUnion',
+ 'data': { 'kind': 'int', 'type': 'str' } }
diff --git a/tests/qapi-schema/union-clash-type.out b/tests/qapi-schema/union-clash-type.out
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/tests/qapi-schema/union-clash-type.out
diff --git a/tests/qapi-schema/union-empty.err b/tests/qapi-schema/union-empty.err
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/tests/qapi-schema/union-empty.err
diff --git a/tests/qapi-schema/type-bypass.exit b/tests/qapi-schema/union-empty.exit
index 573541ac9..573541ac9 100644
--- a/tests/qapi-schema/type-bypass.exit
+++ b/tests/qapi-schema/union-empty.exit
diff --git a/tests/qapi-schema/union-empty.json b/tests/qapi-schema/union-empty.json
new file mode 100644
index 000000000..178500711
--- /dev/null
+++ b/tests/qapi-schema/union-empty.json
@@ -0,0 +1,2 @@
+# FIXME - unions should not be empty
+{ 'union': 'Union', 'data': { } }
diff --git a/tests/qapi-schema/union-empty.out b/tests/qapi-schema/union-empty.out
new file mode 100644
index 000000000..8b5a7bf58
--- /dev/null
+++ b/tests/qapi-schema/union-empty.out
@@ -0,0 +1,3 @@
+object :empty
+object Union
+enum UnionKind []
diff --git a/tests/qapi-schema/union-invalid-base.err b/tests/qapi-schema/union-invalid-base.err
index 9f637963e..03d7b97a9 100644
--- a/tests/qapi-schema/union-invalid-base.err
+++ b/tests/qapi-schema/union-invalid-base.err
@@ -1 +1 @@
-tests/qapi-schema/union-invalid-base.json:8: Base 'int' is not a valid struct
+tests/qapi-schema/union-invalid-base.json:8: 'base' for union 'TestUnion' cannot use built-in type 'int'
diff --git a/tests/qemu-iotests/017.out b/tests/qemu-iotests/017.out
index 7c409fc5b..8fc924194 100644
--- a/tests/qemu-iotests/017.out
+++ b/tests/qemu-iotests/017.out
@@ -269,7 +269,7 @@ wrote 65536/65536 bytes at offset 4295032832
No errors were found on the image.
Creating test image with backing file
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=6442450944 backing_file='TEST_DIR/t.IMGFMT.base'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=6442450944 backing_file=TEST_DIR/t.IMGFMT.base
Filling test image
=== IO: pattern 1
diff --git a/tests/qemu-iotests/018.out b/tests/qemu-iotests/018.out
index 39a6011d2..d66bd6343 100644
--- a/tests/qemu-iotests/018.out
+++ b/tests/qemu-iotests/018.out
@@ -269,7 +269,7 @@ wrote 65536/65536 bytes at offset 4295032832
No errors were found on the image.
Creating test image with backing file
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=6442450944 backing_file='TEST_DIR/t.IMGFMT.base'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=6442450944 backing_file=TEST_DIR/t.IMGFMT.base
Filling test image
=== IO: pattern 1
diff --git a/tests/qemu-iotests/019.out b/tests/qemu-iotests/019.out
index 4695b972d..615450a53 100644
--- a/tests/qemu-iotests/019.out
+++ b/tests/qemu-iotests/019.out
@@ -269,7 +269,7 @@ wrote 65536/65536 bytes at offset 4296015872
No errors were found on the image.
Creating test image with backing file
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=6442450944 backing_file='TEST_DIR/t.IMGFMT.base'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=6442450944 backing_file=TEST_DIR/t.IMGFMT.base
Filling test image
=== IO: pattern 43
diff --git a/tests/qemu-iotests/020.out b/tests/qemu-iotests/020.out
index 71aab1c74..134aa293e 100644
--- a/tests/qemu-iotests/020.out
+++ b/tests/qemu-iotests/020.out
@@ -269,7 +269,7 @@ wrote 65536/65536 bytes at offset 4295032832
No errors were found on the image.
Creating test image with backing file
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=6442450944 backing_file='TEST_DIR/t.IMGFMT.base'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=6442450944 backing_file=TEST_DIR/t.IMGFMT.base
Filling test image
=== IO: pattern 1
diff --git a/tests/qemu-iotests/024.out b/tests/qemu-iotests/024.out
index 521d46942..9b9ef3a34 100644
--- a/tests/qemu-iotests/024.out
+++ b/tests/qemu-iotests/024.out
@@ -33,7 +33,7 @@ wrote 131072/131072 bytes at offset 786432
128 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
Creating COW image
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=1073741824 backing_file='TEST_DIR/t.IMGFMT.base_old'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=1073741824 backing_file=TEST_DIR/t.IMGFMT.base_old
=== IO: pattern 0x33
wrote 262144/262144 bytes at offset 0
256 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
diff --git a/tests/qemu-iotests/028.out b/tests/qemu-iotests/028.out
index 5db167ce7..29c9972e2 100644
--- a/tests/qemu-iotests/028.out
+++ b/tests/qemu-iotests/028.out
@@ -70,7 +70,7 @@ wrote 512/512 bytes at offset 3221225984
No errors were found on the image.
Creating test image with backing file
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=4294968832 backing_file='TEST_DIR/t.IMGFMT.base'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=4294968832 backing_file=TEST_DIR/t.IMGFMT.base
Filling test image
=== IO: pattern 196
@@ -468,7 +468,7 @@ No errors were found on the image.
block-backup
-Formatting 'TEST_DIR/t.IMGFMT.copy', fmt=IMGFMT size=4294968832 backing_file='TEST_DIR/t.IMGFMT.base' backing_fmt='IMGFMT'
+Formatting 'TEST_DIR/t.IMGFMT.copy', fmt=IMGFMT size=4294968832 backing_file=TEST_DIR/t.IMGFMT.base backing_fmt=IMGFMT
(qemu)
(qemu) iininfinfoinfo info binfo blinfo bloinfo blocinfo blockinfo block-info block-jinfo block-joinfo block-jobinfo block-jobs
Type backup, device disk: Completed 0 of 4294968832 bytes, speed limit 0 bytes/s
diff --git a/tests/qemu-iotests/030 b/tests/qemu-iotests/030
index 952a524ec..32469efd7 100755
--- a/tests/qemu-iotests/030
+++ b/tests/qemu-iotests/030
@@ -245,6 +245,7 @@ class TestEIO(TestErrors):
while not completed:
for event in self.vm.get_qmp_events(wait=True):
if event['event'] == 'BLOCK_JOB_ERROR':
+ error = True
self.assert_qmp(event, 'data/device', 'drive0')
self.assert_qmp(event, 'data/operation', 'read')
@@ -257,9 +258,11 @@ class TestEIO(TestErrors):
self.assert_qmp(result, 'return', {})
result = self.vm.qmp('query-block-jobs')
+ if result == {'return': []}:
+ # Race; likely already finished. Check.
+ continue
self.assert_qmp(result, 'return[0]/paused', False)
self.assert_qmp(result, 'return[0]/io-status', 'ok')
- error = True
elif event['event'] == 'BLOCK_JOB_COMPLETED':
self.assertTrue(error, 'job completed unexpectedly')
self.assert_qmp(event, 'data/type', 'stream')
diff --git a/tests/qemu-iotests/034.out b/tests/qemu-iotests/034.out
index d12daf206..34fda80c8 100644
--- a/tests/qemu-iotests/034.out
+++ b/tests/qemu-iotests/034.out
@@ -4,7 +4,7 @@ QA output created by 034
Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728
wrote 1048576/1048576 bytes at offset 0
1 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=6442450944 backing_file='TEST_DIR/t.IMGFMT.base'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=6442450944 backing_file=TEST_DIR/t.IMGFMT.base
== zero write with backing file ==
wrote 196608/196608 bytes at offset 65536
diff --git a/tests/qemu-iotests/037.out b/tests/qemu-iotests/037.out
index dc40a021a..55b30fdc6 100644
--- a/tests/qemu-iotests/037.out
+++ b/tests/qemu-iotests/037.out
@@ -514,7 +514,7 @@ wrote 512/512 bytes at offset 130048
512 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
wrote 512/512 bytes at offset 130560
512 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=6442450944 backing_file='TEST_DIR/t.IMGFMT.base'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=6442450944 backing_file=TEST_DIR/t.IMGFMT.base
== COW in a single cluster ==
wrote 2048/2048 bytes at offset 0
diff --git a/tests/qemu-iotests/038.out b/tests/qemu-iotests/038.out
index e1a7e9441..ecb656e08 100644
--- a/tests/qemu-iotests/038.out
+++ b/tests/qemu-iotests/038.out
@@ -514,7 +514,7 @@ wrote 65536/65536 bytes at offset 16646144
64 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
wrote 65536/65536 bytes at offset 16711680
64 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=6442450944 backing_file='TEST_DIR/t.IMGFMT.base'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=6442450944 backing_file=TEST_DIR/t.IMGFMT.base
== Some concurrent requests touching the same cluster ==
wrote 65536/65536 bytes at offset XXX
diff --git a/tests/qemu-iotests/039 b/tests/qemu-iotests/039
index 859705f84..9e9b379ba 100755
--- a/tests/qemu-iotests/039
+++ b/tests/qemu-iotests/039
@@ -47,13 +47,6 @@ _supported_os Linux
_default_cache_mode "writethrough"
_supported_cache_modes "writethrough"
-_subshell_exec()
-{
- # Executing crashing commands in a subshell prevents information like the
- # "Killed" line from being lost
- (exec "$@")
-}
-
size=128M
echo
@@ -74,8 +67,8 @@ echo "== Creating a dirty image file =="
IMGOPTS="compat=1.1,lazy_refcounts=on"
_make_test_img $size
-_subshell_exec $QEMU_IO -c "write -P 0x5a 0 512" \
- -c "sigraise $(kill -l KILL)" "$TEST_IMG" 2>&1 \
+$QEMU_IO -c "write -P 0x5a 0 512" \
+ -c "sigraise $(kill -l KILL)" "$TEST_IMG" 2>&1 \
| _filter_qemu_io
# The dirty bit must be set
@@ -109,8 +102,8 @@ echo "== Opening a dirty image read/write should repair it =="
IMGOPTS="compat=1.1,lazy_refcounts=on"
_make_test_img $size
-_subshell_exec $QEMU_IO -c "write -P 0x5a 0 512" \
- -c "sigraise $(kill -l KILL)" "$TEST_IMG" 2>&1 \
+$QEMU_IO -c "write -P 0x5a 0 512" \
+ -c "sigraise $(kill -l KILL)" "$TEST_IMG" 2>&1 \
| _filter_qemu_io
# The dirty bit must be set
@@ -127,8 +120,8 @@ echo "== Creating an image file with lazy_refcounts=off =="
IMGOPTS="compat=1.1,lazy_refcounts=off"
_make_test_img $size
-_subshell_exec $QEMU_IO -c "write -P 0x5a 0 512" \
- -c "sigraise $(kill -l KILL)" "$TEST_IMG" 2>&1 \
+$QEMU_IO -c "write -P 0x5a 0 512" \
+ -c "sigraise $(kill -l KILL)" "$TEST_IMG" 2>&1 \
| _filter_qemu_io
# The dirty bit must not be set since lazy_refcounts=off
@@ -154,6 +147,33 @@ $PYTHON qcow2.py "$TEST_IMG".base dump-header | grep incompatible_features
_check_test_img
TEST_IMG="$TEST_IMG".base _check_test_img
+echo
+echo "== Changing lazy_refcounts setting at runtime =="
+
+IMGOPTS="compat=1.1,lazy_refcounts=off"
+_make_test_img $size
+
+$QEMU_IO -c "reopen -o lazy-refcounts=on" \
+ -c "write -P 0x5a 0 512" \
+ -c "sigraise $(kill -l KILL)" "$TEST_IMG" 2>&1 \
+ | _filter_qemu_io
+
+# The dirty bit must be set
+$PYTHON qcow2.py "$TEST_IMG" dump-header | grep incompatible_features
+_check_test_img
+
+IMGOPTS="compat=1.1,lazy_refcounts=on"
+_make_test_img $size
+
+$QEMU_IO -c "reopen -o lazy-refcounts=off" \
+ -c "write -P 0x5a 0 512" \
+ -c "sigraise $(kill -l KILL)" "$TEST_IMG" 2>&1 \
+ | _filter_qemu_io
+
+# The dirty bit must not be set
+$PYTHON qcow2.py "$TEST_IMG" dump-header | grep incompatible_features
+_check_test_img
+
# success, all done
echo "*** done"
diff --git a/tests/qemu-iotests/039.out b/tests/qemu-iotests/039.out
index d09751f9c..32c884694 100644
--- a/tests/qemu-iotests/039.out
+++ b/tests/qemu-iotests/039.out
@@ -11,7 +11,11 @@ No errors were found on the image.
Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728
wrote 512/512 bytes at offset 0
512 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
-./039: Killed ( exec "$@" )
+./common.config: Killed ( if [ "${VALGRIND_QEMU}" == "y" ]; then
+ exec valgrind --log-file="${VALGRIND_LOGFILE}" --error-exitcode=99 "$QEMU_IO_PROG" $QEMU_IO_OPTIONS "$@";
+else
+ exec "$QEMU_IO_PROG" $QEMU_IO_OPTIONS "$@";
+fi )
incompatible_features 0x1
ERROR cluster 5 refcount=0 reference=1
ERROR OFLAG_COPIED data cluster: l2_entry=8000000000050000 refcount=0
@@ -46,7 +50,11 @@ read 512/512 bytes at offset 0
Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728
wrote 512/512 bytes at offset 0
512 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
-./039: Killed ( exec "$@" )
+./common.config: Killed ( if [ "${VALGRIND_QEMU}" == "y" ]; then
+ exec valgrind --log-file="${VALGRIND_LOGFILE}" --error-exitcode=99 "$QEMU_IO_PROG" $QEMU_IO_OPTIONS "$@";
+else
+ exec "$QEMU_IO_PROG" $QEMU_IO_OPTIONS "$@";
+fi )
incompatible_features 0x1
ERROR cluster 5 refcount=0 reference=1
Rebuilding refcount structure
@@ -60,13 +68,17 @@ incompatible_features 0x0
Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728
wrote 512/512 bytes at offset 0
512 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
-./039: Killed ( exec "$@" )
+./common.config: Killed ( if [ "${VALGRIND_QEMU}" == "y" ]; then
+ exec valgrind --log-file="${VALGRIND_LOGFILE}" --error-exitcode=99 "$QEMU_IO_PROG" $QEMU_IO_OPTIONS "$@";
+else
+ exec "$QEMU_IO_PROG" $QEMU_IO_OPTIONS "$@";
+fi )
incompatible_features 0x0
No errors were found on the image.
== Committing to a backing file with lazy_refcounts=on ==
Formatting 'TEST_DIR/t.IMGFMT.base', fmt=IMGFMT size=134217728
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 backing_file='TEST_DIR/t.IMGFMT.base'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 backing_file=TEST_DIR/t.IMGFMT.base
wrote 512/512 bytes at offset 0
512 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
Image committed.
@@ -74,4 +86,30 @@ incompatible_features 0x0
incompatible_features 0x0
No errors were found on the image.
No errors were found on the image.
+
+== Changing lazy_refcounts setting at runtime ==
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728
+wrote 512/512 bytes at offset 0
+512 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
+./common.config: Killed ( if [ "${VALGRIND_QEMU}" == "y" ]; then
+ exec valgrind --log-file="${VALGRIND_LOGFILE}" --error-exitcode=99 "$QEMU_IO_PROG" $QEMU_IO_OPTIONS "$@";
+else
+ exec "$QEMU_IO_PROG" $QEMU_IO_OPTIONS "$@";
+fi )
+incompatible_features 0x1
+ERROR cluster 5 refcount=0 reference=1
+ERROR OFLAG_COPIED data cluster: l2_entry=8000000000050000 refcount=0
+
+2 errors were found on the image.
+Data may be corrupted, or further writes to the image may corrupt it.
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728
+wrote 512/512 bytes at offset 0
+512 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
+./common.config: Killed ( if [ "${VALGRIND_QEMU}" == "y" ]; then
+ exec valgrind --log-file="${VALGRIND_LOGFILE}" --error-exitcode=99 "$QEMU_IO_PROG" $QEMU_IO_OPTIONS "$@";
+else
+ exec "$QEMU_IO_PROG" $QEMU_IO_OPTIONS "$@";
+fi )
+incompatible_features 0x0
+No errors were found on the image.
*** done
diff --git a/tests/qemu-iotests/040 b/tests/qemu-iotests/040
index ea2f98e51..5bdaf3d48 100755
--- a/tests/qemu-iotests/040
+++ b/tests/qemu-iotests/040
@@ -41,6 +41,7 @@ class ImageCommitTestCase(iotests.QMPTestCase):
while not completed:
for event in self.vm.get_qmp_events(wait=True):
if event['event'] == 'BLOCK_JOB_COMPLETED':
+ self.assert_qmp_absent(event, 'data/error')
self.assert_qmp(event, 'data/type', 'commit')
self.assert_qmp(event, 'data/device', 'drive0')
self.assert_qmp(event, 'data/offset', event['data']['len'])
@@ -251,5 +252,34 @@ class TestSetSpeed(ImageCommitTestCase):
class TestActiveZeroLengthImage(TestSingleDrive):
image_len = 0
+class TestReopenOverlay(ImageCommitTestCase):
+ image_len = 1024 * 1024
+ img0 = os.path.join(iotests.test_dir, '0.img')
+ img1 = os.path.join(iotests.test_dir, '1.img')
+ img2 = os.path.join(iotests.test_dir, '2.img')
+ img3 = os.path.join(iotests.test_dir, '3.img')
+
+ def setUp(self):
+ iotests.create_image(self.img0, self.image_len)
+ qemu_img('create', '-f', iotests.imgfmt, '-o', 'backing_file=%s' % self.img0, self.img1)
+ qemu_img('create', '-f', iotests.imgfmt, '-o', 'backing_file=%s' % self.img1, self.img2)
+ qemu_img('create', '-f', iotests.imgfmt, '-o', 'backing_file=%s' % self.img2, self.img3)
+ qemu_io('-f', iotests.imgfmt, '-c', 'write -P 0xab 0 128K', self.img1)
+ self.vm = iotests.VM().add_drive(self.img3)
+ self.vm.launch()
+
+ def tearDown(self):
+ self.vm.shutdown()
+ os.remove(self.img0)
+ os.remove(self.img1)
+ os.remove(self.img2)
+ os.remove(self.img3)
+
+ # This tests what happens when the overlay image of the 'top' node
+ # needs to be reopened in read-write mode in order to update the
+ # backing image string.
+ def test_reopen_overlay(self):
+ self.run_commit_test(self.img1, self.img0)
+
if __name__ == '__main__':
iotests.main(supported_fmts=['qcow2', 'qed'])
diff --git a/tests/qemu-iotests/040.out b/tests/qemu-iotests/040.out
index 42314e9c0..4fd1c2dcd 100644
--- a/tests/qemu-iotests/040.out
+++ b/tests/qemu-iotests/040.out
@@ -1,5 +1,5 @@
-........................
+.........................
----------------------------------------------------------------------
-Ran 24 tests
+Ran 25 tests
OK
diff --git a/tests/qemu-iotests/041 b/tests/qemu-iotests/041
index 3d46ed705..05b5962ce 100755
--- a/tests/qemu-iotests/041
+++ b/tests/qemu-iotests/041
@@ -42,6 +42,8 @@ class TestSingleDrive(iotests.QMPTestCase):
iotests.create_image(backing_img, self.image_len)
qemu_img('create', '-f', iotests.imgfmt, '-o', 'backing_file=%s' % backing_img, test_img)
self.vm = iotests.VM().add_drive(test_img)
+ if iotests.qemu_default_machine == 'pc':
+ self.vm.add_drive(None, 'media=cdrom', 'ide')
self.vm.launch()
def tearDown(self):
@@ -167,8 +169,11 @@ class TestSingleDrive(iotests.QMPTestCase):
'target image does not match source after mirroring')
def test_medium_not_found(self):
- result = self.vm.qmp('drive-mirror', device='ide1-cd0', sync='full',
- target=target_img)
+ if iotests.qemu_default_machine != 'pc':
+ return
+
+ result = self.vm.qmp('drive-mirror', device='drive1', # CD-ROM
+ sync='full', target=target_img)
self.assert_qmp(result, 'error/class', 'GenericError')
def test_image_not_found(self):
@@ -707,6 +712,9 @@ class TestRepairQuorum(iotests.QMPTestCase):
def setUp(self):
self.vm = iotests.VM()
+ if iotests.qemu_default_machine == 'pc':
+ self.vm.add_drive(None, 'media=cdrom', 'ide')
+
# Add each individual quorum images
for i in self.IMAGES:
qemu_img('create', '-f', iotests.imgfmt, i,
@@ -772,7 +780,7 @@ class TestRepairQuorum(iotests.QMPTestCase):
# here we check that the last registered quorum file has not been
# swapped out and unref
result = self.vm.qmp('query-named-block-nodes')
- self.assert_qmp(result, 'return[0]/file', quorum_img3)
+ self.assert_qmp(result, 'return[1]/file', quorum_img3)
self.vm.shutdown()
def test_cancel_after_ready(self):
@@ -791,7 +799,7 @@ class TestRepairQuorum(iotests.QMPTestCase):
result = self.vm.qmp('query-named-block-nodes')
# here we check that the last registered quorum file has not been
# swapped out and unref
- self.assert_qmp(result, 'return[0]/file', quorum_img3)
+ self.assert_qmp(result, 'return[1]/file', quorum_img3)
self.vm.shutdown()
self.assertTrue(iotests.compare_images(quorum_img2, quorum_repair_img),
'target image does not match source after mirroring')
@@ -831,7 +839,11 @@ class TestRepairQuorum(iotests.QMPTestCase):
if not self.has_quorum():
return
- result = self.vm.qmp('drive-mirror', device='ide1-cd0', sync='full',
+ if iotests.qemu_default_machine != 'pc':
+ return
+
+ result = self.vm.qmp('drive-mirror', device='drive0', # CD-ROM
+ sync='full',
node_name='repair0',
replaces='img1',
target=quorum_repair_img, format=iotests.imgfmt)
@@ -877,7 +889,7 @@ class TestRepairQuorum(iotests.QMPTestCase):
target=quorum_repair_img, format=iotests.imgfmt)
self.assert_qmp(result, 'error/class', 'GenericError')
- def test_unexistant_replaces(self):
+ def test_nonexistent_replaces(self):
if not self.has_quorum():
return
diff --git a/tests/qemu-iotests/043.out b/tests/qemu-iotests/043.out
index 012cc008e..33f8cc37d 100644
--- a/tests/qemu-iotests/043.out
+++ b/tests/qemu-iotests/043.out
@@ -4,20 +4,20 @@ Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728
== backing file references self ==
qemu-img: Backing file 'TEST_DIR/t.IMGFMT' creates an infinite loop.
Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 backing_file='TEST_DIR/t.IMGFMT.base'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 backing_file=TEST_DIR/t.IMGFMT.base
== parent references self ==
qemu-img: Backing file 'TEST_DIR/t.IMGFMT' creates an infinite loop.
Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 backing_file='TEST_DIR/t.IMGFMT.1.base'
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 backing_file='TEST_DIR/t.IMGFMT.2.base'
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 backing_file='TEST_DIR/t.IMGFMT.3.base'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 backing_file=TEST_DIR/t.IMGFMT.1.base
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 backing_file=TEST_DIR/t.IMGFMT.2.base
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 backing_file=TEST_DIR/t.IMGFMT.3.base
== ancestor references another ancestor ==
qemu-img: Backing file 'TEST_DIR/t.IMGFMT.2.base' creates an infinite loop.
Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 backing_file='TEST_DIR/t.IMGFMT.1.base'
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 backing_file='TEST_DIR/t.IMGFMT.2.base'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 backing_file=TEST_DIR/t.IMGFMT.1.base
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 backing_file=TEST_DIR/t.IMGFMT.2.base
== finite chain of length 3 (human) ==
image: TEST_DIR/t.IMGFMT
diff --git a/tests/qemu-iotests/046.out b/tests/qemu-iotests/046.out
index 9d18af53a..ca2c7404a 100644
--- a/tests/qemu-iotests/046.out
+++ b/tests/qemu-iotests/046.out
@@ -66,7 +66,7 @@ wrote 65536/65536 bytes at offset 1966080
64 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
wrote 65536/65536 bytes at offset 2031616
64 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=6442450944 backing_file='TEST_DIR/t.IMGFMT.base'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=6442450944 backing_file=TEST_DIR/t.IMGFMT.base
== Some concurrent requests touching the same cluster ==
blkdebug: Suspended request 'A'
diff --git a/tests/qemu-iotests/049.out b/tests/qemu-iotests/049.out
index 9f93666c5..a2b670395 100644
--- a/tests/qemu-iotests/049.out
+++ b/tests/qemu-iotests/049.out
@@ -95,17 +95,15 @@ qemu-img create -f qcow2 TEST_DIR/t.qcow2 -- -1024
qemu-img: Image size must be less than 8 EiB!
qemu-img create -f qcow2 -o size=-1024 TEST_DIR/t.qcow2
-qemu-img: qcow2 doesn't support shrinking images yet
-qemu-img: TEST_DIR/t.qcow2: Could not resize image: Operation not supported
-Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=-1024 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
+qemu-img: Parameter 'size' expects a non-negative number below 2^64
+qemu-img: TEST_DIR/t.qcow2: Invalid options for file format 'qcow2'
qemu-img create -f qcow2 TEST_DIR/t.qcow2 -- -1k
qemu-img: Image size must be less than 8 EiB!
qemu-img create -f qcow2 -o size=-1k TEST_DIR/t.qcow2
-qemu-img: qcow2 doesn't support shrinking images yet
-qemu-img: TEST_DIR/t.qcow2: Could not resize image: Operation not supported
-Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=-1024 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
+qemu-img: Parameter 'size' expects a non-negative number below 2^64
+qemu-img: TEST_DIR/t.qcow2: Invalid options for file format 'qcow2'
qemu-img create -f qcow2 TEST_DIR/t.qcow2 -- 1kilobyte
qemu-img: Invalid image size specified! You may use k, M, G, T, P or E suffixes for
@@ -120,6 +118,7 @@ qemu-img: kilobytes, megabytes, gigabytes, terabytes, petabytes and exabytes.
qemu-img create -f qcow2 -o size=foobar TEST_DIR/t.qcow2
qemu-img: Parameter 'size' expects a size
+You may use k, M, G or T suffixes for kilobytes, megabytes, gigabytes and terabytes.
qemu-img: TEST_DIR/t.qcow2: Invalid options for file format 'qcow2'
== Check correct interpretation of suffixes for cluster size ==
@@ -157,30 +156,30 @@ Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 encryption=off cluster_si
== Check compat level option ==
qemu-img create -f qcow2 -o compat=0.10 TEST_DIR/t.qcow2 64M
-Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 compat='0.10' encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
+Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 compat=0.10 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
qemu-img create -f qcow2 -o compat=1.1 TEST_DIR/t.qcow2 64M
-Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 compat='1.1' encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
+Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 compat=1.1 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
qemu-img create -f qcow2 -o compat=0.42 TEST_DIR/t.qcow2 64M
qemu-img: TEST_DIR/t.qcow2: Invalid compatibility level: '0.42'
-Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 compat='0.42' encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
+Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 compat=0.42 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
qemu-img create -f qcow2 -o compat=foobar TEST_DIR/t.qcow2 64M
qemu-img: TEST_DIR/t.qcow2: Invalid compatibility level: 'foobar'
-Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 compat='foobar' encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
+Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 compat=foobar encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
== Check preallocation option ==
qemu-img create -f qcow2 -o preallocation=off TEST_DIR/t.qcow2 64M
-Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 encryption=off cluster_size=65536 preallocation='off' lazy_refcounts=off refcount_bits=16
+Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 encryption=off cluster_size=65536 preallocation=off lazy_refcounts=off refcount_bits=16
qemu-img create -f qcow2 -o preallocation=metadata TEST_DIR/t.qcow2 64M
-Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 encryption=off cluster_size=65536 preallocation='metadata' lazy_refcounts=off refcount_bits=16
+Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 encryption=off cluster_size=65536 preallocation=metadata lazy_refcounts=off refcount_bits=16
qemu-img create -f qcow2 -o preallocation=1234 TEST_DIR/t.qcow2 64M
qemu-img: TEST_DIR/t.qcow2: invalid parameter value: 1234
-Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 encryption=off cluster_size=65536 preallocation='1234' lazy_refcounts=off refcount_bits=16
+Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 encryption=off cluster_size=65536 preallocation=1234 lazy_refcounts=off refcount_bits=16
== Check encryption option ==
@@ -199,16 +198,16 @@ Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 encryption=on cluster_siz
== Check lazy_refcounts option (only with v3) ==
qemu-img create -f qcow2 -o compat=1.1,lazy_refcounts=off TEST_DIR/t.qcow2 64M
-Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 compat='1.1' encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
+Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 compat=1.1 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
qemu-img create -f qcow2 -o compat=1.1,lazy_refcounts=on TEST_DIR/t.qcow2 64M
-Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 compat='1.1' encryption=off cluster_size=65536 lazy_refcounts=on refcount_bits=16
+Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 compat=1.1 encryption=off cluster_size=65536 lazy_refcounts=on refcount_bits=16
qemu-img create -f qcow2 -o compat=0.10,lazy_refcounts=off TEST_DIR/t.qcow2 64M
-Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 compat='0.10' encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
+Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 compat=0.10 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
qemu-img create -f qcow2 -o compat=0.10,lazy_refcounts=on TEST_DIR/t.qcow2 64M
qemu-img: TEST_DIR/t.qcow2: Lazy refcounts only supported with compatibility level 1.1 and above (use compat=1.1 or greater)
-Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 compat='0.10' encryption=off cluster_size=65536 lazy_refcounts=on refcount_bits=16
+Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 compat=0.10 encryption=off cluster_size=65536 lazy_refcounts=on refcount_bits=16
*** done
diff --git a/tests/qemu-iotests/050.out b/tests/qemu-iotests/050.out
index a6cb2e686..397cf7f39 100644
--- a/tests/qemu-iotests/050.out
+++ b/tests/qemu-iotests/050.out
@@ -7,7 +7,7 @@ wrote 1048576/1048576 bytes at offset 0
Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=10485760
wrote 1048576/1048576 bytes at offset 0
1 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=10485760 backing_file='TEST_DIR/t.IMGFMT.old'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=10485760 backing_file=TEST_DIR/t.IMGFMT.old
wrote 1048576/1048576 bytes at offset 0
1 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
diff --git a/tests/qemu-iotests/051 b/tests/qemu-iotests/051
index 4a8055b67..17dbf04af 100755
--- a/tests/qemu-iotests/051
+++ b/tests/qemu-iotests/051
@@ -108,7 +108,8 @@ echo
echo === Overriding backing file ===
echo
-echo "info block" | run_qemu -drive file="$TEST_IMG",driver=qcow2,backing.file.filename="$TEST_IMG.orig" -nodefaults
+echo "info block" | run_qemu -drive file="$TEST_IMG",driver=qcow2,backing.file.filename="$TEST_IMG.orig" -nodefaults\
+ | _filter_generated_node_ids
# Drivers that don't support backing files
run_qemu -drive file="$TEST_IMG",driver=raw,backing.file.filename="$TEST_IMG.orig"
diff --git a/tests/qemu-iotests/051.out b/tests/qemu-iotests/051.out
index 23c282357..7765aa0bb 100644
--- a/tests/qemu-iotests/051.out
+++ b/tests/qemu-iotests/051.out
@@ -1,6 +1,6 @@
QA output created by 051
Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 backing_file='TEST_DIR/t.IMGFMT.base'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 backing_file=TEST_DIR/t.IMGFMT.base
=== Unknown option ===
@@ -59,7 +59,7 @@ QEMU X.Y.Z monitor - type 'help' for more information
Testing: -drive file=TEST_DIR/t.qcow2,driver=qcow2,backing.file.filename=TEST_DIR/t.qcow2.orig -nodefaults
QEMU X.Y.Z monitor - type 'help' for more information
(qemu) iininfinfoinfo info binfo blinfo bloinfo blocinfo block
-ide0-hd0: TEST_DIR/t.qcow2 (qcow2)
+ide0-hd0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
Cache mode: writeback
Backing file: TEST_DIR/t.qcow2.orig (chain depth: 1)
(qemu) qququiquit
diff --git a/tests/qemu-iotests/055 b/tests/qemu-iotests/055
index 017a609f3..c8e357870 100755
--- a/tests/qemu-iotests/055
+++ b/tests/qemu-iotests/055
@@ -42,6 +42,8 @@ class TestSingleDrive(iotests.QMPTestCase):
qemu_img('create', '-f', iotests.imgfmt, blockdev_target_img, str(TestSingleDrive.image_len))
self.vm = iotests.VM().add_drive(test_img).add_drive(blockdev_target_img)
+ if iotests.qemu_default_machine == 'pc':
+ self.vm.add_drive(None, 'media=cdrom', 'ide')
self.vm.launch()
def tearDown(self):
@@ -104,12 +106,18 @@ class TestSingleDrive(iotests.QMPTestCase):
self.do_test_pause('blockdev-backup', 'drive1', blockdev_target_img)
def test_medium_not_found(self):
- result = self.vm.qmp('drive-backup', device='ide1-cd0',
+ if iotests.qemu_default_machine != 'pc':
+ return
+
+ result = self.vm.qmp('drive-backup', device='drive2', # CD-ROM
target=target_img, sync='full')
self.assert_qmp(result, 'error/class', 'GenericError')
def test_medium_not_found_blockdev_backup(self):
- result = self.vm.qmp('blockdev-backup', device='ide1-cd0',
+ if iotests.qemu_default_machine != 'pc':
+ return
+
+ result = self.vm.qmp('blockdev-backup', device='drive2', # CD-ROM
target='drive1', sync='full')
self.assert_qmp(result, 'error/class', 'GenericError')
@@ -249,6 +257,8 @@ class TestSingleTransaction(iotests.QMPTestCase):
qemu_img('create', '-f', iotests.imgfmt, blockdev_target_img, str(TestSingleDrive.image_len))
self.vm = iotests.VM().add_drive(test_img).add_drive(blockdev_target_img)
+ if iotests.qemu_default_machine == 'pc':
+ self.vm.add_drive(None, 'media=cdrom', 'ide')
self.vm.launch()
def tearDown(self):
@@ -323,9 +333,12 @@ class TestSingleTransaction(iotests.QMPTestCase):
self.do_test_pause('blockdev-backup', 'drive1', blockdev_target_img)
def do_test_medium_not_found(self, cmd, target):
+ if iotests.qemu_default_machine != 'pc':
+ return
+
result = self.vm.qmp('transaction', actions=[{
'type': cmd,
- 'data': { 'device': 'ide1-cd0',
+ 'data': { 'device': 'drive2', # CD-ROM
'target': target,
'sync': 'full' },
}
diff --git a/tests/qemu-iotests/056 b/tests/qemu-iotests/056
index 54e4bd069..04f2c3c84 100755
--- a/tests/qemu-iotests/056
+++ b/tests/qemu-iotests/056
@@ -82,6 +82,31 @@ class TestSyncModesNoneAndTop(iotests.QMPTestCase):
time.sleep(1)
self.assertEqual(-1, qemu_io('-c', 'read -P0x41 0 512', target_img).find("verification failed"))
+class TestBeforeWriteNotifier(iotests.QMPTestCase):
+ def setUp(self):
+ self.vm = iotests.VM().add_drive_raw("file=blkdebug::null-co://,id=drive0,align=65536,driver=blkdebug")
+ self.vm.launch()
+
+ def tearDown(self):
+ self.vm.shutdown()
+ os.remove(target_img)
+
+ def test_before_write_notifier(self):
+ self.vm.pause_drive("drive0")
+ result = self.vm.qmp('drive-backup', device='drive0',
+ sync='full', target=target_img,
+ format="file", speed=1)
+ self.assert_qmp(result, 'return', {})
+ result = self.vm.qmp('block-job-pause', device="drive0")
+ self.assert_qmp(result, 'return', {})
+ # Speed is low enough that this must be an uncopied range, which will
+ # trigger the before write notifier
+ self.vm.hmp_qemu_io('drive0', 'aio_write -P 1 512512 512')
+ self.vm.resume_drive("drive0")
+ result = self.vm.qmp('block-job-resume', device="drive0")
+ self.assert_qmp(result, 'return', {})
+ event = self.cancel_and_wait()
+ self.assert_qmp(event, 'data/type', 'backup')
if __name__ == '__main__':
iotests.main(supported_fmts=['qcow2', 'qed'])
diff --git a/tests/qemu-iotests/056.out b/tests/qemu-iotests/056.out
index fbc63e62f..8d7e99670 100644
--- a/tests/qemu-iotests/056.out
+++ b/tests/qemu-iotests/056.out
@@ -1,5 +1,5 @@
-..
+...
----------------------------------------------------------------------
-Ran 2 tests
+Ran 3 tests
OK
diff --git a/tests/qemu-iotests/058 b/tests/qemu-iotests/058
index f2bdd0bff..63a659878 100755
--- a/tests/qemu-iotests/058
+++ b/tests/qemu-iotests/058
@@ -32,11 +32,17 @@ status=1 # failure is the default!
nbd_unix_socket=$TEST_DIR/test_qemu_nbd_socket
nbd_snapshot_img="nbd:unix:$nbd_unix_socket"
+rm -f "${TEST_DIR}/qemu-nbd.pid"
_cleanup_nbd()
{
- if [ -n "$NBD_SNAPSHOT_PID" ]; then
- kill "$NBD_SNAPSHOT_PID"
+ local NBD_SNAPSHOT_PID
+ if [ -f "${TEST_DIR}/qemu-nbd.pid" ]; then
+ read NBD_SNAPSHOT_PID < "${TEST_DIR}/qemu-nbd.pid"
+ rm -f "${TEST_DIR}/qemu-nbd.pid"
+ if [ -n "$NBD_SNAPSHOT_PID" ]; then
+ kill "$NBD_SNAPSHOT_PID"
+ fi
fi
rm -f "$nbd_unix_socket"
}
@@ -60,7 +66,6 @@ _export_nbd_snapshot()
{
_cleanup_nbd
$QEMU_NBD -v -t -k "$nbd_unix_socket" "$TEST_IMG" -l $1 &
- NBD_SNAPSHOT_PID=$!
_wait_for_nbd
}
@@ -68,7 +73,6 @@ _export_nbd_snapshot1()
{
_cleanup_nbd
$QEMU_NBD -v -t -k "$nbd_unix_socket" "$TEST_IMG" -l snapshot.name=$1 &
- NBD_SNAPSHOT_PID=$!
_wait_for_nbd
}
diff --git a/tests/qemu-iotests/059.out b/tests/qemu-iotests/059.out
index 67e3cf57e..00057fef9 100644
--- a/tests/qemu-iotests/059.out
+++ b/tests/qemu-iotests/059.out
@@ -16,17 +16,17 @@ qemu-io: can't open device TEST_DIR/t.vmdk: L1 size too big
no file open, try 'help open'
=== Testing monolithicFlat creation and opening ===
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=2147483648
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=2147483648 subformat=monolithicFlat
image: TEST_DIR/t.IMGFMT
file format: IMGFMT
virtual size: 2.0G (2147483648 bytes)
=== Testing monolithicFlat with zeroed_grain ===
qemu-img: TEST_DIR/t.IMGFMT: Flat image can't enable zeroed grain
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=2147483648
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=2147483648 subformat=monolithicFlat
=== Testing big twoGbMaxExtentFlat ===
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=1073741824000
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=1073741824000 subformat=twoGbMaxExtentFlat
image: TEST_DIR/t.vmdk
file format: vmdk
virtual size: 1.0T (1073741824000 bytes)
@@ -2043,7 +2043,7 @@ RW 12582912 VMFS "dummy.IMGFMT" 1
=== Testing truncated sparse ===
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=107374182400
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=107374182400 subformat=monolithicSparse
qemu-img: Could not open 'TEST_DIR/t.IMGFMT': File truncated, expecting at least 13172736 bytes
=== Converting to streamOptimized from image with small cluster size===
@@ -2054,7 +2054,7 @@ wrote 512/512 bytes at offset 10240
512 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
=== Testing monolithicFlat with internally generated JSON file name ===
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 subformat=monolithicFlat
qemu-io: can't open: Cannot use relative extent paths with VMDK descriptor file 'json:{"image": {"driver": "file", "filename": "TEST_DIR/t.IMGFMT"}, "driver": "blkdebug", "inject-error.0.event": "read_aio"}'
=== Testing version 3 ===
@@ -2264,7 +2264,7 @@ read 512/512 bytes at offset 64931328
512 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
=== Testing 4TB monolithicFlat creation and IO ===
-Formatting 'TEST_DIR/iotest-version3.IMGFMT', fmt=IMGFMT size=4398046511104
+Formatting 'TEST_DIR/iotest-version3.IMGFMT', fmt=IMGFMT size=4398046511104 subformat=monolithicFlat
image: TEST_DIR/iotest-version3.IMGFMT
file format: IMGFMT
virtual size: 4.0T (4398046511104 bytes)
diff --git a/tests/qemu-iotests/061 b/tests/qemu-iotests/061
index 8d37f8a65..e191e65d5 100755
--- a/tests/qemu-iotests/061
+++ b/tests/qemu-iotests/061
@@ -58,7 +58,8 @@ echo
echo "=== Testing dirty version downgrade ==="
echo
IMGOPTS="compat=1.1,lazy_refcounts=on" _make_test_img 64M
-$QEMU_IO -c "write -P 0x2a 0 128k" -c flush -c abort "$TEST_IMG" | _filter_qemu_io
+$QEMU_IO -c "write -P 0x2a 0 128k" -c flush \
+ -c "sigraise $(kill -l KILL)" "$TEST_IMG" 2>&1 | _filter_qemu_io
$PYTHON qcow2.py "$TEST_IMG" dump-header
$QEMU_IMG amend -o "compat=0.10" "$TEST_IMG"
$PYTHON qcow2.py "$TEST_IMG" dump-header
@@ -91,7 +92,8 @@ echo
echo "=== Testing dirty lazy_refcounts=off ==="
echo
IMGOPTS="compat=1.1,lazy_refcounts=on" _make_test_img 64M
-$QEMU_IO -c "write -P 0x2a 0 128k" -c flush -c abort "$TEST_IMG" | _filter_qemu_io
+$QEMU_IO -c "write -P 0x2a 0 128k" -c flush \
+ -c "sigraise $(kill -l KILL)" "$TEST_IMG" 2>&1 | _filter_qemu_io
$PYTHON qcow2.py "$TEST_IMG" dump-header
$QEMU_IMG amend -o "lazy_refcounts=off" "$TEST_IMG"
$PYTHON qcow2.py "$TEST_IMG" dump-header
diff --git a/tests/qemu-iotests/061.out b/tests/qemu-iotests/061.out
index 5ec248f79..f2598a8f9 100644
--- a/tests/qemu-iotests/061.out
+++ b/tests/qemu-iotests/061.out
@@ -57,6 +57,11 @@ No errors were found on the image.
Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864
wrote 131072/131072 bytes at offset 0
128 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
+./common.config: Killed ( if [ "${VALGRIND_QEMU}" == "y" ]; then
+ exec valgrind --log-file="${VALGRIND_LOGFILE}" --error-exitcode=99 "$QEMU_IO_PROG" $QEMU_IO_OPTIONS "$@";
+else
+ exec "$QEMU_IO_PROG" $QEMU_IO_OPTIONS "$@";
+fi )
magic 0x514649fb
version 3
backing_file_offset 0x0
@@ -214,6 +219,11 @@ No errors were found on the image.
Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864
wrote 131072/131072 bytes at offset 0
128 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
+./common.config: Killed ( if [ "${VALGRIND_QEMU}" == "y" ]; then
+ exec valgrind --log-file="${VALGRIND_LOGFILE}" --error-exitcode=99 "$QEMU_IO_PROG" $QEMU_IO_OPTIONS "$@";
+else
+ exec "$QEMU_IO_PROG" $QEMU_IO_OPTIONS "$@";
+fi )
magic 0x514649fb
version 3
backing_file_offset 0x0
@@ -334,7 +344,7 @@ read 131072/131072 bytes at offset 0
Formatting 'TEST_DIR/t.IMGFMT.base', fmt=IMGFMT size=67108864
wrote 131072/131072 bytes at offset 0
128 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file='TEST_DIR/t.IMGFMT.base'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file=TEST_DIR/t.IMGFMT.base
read 131072/131072 bytes at offset 0
128 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
wrote 65536/65536 bytes at offset 0
@@ -350,7 +360,7 @@ read 65536/65536 bytes at offset 65536
Formatting 'TEST_DIR/t.IMGFMT.base', fmt=IMGFMT size=67108864
wrote 131072/131072 bytes at offset 0
128 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file='TEST_DIR/t.IMGFMT.base'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file=TEST_DIR/t.IMGFMT.base
wrote 65536/65536 bytes at offset 0
64 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
wrote 131072/131072 bytes at offset 0
@@ -369,7 +379,7 @@ read 65536/65536 bytes at offset 65536
Formatting 'TEST_DIR/t.IMGFMT.base', fmt=IMGFMT size=67108864
wrote 131072/131072 bytes at offset 0
128 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file='TEST_DIR/t.IMGFMT.base'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file=TEST_DIR/t.IMGFMT.base
wrote 131072/131072 bytes at offset 0
128 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
No errors were found on the image.
@@ -393,7 +403,7 @@ read 67108864/67108864 bytes at offset 0
=== Testing progress report without snapshot ===
Formatting 'TEST_DIR/t.IMGFMT.base', fmt=IMGFMT size=4294967296
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=4294967296 backing_file='TEST_DIR/t.IMGFMT.base'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=4294967296 backing_file=TEST_DIR/t.IMGFMT.base
wrote 65536/65536 bytes at offset 0
64 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
wrote 65536/65536 bytes at offset 1073741824
@@ -408,7 +418,7 @@ No errors were found on the image.
=== Testing progress report with snapshot ===
Formatting 'TEST_DIR/t.IMGFMT.base', fmt=IMGFMT size=4294967296
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=4294967296 backing_file='TEST_DIR/t.IMGFMT.base'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=4294967296 backing_file=TEST_DIR/t.IMGFMT.base
wrote 65536/65536 bytes at offset 0
64 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
wrote 65536/65536 bytes at offset 1073741824
diff --git a/tests/qemu-iotests/067 b/tests/qemu-iotests/067
index 83eefa394..3788534d6 100755
--- a/tests/qemu-iotests/067
+++ b/tests/qemu-iotests/067
@@ -48,7 +48,8 @@ function do_run_qemu()
function run_qemu()
{
do_run_qemu "$@" 2>&1 | _filter_testdir | _filter_qmp | _filter_qemu \
- | sed -e 's/\("actual-size":\s*\)[0-9]\+/\1SIZE/g'
+ | sed -e 's/\("actual-size":\s*\)[0-9]\+/\1SIZE/g' \
+ | _filter_generated_node_ids
}
size=128M
@@ -59,7 +60,7 @@ echo
echo === -drive/-device and device_del ===
echo
-run_qemu -drive file=$TEST_IMG,format=$IMGFMT,if=none,id=disk -device virtio-blk-pci,drive=disk,id=virtio0 <<EOF
+run_qemu -drive file=$TEST_IMG,format=$IMGFMT,if=none,id=disk -device virtio-blk,drive=disk,id=virtio0 <<EOF
{ "execute": "qmp_capabilities" }
{ "execute": "query-block" }
{ "execute": "device_del", "arguments": { "id": "virtio0" } }
@@ -76,7 +77,7 @@ run_qemu -drive file=$TEST_IMG,format=$IMGFMT,if=none,id=disk <<EOF
{ "execute": "qmp_capabilities" }
{ "execute": "query-block" }
{ "execute": "device_add",
- "arguments": { "driver": "virtio-blk-pci", "drive": "disk",
+ "arguments": { "driver": "virtio-blk", "drive": "disk",
"id": "virtio0" } }
{ "execute": "device_del", "arguments": { "id": "virtio0" } }
{ "execute": "system_reset" }
@@ -94,7 +95,7 @@ run_qemu <<EOF
"arguments": { "command-line": "drive_add 0 file=$TEST_IMG,format=$IMGFMT,if=none,id=disk" } }
{ "execute": "query-block" }
{ "execute": "device_add",
- "arguments": { "driver": "virtio-blk-pci", "drive": "disk",
+ "arguments": { "driver": "virtio-blk", "drive": "disk",
"id": "virtio0" } }
{ "execute": "device_del", "arguments": { "id": "virtio0" } }
{ "execute": "system_reset" }
@@ -122,7 +123,7 @@ run_qemu <<EOF
}
{ "execute": "query-block" }
{ "execute": "device_add",
- "arguments": { "driver": "virtio-blk-pci", "drive": "disk",
+ "arguments": { "driver": "virtio-blk", "drive": "disk",
"id": "virtio0" } }
{ "execute": "device_del", "arguments": { "id": "virtio0" } }
{ "execute": "system_reset" }
diff --git a/tests/qemu-iotests/067.out b/tests/qemu-iotests/067.out
index 6ff41bc7a..27ad56fe2 100644
--- a/tests/qemu-iotests/067.out
+++ b/tests/qemu-iotests/067.out
@@ -3,7 +3,7 @@ Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728
=== -drive/-device and device_del ===
-Testing: -drive file=TEST_DIR/t.qcow2,format=qcow2,if=none,id=disk -device virtio-blk-pci,drive=disk,id=virtio0
+Testing: -drive file=TEST_DIR/t.qcow2,format=qcow2,if=none,id=disk -device virtio-blk,drive=disk,id=virtio0
{
QMP_VERSION
}
@@ -40,6 +40,7 @@ Testing: -drive file=TEST_DIR/t.qcow2,format=qcow2,if=none,id=disk -device virti
},
"iops_wr": 0,
"ro": false,
+ "node-name": "NODE_NAME",
"backing_file_depth": 0,
"drv": "qcow2",
"iops": 0,
@@ -57,28 +58,6 @@ Testing: -drive file=TEST_DIR/t.qcow2,format=qcow2,if=none,id=disk -device virti
"encryption_key_missing": false
},
"type": "unknown"
- },
- {
- "io-status": "ok",
- "device": "ide1-cd0",
- "locked": false,
- "removable": true,
- "tray_open": false,
- "type": "unknown"
- },
- {
- "device": "floppy0",
- "locked": false,
- "removable": true,
- "tray_open": false,
- "type": "unknown"
- },
- {
- "device": "sd0",
- "locked": false,
- "removable": true,
- "tray_open": false,
- "type": "unknown"
}
]
}
@@ -120,28 +99,6 @@ Testing: -drive file=TEST_DIR/t.qcow2,format=qcow2,if=none,id=disk -device virti
}
{
"return": [
- {
- "io-status": "ok",
- "device": "ide1-cd0",
- "locked": false,
- "removable": true,
- "tray_open": false,
- "type": "unknown"
- },
- {
- "device": "floppy0",
- "locked": false,
- "removable": true,
- "tray_open": false,
- "type": "unknown"
- },
- {
- "device": "sd0",
- "locked": false,
- "removable": true,
- "tray_open": false,
- "type": "unknown"
- }
]
}
{
@@ -155,28 +112,6 @@ Testing: -drive file=TEST_DIR/t.qcow2,format=qcow2,if=none,id=disk -device virti
},
"event": "SHUTDOWN"
}
-{
- "timestamp": {
- "seconds": TIMESTAMP,
- "microseconds": TIMESTAMP
- },
- "event": "DEVICE_TRAY_MOVED",
- "data": {
- "device": "ide1-cd0",
- "tray-open": true
- }
-}
-{
- "timestamp": {
- "seconds": TIMESTAMP,
- "microseconds": TIMESTAMP
- },
- "event": "DEVICE_TRAY_MOVED",
- "data": {
- "device": "floppy0",
- "tray-open": true
- }
-}
=== -drive/device_add and device_del ===
@@ -217,6 +152,7 @@ Testing: -drive file=TEST_DIR/t.qcow2,format=qcow2,if=none,id=disk
},
"iops_wr": 0,
"ro": false,
+ "node-name": "NODE_NAME",
"backing_file_depth": 0,
"drv": "qcow2",
"iops": 0,
@@ -235,28 +171,6 @@ Testing: -drive file=TEST_DIR/t.qcow2,format=qcow2,if=none,id=disk
},
"tray_open": false,
"type": "unknown"
- },
- {
- "io-status": "ok",
- "device": "ide1-cd0",
- "locked": false,
- "removable": true,
- "tray_open": false,
- "type": "unknown"
- },
- {
- "device": "floppy0",
- "locked": false,
- "removable": true,
- "tray_open": false,
- "type": "unknown"
- },
- {
- "device": "sd0",
- "locked": false,
- "removable": true,
- "tray_open": false,
- "type": "unknown"
}
]
}
@@ -302,28 +216,6 @@ Testing: -drive file=TEST_DIR/t.qcow2,format=qcow2,if=none,id=disk
}
{
"return": [
- {
- "io-status": "ok",
- "device": "ide1-cd0",
- "locked": false,
- "removable": true,
- "tray_open": false,
- "type": "unknown"
- },
- {
- "device": "floppy0",
- "locked": false,
- "removable": true,
- "tray_open": false,
- "type": "unknown"
- },
- {
- "device": "sd0",
- "locked": false,
- "removable": true,
- "tray_open": false,
- "type": "unknown"
- }
]
}
{
@@ -337,28 +229,6 @@ Testing: -drive file=TEST_DIR/t.qcow2,format=qcow2,if=none,id=disk
},
"event": "SHUTDOWN"
}
-{
- "timestamp": {
- "seconds": TIMESTAMP,
- "microseconds": TIMESTAMP
- },
- "event": "DEVICE_TRAY_MOVED",
- "data": {
- "device": "ide1-cd0",
- "tray-open": true
- }
-}
-{
- "timestamp": {
- "seconds": TIMESTAMP,
- "microseconds": TIMESTAMP
- },
- "event": "DEVICE_TRAY_MOVED",
- "data": {
- "device": "floppy0",
- "tray-open": true
- }
-}
=== drive_add/device_add and device_del ===
@@ -377,28 +247,6 @@ Testing:
{
"return": [
{
- "io-status": "ok",
- "device": "ide1-cd0",
- "locked": false,
- "removable": true,
- "tray_open": false,
- "type": "unknown"
- },
- {
- "device": "floppy0",
- "locked": false,
- "removable": true,
- "tray_open": false,
- "type": "unknown"
- },
- {
- "device": "sd0",
- "locked": false,
- "removable": true,
- "tray_open": false,
- "type": "unknown"
- },
- {
"device": "disk",
"locked": false,
"removable": true,
@@ -424,6 +272,7 @@ Testing:
},
"iops_wr": 0,
"ro": false,
+ "node-name": "NODE_NAME",
"backing_file_depth": 0,
"drv": "qcow2",
"iops": 0,
@@ -487,28 +336,6 @@ Testing:
}
{
"return": [
- {
- "io-status": "ok",
- "device": "ide1-cd0",
- "locked": false,
- "removable": true,
- "tray_open": false,
- "type": "unknown"
- },
- {
- "device": "floppy0",
- "locked": false,
- "removable": true,
- "tray_open": false,
- "type": "unknown"
- },
- {
- "device": "sd0",
- "locked": false,
- "removable": true,
- "tray_open": false,
- "type": "unknown"
- }
]
}
{
@@ -522,28 +349,6 @@ Testing:
},
"event": "SHUTDOWN"
}
-{
- "timestamp": {
- "seconds": TIMESTAMP,
- "microseconds": TIMESTAMP
- },
- "event": "DEVICE_TRAY_MOVED",
- "data": {
- "device": "ide1-cd0",
- "tray-open": true
- }
-}
-{
- "timestamp": {
- "seconds": TIMESTAMP,
- "microseconds": TIMESTAMP
- },
- "event": "DEVICE_TRAY_MOVED",
- "data": {
- "device": "floppy0",
- "tray-open": true
- }
-}
=== blockdev_add/device_add and device_del ===
@@ -563,28 +368,6 @@ Testing:
{
"return": [
{
- "io-status": "ok",
- "device": "ide1-cd0",
- "locked": false,
- "removable": true,
- "tray_open": false,
- "type": "unknown"
- },
- {
- "device": "floppy0",
- "locked": false,
- "removable": true,
- "tray_open": false,
- "type": "unknown"
- },
- {
- "device": "sd0",
- "locked": false,
- "removable": true,
- "tray_open": false,
- "type": "unknown"
- },
- {
"device": "disk",
"locked": false,
"removable": true,
@@ -610,6 +393,7 @@ Testing:
},
"iops_wr": 0,
"ro": false,
+ "node-name": "NODE_NAME",
"backing_file_depth": 0,
"drv": "qcow2",
"iops": 0,
@@ -675,28 +459,6 @@ Testing:
"return": [
{
"io-status": "ok",
- "device": "ide1-cd0",
- "locked": false,
- "removable": true,
- "tray_open": false,
- "type": "unknown"
- },
- {
- "device": "floppy0",
- "locked": false,
- "removable": true,
- "tray_open": false,
- "type": "unknown"
- },
- {
- "device": "sd0",
- "locked": false,
- "removable": true,
- "tray_open": false,
- "type": "unknown"
- },
- {
- "io-status": "ok",
"device": "disk",
"locked": false,
"removable": true,
@@ -722,6 +484,7 @@ Testing:
},
"iops_wr": 0,
"ro": false,
+ "node-name": "NODE_NAME",
"backing_file_depth": 0,
"drv": "qcow2",
"iops": 0,
@@ -754,27 +517,5 @@ Testing:
},
"event": "SHUTDOWN"
}
-{
- "timestamp": {
- "seconds": TIMESTAMP,
- "microseconds": TIMESTAMP
- },
- "event": "DEVICE_TRAY_MOVED",
- "data": {
- "device": "ide1-cd0",
- "tray-open": true
- }
-}
-{
- "timestamp": {
- "seconds": TIMESTAMP,
- "microseconds": TIMESTAMP
- },
- "event": "DEVICE_TRAY_MOVED",
- "data": {
- "device": "floppy0",
- "tray-open": true
- }
-}
*** done
diff --git a/tests/qemu-iotests/069.out b/tests/qemu-iotests/069.out
index 4d7e63cf8..c78e8c2b7 100644
--- a/tests/qemu-iotests/069.out
+++ b/tests/qemu-iotests/069.out
@@ -3,6 +3,6 @@ QA output created by 069
=== Creating an image with a backing file and deleting that file ===
Formatting 'TEST_DIR/t.IMGFMT.base', fmt=IMGFMT size=131072
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=131072 backing_file='TEST_DIR/t.IMGFMT.base'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=131072 backing_file=TEST_DIR/t.IMGFMT.base
qemu-io: can't open device TEST_DIR/t.IMGFMT: Could not open backing file: Could not open 'TEST_DIR/t.IMGFMT.base': No such file or directory
*** done
diff --git a/tests/qemu-iotests/071 b/tests/qemu-iotests/071
index 9eaa49b41..92ab99145 100755
--- a/tests/qemu-iotests/071
+++ b/tests/qemu-iotests/071
@@ -104,11 +104,20 @@ echo
echo "=== Testing blkdebug on existing block device ==="
echo
-run_qemu -drive "file=$TEST_IMG,format=raw,if=none,id=drive0" <<EOF
+run_qemu <<EOF
{ "execute": "qmp_capabilities" }
{ "execute": "blockdev-add",
"arguments": {
"options": {
+ "node-name": "drive0",
+ "driver": "file",
+ "filename": "$TEST_IMG"
+ }
+ }
+}
+{ "execute": "blockdev-add",
+ "arguments": {
+ "options": {
"driver": "$IMGFMT",
"id": "drive0-debug",
"file": {
@@ -133,20 +142,29 @@ echo
echo "=== Testing blkverify on existing block device ==="
echo
-run_qemu -drive "file=$TEST_IMG,format=$IMGFMT,if=none,id=drive0" <<EOF
+run_qemu <<EOF
{ "execute": "qmp_capabilities" }
{ "execute": "blockdev-add",
"arguments": {
"options": {
+ "node-name": "drive0",
+ "driver": "$IMGFMT",
+ "file": {
+ "driver": "file",
+ "filename": "$TEST_IMG"
+ }
+ }
+ }
+}
+{ "execute": "blockdev-add",
+ "arguments": {
+ "options": {
"driver": "blkverify",
"id": "drive0-verify",
"test": "drive0",
"raw": {
- "driver": "raw",
- "file": {
- "driver": "file",
- "filename": "$TEST_IMG.base"
- }
+ "driver": "file",
+ "filename": "$TEST_IMG.base"
}
}
}
@@ -163,11 +181,20 @@ echo
echo "=== Testing blkverify on existing raw block device ==="
echo
-run_qemu -drive "file=$TEST_IMG.base,format=raw,if=none,id=drive0" <<EOF
+run_qemu <<EOF
{ "execute": "qmp_capabilities" }
{ "execute": "blockdev-add",
"arguments": {
"options": {
+ "node-name": "drive0",
+ "driver": "file",
+ "filename": "$TEST_IMG.base"
+ }
+ }
+}
+{ "execute": "blockdev-add",
+ "arguments": {
+ "options": {
"driver": "blkverify",
"id": "drive0-verify",
"test": {
@@ -193,11 +220,20 @@ echo
echo "=== Testing blkdebug's set-state through QMP ==="
echo
-run_qemu -drive "file=$TEST_IMG,format=raw,if=none,id=drive0" <<EOF
+run_qemu <<EOF
{ "execute": "qmp_capabilities" }
{ "execute": "blockdev-add",
"arguments": {
"options": {
+ "node-name": "drive0",
+ "driver": "file",
+ "filename": "$TEST_IMG"
+ }
+ }
+}
+{ "execute": "blockdev-add",
+ "arguments": {
+ "options": {
"driver": "$IMGFMT",
"id": "drive0-debug",
"file": {
diff --git a/tests/qemu-iotests/071.out b/tests/qemu-iotests/071.out
index 9205ce251..2b40eadae 100644
--- a/tests/qemu-iotests/071.out
+++ b/tests/qemu-iotests/071.out
@@ -42,44 +42,46 @@ read failed: Input/output error
=== Testing blkdebug on existing block device ===
-Testing: -drive file=TEST_DIR/t.IMGFMT,format=raw,if=none,id=drive0
+Testing:
QMP_VERSION
{"return": {}}
{"return": {}}
+{"return": {}}
read failed: Input/output error
{"return": ""}
{"return": {}}
{"timestamp": {"seconds": TIMESTAMP, "microseconds": TIMESTAMP}, "event": "SHUTDOWN"}
-{"timestamp": {"seconds": TIMESTAMP, "microseconds": TIMESTAMP}, "event": "DEVICE_TRAY_MOVED", "data": {"device": "ide1-cd0", "tray-open": true}}
-{"timestamp": {"seconds": TIMESTAMP, "microseconds": TIMESTAMP}, "event": "DEVICE_TRAY_MOVED", "data": {"device": "floppy0", "tray-open": true}}
QEMU_PROG: Failed to flush the L2 table cache: Input/output error
QEMU_PROG: Failed to flush the refcount block cache: Input/output error
=== Testing blkverify on existing block device ===
-Testing: -drive file=TEST_DIR/t.IMGFMT,format=IMGFMT,if=none,id=drive0
+Testing:
QMP_VERSION
{"return": {}}
{"return": {}}
+{"return": {}}
blkverify: read sector_num=0 nb_sectors=1 contents mismatch in sector 0
=== Testing blkverify on existing raw block device ===
-Testing: -drive file=TEST_DIR/t.IMGFMT.base,format=raw,if=none,id=drive0
+Testing:
QMP_VERSION
{"return": {}}
{"return": {}}
+{"return": {}}
blkverify: read sector_num=0 nb_sectors=1 contents mismatch in sector 0
=== Testing blkdebug's set-state through QMP ===
-Testing: -drive file=TEST_DIR/t.IMGFMT,format=raw,if=none,id=drive0
+Testing:
QMP_VERSION
{"return": {}}
{"return": {}}
+{"return": {}}
read 512/512 bytes at offset 0
512 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
{"return": ""}
@@ -90,8 +92,6 @@ read failed: Input/output error
{"return": ""}
{"return": {}}
{"timestamp": {"seconds": TIMESTAMP, "microseconds": TIMESTAMP}, "event": "SHUTDOWN"}
-{"timestamp": {"seconds": TIMESTAMP, "microseconds": TIMESTAMP}, "event": "DEVICE_TRAY_MOVED", "data": {"device": "ide1-cd0", "tray-open": true}}
-{"timestamp": {"seconds": TIMESTAMP, "microseconds": TIMESTAMP}, "event": "DEVICE_TRAY_MOVED", "data": {"device": "floppy0", "tray-open": true}}
QEMU_PROG: Failed to flush the L2 table cache: Input/output error
QEMU_PROG: Failed to flush the refcount block cache: Input/output error
diff --git a/tests/qemu-iotests/073.out b/tests/qemu-iotests/073.out
index 733d79ca9..de5452492 100644
--- a/tests/qemu-iotests/073.out
+++ b/tests/qemu-iotests/073.out
@@ -2,7 +2,7 @@ QA output created by 073
== creating backing file ==
Formatting 'TEST_DIR/t.IMGFMT.base', fmt=IMGFMT size=134217728
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 backing_file='TEST_DIR/t.IMGFMT.base'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 backing_file=TEST_DIR/t.IMGFMT.base
wrote 134217728/134217728 bytes at offset 0
128 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
diff --git a/tests/qemu-iotests/079.out b/tests/qemu-iotests/079.out
index 6dc5d5763..aab922fb3 100644
--- a/tests/qemu-iotests/079.out
+++ b/tests/qemu-iotests/079.out
@@ -1,14 +1,14 @@
QA output created by 079
=== Check option preallocation and cluster_size ===
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=4294967296 preallocation='metadata'
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=4294967296 preallocation='metadata'
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=4294967296 preallocation='metadata'
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=4294967296 preallocation='metadata'
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=4294967296 preallocation='metadata'
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=4294967296 preallocation='metadata'
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=4294967296 preallocation='metadata'
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=4294967296 preallocation='metadata'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=4294967296 preallocation=metadata
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=4294967296 preallocation=metadata
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=4294967296 preallocation=metadata
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=4294967296 preallocation=metadata
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=4294967296 preallocation=metadata
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=4294967296 preallocation=metadata
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=4294967296 preallocation=metadata
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=4294967296 preallocation=metadata
qemu-img: TEST_DIR/t.IMGFMT: Cluster size must be a power of two between 512 and 2048k
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=4294967296 preallocation='metadata'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=4294967296 preallocation=metadata
*** done
diff --git a/tests/qemu-iotests/081 b/tests/qemu-iotests/081
index d9b042cfc..e4b4c6cbf 100755
--- a/tests/qemu-iotests/081
+++ b/tests/qemu-iotests/081
@@ -53,7 +53,8 @@ function do_run_qemu()
function run_qemu()
{
- do_run_qemu "$@" 2>&1 | _filter_testdir | _filter_qemu | _filter_qmp | _filter_qemu_io
+ do_run_qemu "$@" 2>&1 | _filter_testdir | _filter_qemu | _filter_qmp\
+ | _filter_qemu_io | _filter_generated_node_ids
}
test_quorum=$($QEMU_IMG --help|grep quorum)
@@ -101,17 +102,29 @@ $QEMU_IO -c "open -o $quorum" -c "read -P 0x32 0 $size" | _filter_qemu_io
echo
echo "== checking mixed reference/option specification =="
-run_qemu -drive "file=$TEST_DIR/2.raw,format=$IMGFMT,if=none,id=drive2" <<EOF
+run_qemu <<EOF
{ "execute": "qmp_capabilities" }
{ "execute": "blockdev-add",
"arguments": {
"options": {
+ "node-name": "drive2",
+ "driver": "$IMGFMT",
+ "file": {
+ "driver": "file",
+ "filename": "$TEST_DIR/2.raw"
+ }
+ }
+ }
+}
+{ "execute": "blockdev-add",
+ "arguments": {
+ "options": {
"driver": "quorum",
"id": "drive0-quorum",
"vote-threshold": 2,
"children": [
{
- "driver": "raw",
+ "driver": "$IMGFMT",
"file": {
"driver": "file",
"filename": "$TEST_DIR/1.raw"
@@ -119,7 +132,7 @@ run_qemu -drive "file=$TEST_DIR/2.raw,format=$IMGFMT,if=none,id=drive2" <<EOF
},
"drive2",
{
- "driver": "raw",
+ "driver": "$IMGFMT",
"file": {
"driver": "file",
"filename": "$TEST_DIR/3.raw"
diff --git a/tests/qemu-iotests/081.out b/tests/qemu-iotests/081.out
index 9f57d9d3b..70632314c 100644
--- a/tests/qemu-iotests/081.out
+++ b/tests/qemu-iotests/081.out
@@ -26,18 +26,17 @@ read 10485760/10485760 bytes at offset 0
10 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
== checking mixed reference/option specification ==
-Testing: -drive file=TEST_DIR/2.IMGFMT,format=IMGFMT,if=none,id=drive2
+Testing:
QMP_VERSION
{"return": {}}
{"return": {}}
-{"timestamp": {"seconds": TIMESTAMP, "microseconds": TIMESTAMP}, "event": "QUORUM_REPORT_BAD", "data": {"node-name": "", "sectors-count": 20480, "sector-num": 0}}
+{"return": {}}
+{"timestamp": {"seconds": TIMESTAMP, "microseconds": TIMESTAMP}, "event": "QUORUM_REPORT_BAD", "data": {"node-name": "drive2", "sectors-count": 20480, "sector-num": 0}}
read 10485760/10485760 bytes at offset 0
10 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
{"return": ""}
{"return": {}}
{"timestamp": {"seconds": TIMESTAMP, "microseconds": TIMESTAMP}, "event": "SHUTDOWN"}
-{"timestamp": {"seconds": TIMESTAMP, "microseconds": TIMESTAMP}, "event": "DEVICE_TRAY_MOVED", "data": {"device": "ide1-cd0", "tray-open": true}}
-{"timestamp": {"seconds": TIMESTAMP, "microseconds": TIMESTAMP}, "event": "DEVICE_TRAY_MOVED", "data": {"device": "floppy0", "tray-open": true}}
== using quorum rewrite corrupted mode ==
diff --git a/tests/qemu-iotests/082.out b/tests/qemu-iotests/082.out
index 3a749b825..a952330ba 100644
--- a/tests/qemu-iotests/082.out
+++ b/tests/qemu-iotests/082.out
@@ -147,10 +147,10 @@ refcount_bits Width of a reference count entry in bits
nocow Turn off copy-on-write (valid only on btrfs)
Testing: create -f qcow2 -o backing_file=TEST_DIR/t.qcow2,,help TEST_DIR/t.qcow2 128M
-Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=134217728 backing_file='TEST_DIR/t.qcow2,help' encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
+Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/t.qcow2,,help encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
Testing: create -f qcow2 -o backing_file=TEST_DIR/t.qcow2,,? TEST_DIR/t.qcow2 128M
-Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=134217728 backing_file='TEST_DIR/t.qcow2,?' encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
+Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/t.qcow2,,? encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
Testing: create -f qcow2 -o backing_file=TEST_DIR/t.qcow2, -o help TEST_DIR/t.qcow2 128M
qemu-img: Invalid option list: backing_file=TEST_DIR/t.qcow2,
diff --git a/tests/qemu-iotests/085 b/tests/qemu-iotests/085
index 56cd6f89b..aa77eca77 100755
--- a/tests/qemu-iotests/085
+++ b/tests/qemu-iotests/085
@@ -7,6 +7,7 @@
# snapshots are performed.
#
# Copyright (C) 2014 Red Hat, Inc.
+# Copyright (C) 2015 Igalia, S.L.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
@@ -34,17 +35,17 @@ status=1 # failure is the default!
snapshot_virt0="snapshot-v0.qcow2"
snapshot_virt1="snapshot-v1.qcow2"
-MAX_SNAPSHOTS=10
+SNAPSHOTS=10
_cleanup()
{
_cleanup_qemu
- for i in $(seq 1 ${MAX_SNAPSHOTS})
+ for i in $(seq 1 ${SNAPSHOTS})
do
rm -f "${TEST_DIR}/${i}-${snapshot_virt0}"
rm -f "${TEST_DIR}/${i}-${snapshot_virt1}"
done
- _cleanup_test_img
+ rm -f "${TEST_IMG}.1" "${TEST_IMG}.2"
}
trap "_cleanup; exit \$status" 0 1 2 3 15
@@ -64,7 +65,7 @@ function create_single_snapshot()
{
cmd="{ 'execute': 'blockdev-snapshot-sync',
'arguments': { 'device': 'virtio0',
- 'snapshot-file':'"${TEST_DIR}/${1}-${snapshot_virt0}"',
+ 'snapshot-file':'${TEST_DIR}/${1}-${snapshot_virt0}',
'format': 'qcow2' } }"
_send_qemu_cmd $h "${cmd}" "return"
}
@@ -76,27 +77,60 @@ function create_group_snapshot()
{'actions': [
{ 'type': 'blockdev-snapshot-sync', 'data' :
{ 'device': 'virtio0',
- 'snapshot-file': '"${TEST_DIR}/${1}-${snapshot_virt0}"' } },
+ 'snapshot-file': '${TEST_DIR}/${1}-${snapshot_virt0}' } },
{ 'type': 'blockdev-snapshot-sync', 'data' :
{ 'device': 'virtio1',
- 'snapshot-file': '"${TEST_DIR}/${1}-${snapshot_virt1}"' } } ]
+ 'snapshot-file': '${TEST_DIR}/${1}-${snapshot_virt1}' } } ]
} }"
_send_qemu_cmd $h "${cmd}" "return"
}
+# ${1}: unique identifier for the snapshot filename
+# ${2}: true: open backing images; false: don't open them (default)
+function add_snapshot_image()
+{
+ if [ "${2}" = "true" ]; then
+ extra_params=""
+ else
+ extra_params="'backing': '', "
+ fi
+ base_image="${TEST_DIR}/$((${1}-1))-${snapshot_virt0}"
+ snapshot_file="${TEST_DIR}/${1}-${snapshot_virt0}"
+ _make_test_img -b "${base_image}" "$size"
+ mv "${TEST_IMG}" "${snapshot_file}"
+ cmd="{ 'execute': 'blockdev-add', 'arguments':
+ { 'options':
+ { 'driver': 'qcow2', 'node-name': 'snap_${1}', ${extra_params}
+ 'file':
+ { 'driver': 'file', 'filename': '${snapshot_file}',
+ 'node-name': 'file_${1}' } } } }"
+ _send_qemu_cmd $h "${cmd}" "return"
+}
+
+# ${1}: unique identifier for the snapshot filename
+# ${2}: expected response, defaults to 'return'
+function blockdev_snapshot()
+{
+ cmd="{ 'execute': 'blockdev-snapshot',
+ 'arguments': { 'node': 'virtio0',
+ 'overlay':'snap_${1}' } }"
+ _send_qemu_cmd $h "${cmd}" "${2:-return}"
+}
+
size=128M
_make_test_img $size
-mv "${TEST_IMG}" "${TEST_IMG}.orig"
+mv "${TEST_IMG}" "${TEST_IMG}.1"
_make_test_img $size
+mv "${TEST_IMG}" "${TEST_IMG}.2"
echo
echo === Running QEMU ===
echo
qemu_comm_method="qmp"
-_launch_qemu -drive file="${TEST_IMG}.orig",if=virtio -drive file="${TEST_IMG}",if=virtio
+_launch_qemu -drive file="${TEST_IMG}.1",if=virtio -drive file="${TEST_IMG}.2",if=virtio
h=$QEMU_HANDLE
echo
@@ -105,6 +139,8 @@ echo
_send_qemu_cmd $h "{ 'execute': 'qmp_capabilities' }" "return"
+# Tests for the blockdev-snapshot-sync command
+
echo
echo === Create a single snapshot on virtio0 ===
echo
@@ -117,7 +153,7 @@ echo === Invalid command - missing device and nodename ===
echo
_send_qemu_cmd $h "{ 'execute': 'blockdev-snapshot-sync',
- 'arguments': { 'snapshot-file':'"${TEST_DIR}/1-${snapshot_virt0}"',
+ 'arguments': { 'snapshot-file':'${TEST_DIR}/1-${snapshot_virt0}',
'format': 'qcow2' } }" "error"
echo
@@ -132,11 +168,75 @@ echo
echo === Create several transactional group snapshots ===
echo
-for i in $(seq 2 ${MAX_SNAPSHOTS})
+for i in $(seq 2 ${SNAPSHOTS})
do
create_group_snapshot ${i}
done
+# Tests for the blockdev-snapshot command
+
+echo
+echo === Create a couple of snapshots using blockdev-snapshot ===
+echo
+
+SNAPSHOTS=$((${SNAPSHOTS}+1))
+add_snapshot_image ${SNAPSHOTS}
+blockdev_snapshot ${SNAPSHOTS}
+
+SNAPSHOTS=$((${SNAPSHOTS}+1))
+add_snapshot_image ${SNAPSHOTS}
+blockdev_snapshot ${SNAPSHOTS}
+
+echo
+echo === Invalid command - cannot create a snapshot using a file BDS ===
+echo
+
+_send_qemu_cmd $h "{ 'execute': 'blockdev-snapshot',
+ 'arguments': { 'node':'virtio0',
+ 'overlay':'file_${SNAPSHOTS}' }
+ }" "error"
+
+echo
+echo === Invalid command - snapshot node used as active layer ===
+echo
+
+blockdev_snapshot ${SNAPSHOTS} error
+
+_send_qemu_cmd $h "{ 'execute': 'blockdev-snapshot',
+ 'arguments': { 'node':'virtio0',
+ 'overlay':'virtio0' }
+ }" "error"
+
+_send_qemu_cmd $h "{ 'execute': 'blockdev-snapshot',
+ 'arguments': { 'node':'virtio0',
+ 'overlay':'virtio1' }
+ }" "error"
+
+echo
+echo === Invalid command - snapshot node used as backing hd ===
+echo
+
+blockdev_snapshot $((${SNAPSHOTS}-1)) error
+
+echo
+echo === Invalid command - snapshot node has a backing image ===
+echo
+
+SNAPSHOTS=$((${SNAPSHOTS}+1))
+add_snapshot_image ${SNAPSHOTS} true
+blockdev_snapshot ${SNAPSHOTS} error
+
+echo
+echo === Invalid command - The node does not exist ===
+echo
+
+blockdev_snapshot $((${SNAPSHOTS}+1)) error
+
+_send_qemu_cmd $h "{ 'execute': 'blockdev-snapshot',
+ 'arguments': { 'node':'nodevice',
+ 'overlay':'snap_${SNAPSHOTS}' }
+ }" "error"
+
# success, all done
echo "*** done"
rm -f $seq.full
diff --git a/tests/qemu-iotests/085.out b/tests/qemu-iotests/085.out
index 5eb8b947c..01c78d689 100644
--- a/tests/qemu-iotests/085.out
+++ b/tests/qemu-iotests/085.out
@@ -11,7 +11,7 @@ Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728
=== Create a single snapshot on virtio0 ===
-Formatting 'TEST_DIR/1-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file='TEST_DIR/t.qcow2.orig' backing_fmt='qcow2' encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
+Formatting 'TEST_DIR/1-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/t.qcow2.1 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
{"return": {}}
=== Invalid command - missing device and nodename ===
@@ -25,31 +25,65 @@ Formatting 'TEST_DIR/1-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file
=== Create several transactional group snapshots ===
-Formatting 'TEST_DIR/2-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file='TEST_DIR/1-snapshot-v0.qcow2' backing_fmt='qcow2' encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
-Formatting 'TEST_DIR/2-snapshot-v1.qcow2', fmt=qcow2 size=134217728 backing_file='TEST_DIR/t.qcow2' backing_fmt='qcow2' encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
+Formatting 'TEST_DIR/2-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/1-snapshot-v0.qcow2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
+Formatting 'TEST_DIR/2-snapshot-v1.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/t.qcow2.2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
{"return": {}}
-Formatting 'TEST_DIR/3-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file='TEST_DIR/2-snapshot-v0.qcow2' backing_fmt='qcow2' encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
-Formatting 'TEST_DIR/3-snapshot-v1.qcow2', fmt=qcow2 size=134217728 backing_file='TEST_DIR/2-snapshot-v1.qcow2' backing_fmt='qcow2' encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
+Formatting 'TEST_DIR/3-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/2-snapshot-v0.qcow2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
+Formatting 'TEST_DIR/3-snapshot-v1.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/2-snapshot-v1.qcow2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
{"return": {}}
-Formatting 'TEST_DIR/4-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file='TEST_DIR/3-snapshot-v0.qcow2' backing_fmt='qcow2' encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
-Formatting 'TEST_DIR/4-snapshot-v1.qcow2', fmt=qcow2 size=134217728 backing_file='TEST_DIR/3-snapshot-v1.qcow2' backing_fmt='qcow2' encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
+Formatting 'TEST_DIR/4-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/3-snapshot-v0.qcow2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
+Formatting 'TEST_DIR/4-snapshot-v1.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/3-snapshot-v1.qcow2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
{"return": {}}
-Formatting 'TEST_DIR/5-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file='TEST_DIR/4-snapshot-v0.qcow2' backing_fmt='qcow2' encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
-Formatting 'TEST_DIR/5-snapshot-v1.qcow2', fmt=qcow2 size=134217728 backing_file='TEST_DIR/4-snapshot-v1.qcow2' backing_fmt='qcow2' encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
+Formatting 'TEST_DIR/5-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/4-snapshot-v0.qcow2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
+Formatting 'TEST_DIR/5-snapshot-v1.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/4-snapshot-v1.qcow2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
{"return": {}}
-Formatting 'TEST_DIR/6-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file='TEST_DIR/5-snapshot-v0.qcow2' backing_fmt='qcow2' encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
-Formatting 'TEST_DIR/6-snapshot-v1.qcow2', fmt=qcow2 size=134217728 backing_file='TEST_DIR/5-snapshot-v1.qcow2' backing_fmt='qcow2' encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
+Formatting 'TEST_DIR/6-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/5-snapshot-v0.qcow2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
+Formatting 'TEST_DIR/6-snapshot-v1.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/5-snapshot-v1.qcow2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
{"return": {}}
-Formatting 'TEST_DIR/7-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file='TEST_DIR/6-snapshot-v0.qcow2' backing_fmt='qcow2' encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
-Formatting 'TEST_DIR/7-snapshot-v1.qcow2', fmt=qcow2 size=134217728 backing_file='TEST_DIR/6-snapshot-v1.qcow2' backing_fmt='qcow2' encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
+Formatting 'TEST_DIR/7-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/6-snapshot-v0.qcow2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
+Formatting 'TEST_DIR/7-snapshot-v1.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/6-snapshot-v1.qcow2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
{"return": {}}
-Formatting 'TEST_DIR/8-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file='TEST_DIR/7-snapshot-v0.qcow2' backing_fmt='qcow2' encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
-Formatting 'TEST_DIR/8-snapshot-v1.qcow2', fmt=qcow2 size=134217728 backing_file='TEST_DIR/7-snapshot-v1.qcow2' backing_fmt='qcow2' encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
+Formatting 'TEST_DIR/8-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/7-snapshot-v0.qcow2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
+Formatting 'TEST_DIR/8-snapshot-v1.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/7-snapshot-v1.qcow2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
{"return": {}}
-Formatting 'TEST_DIR/9-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file='TEST_DIR/8-snapshot-v0.qcow2' backing_fmt='qcow2' encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
-Formatting 'TEST_DIR/9-snapshot-v1.qcow2', fmt=qcow2 size=134217728 backing_file='TEST_DIR/8-snapshot-v1.qcow2' backing_fmt='qcow2' encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
+Formatting 'TEST_DIR/9-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/8-snapshot-v0.qcow2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
+Formatting 'TEST_DIR/9-snapshot-v1.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/8-snapshot-v1.qcow2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
{"return": {}}
-Formatting 'TEST_DIR/10-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file='TEST_DIR/9-snapshot-v0.qcow2' backing_fmt='qcow2' encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
-Formatting 'TEST_DIR/10-snapshot-v1.qcow2', fmt=qcow2 size=134217728 backing_file='TEST_DIR/9-snapshot-v1.qcow2' backing_fmt='qcow2' encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
+Formatting 'TEST_DIR/10-snapshot-v0.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/9-snapshot-v0.qcow2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
+Formatting 'TEST_DIR/10-snapshot-v1.qcow2', fmt=qcow2 size=134217728 backing_file=TEST_DIR/9-snapshot-v1.qcow2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
{"return": {}}
+
+=== Create a couple of snapshots using blockdev-snapshot ===
+
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 backing_file=TEST_DIR/10-snapshot-v0.IMGFMT
+{"return": {}}
+{"return": {}}
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 backing_file=TEST_DIR/11-snapshot-v0.IMGFMT
+{"return": {}}
+{"return": {}}
+
+=== Invalid command - cannot create a snapshot using a file BDS ===
+
+{"error": {"class": "GenericError", "desc": "The snapshot does not support backing images"}}
+
+=== Invalid command - snapshot node used as active layer ===
+
+{"error": {"class": "GenericError", "desc": "The snapshot is already in use by virtio0"}}
+{"error": {"class": "GenericError", "desc": "The snapshot is already in use by virtio0"}}
+{"error": {"class": "GenericError", "desc": "The snapshot is already in use by virtio1"}}
+
+=== Invalid command - snapshot node used as backing hd ===
+
+{"error": {"class": "GenericError", "desc": "Node 'snap_11' is busy: node is used as backing hd of 'virtio0'"}}
+
+=== Invalid command - snapshot node has a backing image ===
+
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 backing_file=TEST_DIR/12-snapshot-v0.IMGFMT
+{"return": {}}
+{"error": {"class": "GenericError", "desc": "The snapshot already has a backing image"}}
+
+=== Invalid command - The node does not exist ===
+
+{"error": {"class": "GenericError", "desc": "Cannot find device=snap_14 nor node_name=snap_14"}}
+{"error": {"class": "GenericError", "desc": "Cannot find device=nodevice nor node_name=nodevice"}}
*** done
diff --git a/tests/qemu-iotests/087 b/tests/qemu-iotests/087
index 869474994..af44299e0 100755
--- a/tests/qemu-iotests/087
+++ b/tests/qemu-iotests/087
@@ -54,7 +54,7 @@ size=128M
_make_test_img $size
echo
-echo === Missing ID ===
+echo === Missing ID and node-name ===
echo
run_qemu <<EOF
diff --git a/tests/qemu-iotests/087.out b/tests/qemu-iotests/087.out
index c71bb3aa4..7d62cd584 100644
--- a/tests/qemu-iotests/087.out
+++ b/tests/qemu-iotests/087.out
@@ -1,16 +1,14 @@
QA output created by 087
Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728
-=== Missing ID ===
+=== Missing ID and node-name ===
Testing:
QMP_VERSION
{"return": {}}
-{"error": {"class": "GenericError", "desc": "Block device needs an ID"}}
+{"error": {"class": "GenericError", "desc": "'id' and/or 'node-name' need to be specified for the root node"}}
{"return": {}}
{"timestamp": {"seconds": TIMESTAMP, "microseconds": TIMESTAMP}, "event": "SHUTDOWN"}
-{"timestamp": {"seconds": TIMESTAMP, "microseconds": TIMESTAMP}, "event": "DEVICE_TRAY_MOVED", "data": {"device": "ide1-cd0", "tray-open": true}}
-{"timestamp": {"seconds": TIMESTAMP, "microseconds": TIMESTAMP}, "event": "DEVICE_TRAY_MOVED", "data": {"device": "floppy0", "tray-open": true}}
=== Duplicate ID ===
@@ -26,8 +24,6 @@ QMP_VERSION
{"error": {"class": "GenericError", "desc": "node-name=disk3 is conflicting with a device id"}}
{"return": {}}
{"timestamp": {"seconds": TIMESTAMP, "microseconds": TIMESTAMP}, "event": "SHUTDOWN"}
-{"timestamp": {"seconds": TIMESTAMP, "microseconds": TIMESTAMP}, "event": "DEVICE_TRAY_MOVED", "data": {"device": "ide1-cd0", "tray-open": true}}
-{"timestamp": {"seconds": TIMESTAMP, "microseconds": TIMESTAMP}, "event": "DEVICE_TRAY_MOVED", "data": {"device": "floppy0", "tray-open": true}}
=== aio=native without O_DIRECT ===
@@ -38,8 +34,6 @@ QMP_VERSION
{"error": {"class": "GenericError", "desc": "aio=native requires cache.direct=true"}}
{"return": {}}
{"timestamp": {"seconds": TIMESTAMP, "microseconds": TIMESTAMP}, "event": "SHUTDOWN"}
-{"timestamp": {"seconds": TIMESTAMP, "microseconds": TIMESTAMP}, "event": "DEVICE_TRAY_MOVED", "data": {"device": "ide1-cd0", "tray-open": true}}
-{"timestamp": {"seconds": TIMESTAMP, "microseconds": TIMESTAMP}, "event": "DEVICE_TRAY_MOVED", "data": {"device": "floppy0", "tray-open": true}}
=== Encrypted image ===
@@ -60,8 +54,6 @@ You can use 'qemu-img convert' to convert your image to an unencrypted one.
{"error": {"class": "GenericError", "desc": "blockdev-add doesn't support encrypted devices"}}
{"return": {}}
{"timestamp": {"seconds": TIMESTAMP, "microseconds": TIMESTAMP}, "event": "SHUTDOWN"}
-{"timestamp": {"seconds": TIMESTAMP, "microseconds": TIMESTAMP}, "event": "DEVICE_TRAY_MOVED", "data": {"device": "ide1-cd0", "tray-open": true}}
-{"timestamp": {"seconds": TIMESTAMP, "microseconds": TIMESTAMP}, "event": "DEVICE_TRAY_MOVED", "data": {"device": "floppy0", "tray-open": true}}
Testing:
QMP_VERSION
@@ -72,8 +64,6 @@ You can use 'qemu-img convert' to convert your image to an unencrypted one.
{"error": {"class": "GenericError", "desc": "Guest must be stopped for opening of encrypted image"}}
{"return": {}}
{"timestamp": {"seconds": TIMESTAMP, "microseconds": TIMESTAMP}, "event": "SHUTDOWN"}
-{"timestamp": {"seconds": TIMESTAMP, "microseconds": TIMESTAMP}, "event": "DEVICE_TRAY_MOVED", "data": {"device": "ide1-cd0", "tray-open": true}}
-{"timestamp": {"seconds": TIMESTAMP, "microseconds": TIMESTAMP}, "event": "DEVICE_TRAY_MOVED", "data": {"device": "floppy0", "tray-open": true}}
=== Missing driver ===
@@ -91,7 +81,5 @@ QMP_VERSION
{"error": {"class": "GenericError", "desc": "Invalid parameter type for 'driver', expected: string"}}
{"return": {}}
{"timestamp": {"seconds": TIMESTAMP, "microseconds": TIMESTAMP}, "event": "SHUTDOWN"}
-{"timestamp": {"seconds": TIMESTAMP, "microseconds": TIMESTAMP}, "event": "DEVICE_TRAY_MOVED", "data": {"device": "ide1-cd0", "tray-open": true}}
-{"timestamp": {"seconds": TIMESTAMP, "microseconds": TIMESTAMP}, "event": "DEVICE_TRAY_MOVED", "data": {"device": "floppy0", "tray-open": true}}
*** done
diff --git a/tests/qemu-iotests/095.out b/tests/qemu-iotests/095.out
index 267c4836e..236006162 100644
--- a/tests/qemu-iotests/095.out
+++ b/tests/qemu-iotests/095.out
@@ -1,7 +1,7 @@
QA output created by 095
Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=5242880
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=104857600 backing_file='TEST_DIR/t.IMGFMT.base'
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=104857600 backing_file='TEST_DIR/t.IMGFMT.snp1'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=104857600 backing_file=TEST_DIR/t.IMGFMT.base
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=104857600 backing_file=TEST_DIR/t.IMGFMT.snp1
=== Base image info before commit and resize ===
image: TEST_DIR/t.IMGFMT.base
diff --git a/tests/qemu-iotests/096 b/tests/qemu-iotests/096
new file mode 100644
index 000000000..e34204b8f
--- /dev/null
+++ b/tests/qemu-iotests/096
@@ -0,0 +1,69 @@
+#!/usr/bin/env python
+#
+# Test that snapshots move the throttling configuration to the active
+# layer
+#
+# Copyright (C) 2015 Igalia, S.L.
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+#
+
+import iotests
+import os
+
+class TestLiveSnapshot(iotests.QMPTestCase):
+ base_img = os.path.join(iotests.test_dir, 'base.img')
+ target_img = os.path.join(iotests.test_dir, 'target.img')
+ group = 'mygroup'
+ iops = 6000
+ iops_size = 1024
+
+ def setUp(self):
+ opts = []
+ opts.append('node-name=base')
+ opts.append('throttling.group=%s' % self.group)
+ opts.append('throttling.iops-total=%d' % self.iops)
+ opts.append('throttling.iops-size=%d' % self.iops_size)
+ iotests.qemu_img('create', '-f', iotests.imgfmt, self.base_img, '100M')
+ self.vm = iotests.VM().add_drive(self.base_img, ','.join(opts))
+ self.vm.launch()
+
+ def tearDown(self):
+ self.vm.shutdown()
+ os.remove(self.base_img)
+ os.remove(self.target_img)
+
+ def checkConfig(self, active_layer):
+ result = self.vm.qmp('query-named-block-nodes')
+ for r in result['return']:
+ if r['node-name'] == active_layer:
+ self.assertEqual(r['group'], self.group)
+ self.assertEqual(r['iops'], self.iops)
+ self.assertEqual(r['iops_size'], self.iops_size)
+ else:
+ self.assertFalse(r.has_key('group'))
+ self.assertEqual(r['iops'], 0)
+ self.assertFalse(r.has_key('iops_size'))
+
+ def testSnapshot(self):
+ self.checkConfig('base')
+ self.vm.qmp('blockdev-snapshot-sync',
+ node_name = 'base',
+ snapshot_node_name = 'target',
+ snapshot_file = self.target_img,
+ format = iotests.imgfmt)
+ self.checkConfig('target')
+
+if __name__ == '__main__':
+ iotests.main(supported_fmts=['qcow2'])
diff --git a/tests/qemu-iotests/096.out b/tests/qemu-iotests/096.out
new file mode 100644
index 000000000..ae1213e6f
--- /dev/null
+++ b/tests/qemu-iotests/096.out
@@ -0,0 +1,5 @@
+.
+----------------------------------------------------------------------
+Ran 1 tests
+
+OK
diff --git a/tests/qemu-iotests/097.out b/tests/qemu-iotests/097.out
index 81651f496..48abd2e64 100644
--- a/tests/qemu-iotests/097.out
+++ b/tests/qemu-iotests/097.out
@@ -3,8 +3,8 @@ QA output created by 097
=== Test pass 0 ===
Formatting 'TEST_DIR/t.IMGFMT.base', fmt=IMGFMT size=67108864
-Formatting 'TEST_DIR/t.IMGFMT.itmd', fmt=IMGFMT size=67108864 backing_file='TEST_DIR/t.IMGFMT.base'
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file='TEST_DIR/t.IMGFMT.itmd'
+Formatting 'TEST_DIR/t.IMGFMT.itmd', fmt=IMGFMT size=67108864 backing_file=TEST_DIR/t.IMGFMT.base
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file=TEST_DIR/t.IMGFMT.itmd
wrote 196608/196608 bytes at offset 0
192 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
wrote 131072/131072 bytes at offset 65536
@@ -32,8 +32,8 @@ Offset Length File
=== Test pass 1 ===
Formatting 'TEST_DIR/t.IMGFMT.base', fmt=IMGFMT size=67108864
-Formatting 'TEST_DIR/t.IMGFMT.itmd', fmt=IMGFMT size=67108864 backing_file='TEST_DIR/t.IMGFMT.base'
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file='TEST_DIR/t.IMGFMT.itmd'
+Formatting 'TEST_DIR/t.IMGFMT.itmd', fmt=IMGFMT size=67108864 backing_file=TEST_DIR/t.IMGFMT.base
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file=TEST_DIR/t.IMGFMT.itmd
wrote 196608/196608 bytes at offset 0
192 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
wrote 131072/131072 bytes at offset 65536
@@ -62,8 +62,8 @@ Offset Length File
=== Test pass 2 ===
Formatting 'TEST_DIR/t.IMGFMT.base', fmt=IMGFMT size=67108864
-Formatting 'TEST_DIR/t.IMGFMT.itmd', fmt=IMGFMT size=67108864 backing_file='TEST_DIR/t.IMGFMT.base'
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file='TEST_DIR/t.IMGFMT.itmd'
+Formatting 'TEST_DIR/t.IMGFMT.itmd', fmt=IMGFMT size=67108864 backing_file=TEST_DIR/t.IMGFMT.base
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file=TEST_DIR/t.IMGFMT.itmd
wrote 196608/196608 bytes at offset 0
192 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
wrote 131072/131072 bytes at offset 65536
@@ -92,8 +92,8 @@ Offset Length File
=== Test pass 3 ===
Formatting 'TEST_DIR/t.IMGFMT.base', fmt=IMGFMT size=67108864
-Formatting 'TEST_DIR/t.IMGFMT.itmd', fmt=IMGFMT size=67108864 backing_file='TEST_DIR/t.IMGFMT.base'
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file='TEST_DIR/t.IMGFMT.itmd'
+Formatting 'TEST_DIR/t.IMGFMT.itmd', fmt=IMGFMT size=67108864 backing_file=TEST_DIR/t.IMGFMT.base
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file=TEST_DIR/t.IMGFMT.itmd
wrote 196608/196608 bytes at offset 0
192 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
wrote 131072/131072 bytes at offset 65536
diff --git a/tests/qemu-iotests/098.out b/tests/qemu-iotests/098.out
index e08a189b4..7634d0e8b 100644
--- a/tests/qemu-iotests/098.out
+++ b/tests/qemu-iotests/098.out
@@ -3,7 +3,7 @@ QA output created by 098
=== l1_update ===
Formatting 'TEST_DIR/t.IMGFMT.base', fmt=IMGFMT size=67108864
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file='TEST_DIR/t.IMGFMT.base'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file=TEST_DIR/t.IMGFMT.base
wrote 65536/65536 bytes at offset 0
64 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
qemu-img: Could not empty blkdebug:TEST_DIR/blkdebug.conf:TEST_DIR/t.IMGFMT: Input/output error
@@ -12,7 +12,7 @@ No errors were found on the image.
=== empty_image_prepare ===
Formatting 'TEST_DIR/t.IMGFMT.base', fmt=IMGFMT size=67108864
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file='TEST_DIR/t.IMGFMT.base'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file=TEST_DIR/t.IMGFMT.base
wrote 65536/65536 bytes at offset 0
64 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
qemu-img: Could not empty blkdebug:TEST_DIR/blkdebug.conf:TEST_DIR/t.IMGFMT: Input/output error
@@ -25,7 +25,7 @@ No errors were found on the image.
=== reftable_update ===
Formatting 'TEST_DIR/t.IMGFMT.base', fmt=IMGFMT size=67108864
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file='TEST_DIR/t.IMGFMT.base'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file=TEST_DIR/t.IMGFMT.base
wrote 65536/65536 bytes at offset 0
64 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
qemu-img: Could not empty blkdebug:TEST_DIR/blkdebug.conf:TEST_DIR/t.IMGFMT: Input/output error
@@ -39,7 +39,7 @@ No errors were found on the image.
=== refblock_alloc ===
Formatting 'TEST_DIR/t.IMGFMT.base', fmt=IMGFMT size=67108864
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file='TEST_DIR/t.IMGFMT.base'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file=TEST_DIR/t.IMGFMT.base
wrote 65536/65536 bytes at offset 0
64 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
qemu-img: Could not empty blkdebug:TEST_DIR/blkdebug.conf:TEST_DIR/t.IMGFMT: Input/output error
diff --git a/tests/qemu-iotests/110.out b/tests/qemu-iotests/110.out
index 152bacf41..0270980c2 100644
--- a/tests/qemu-iotests/110.out
+++ b/tests/qemu-iotests/110.out
@@ -3,7 +3,7 @@ QA output created by 110
=== Reconstructable filename ===
Formatting 'TEST_DIR/t.IMGFMT.base', fmt=IMGFMT size=67108864
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file='t.IMGFMT.base'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file=t.IMGFMT.base
image: TEST_DIR/t.IMGFMT
file format: IMGFMT
virtual size: 64M (67108864 bytes)
@@ -15,5 +15,5 @@ qemu-img: Cannot use relative backing file names for 'json:{"driver": "IMGFMT",
=== Backing name is always relative to the backed image ===
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file='t.IMGFMT.base'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file=t.IMGFMT.base
*** done
diff --git a/tests/qemu-iotests/112.out b/tests/qemu-iotests/112.out
index 9a98633f6..8dd3df087 100644
--- a/tests/qemu-iotests/112.out
+++ b/tests/qemu-iotests/112.out
@@ -21,9 +21,9 @@ refcount bits: 16
Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864
refcount bits: 16
-qemu-img: TEST_DIR/t.IMGFMT: Different refcount widths than 16 bits require compatibility level 1.1 or above (use compat=1.1 or greater)
+qemu-img: TEST_DIR/t.IMGFMT: Different refcount widths than 16 bits require compatibility level 1.1 or above (use or greater)
Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864
-qemu-img: TEST_DIR/t.IMGFMT: Different refcount widths than 16 bits require compatibility level 1.1 or above (use compat=1.1 or greater)
+qemu-img: TEST_DIR/t.IMGFMT: Different refcount widths than 16 bits require compatibility level 1.1 or above (use or greater)
Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864
=== Snapshot limit on refcount_bits=1 ===
diff --git a/tests/qemu-iotests/114.out b/tests/qemu-iotests/114.out
index 6c6b21085..6a2c75056 100644
--- a/tests/qemu-iotests/114.out
+++ b/tests/qemu-iotests/114.out
@@ -1,6 +1,6 @@
QA output created by 114
Formatting 'TEST_DIR/t.IMGFMT.base', fmt=IMGFMT size=67108864
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file='TEST_DIR/t.IMGFMT.base'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file=TEST_DIR/t.IMGFMT.base
image: TEST_DIR/t.IMGFMT
file format: IMGFMT
virtual size: 64M (67108864 bytes)
diff --git a/tests/qemu-iotests/115.out b/tests/qemu-iotests/115.out
index 7b2c5e02f..dbdad17b2 100644
--- a/tests/qemu-iotests/115.out
+++ b/tests/qemu-iotests/115.out
@@ -2,7 +2,7 @@ QA output created by 115
=== Testing large refcount and L1 table ===
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=268435456 preallocation='metadata'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=268435456 preallocation=metadata
No errors were found on the image.
100.00% allocated clusters
*** done
diff --git a/tests/qemu-iotests/118 b/tests/qemu-iotests/118
new file mode 100755
index 000000000..114d0e2de
--- /dev/null
+++ b/tests/qemu-iotests/118
@@ -0,0 +1,720 @@
+#!/usr/bin/env python
+#
+# Test case for the QMP 'change' command and all other associated
+# commands
+#
+# Copyright (C) 2015 Red Hat, Inc.
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+#
+
+import os
+import stat
+import time
+import iotests
+from iotests import qemu_img
+
+old_img = os.path.join(iotests.test_dir, 'test0.img')
+new_img = os.path.join(iotests.test_dir, 'test1.img')
+
+class ChangeBaseClass(iotests.QMPTestCase):
+ has_opened = False
+ has_closed = False
+
+ def process_events(self):
+ for event in self.vm.get_qmp_events(wait=False):
+ if (event['event'] == 'DEVICE_TRAY_MOVED' and
+ event['data']['device'] == 'drive0'):
+ if event['data']['tray-open'] == False:
+ self.has_closed = True
+ else:
+ self.has_opened = True
+
+ def wait_for_open(self):
+ timeout = time.clock() + 3
+ while not self.has_opened and time.clock() < timeout:
+ self.process_events()
+ if not self.has_opened:
+ self.fail('Timeout while waiting for the tray to open')
+
+ def wait_for_close(self):
+ timeout = time.clock() + 3
+ while not self.has_closed and time.clock() < timeout:
+ self.process_events()
+ if not self.has_opened:
+ self.fail('Timeout while waiting for the tray to close')
+
+class GeneralChangeTestsBaseClass(ChangeBaseClass):
+ def test_change(self):
+ result = self.vm.qmp('change', device='drive0', target=new_img,
+ arg=iotests.imgfmt)
+ self.assert_qmp(result, 'return', {})
+
+ self.wait_for_open()
+ self.wait_for_close()
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp(result, 'return[0]/tray_open', False)
+ self.assert_qmp(result, 'return[0]/inserted/image/filename', new_img)
+
+ def test_blockdev_change_medium(self):
+ result = self.vm.qmp('blockdev-change-medium', device='drive0',
+ filename=new_img,
+ format=iotests.imgfmt)
+ self.assert_qmp(result, 'return', {})
+
+ self.wait_for_open()
+ self.wait_for_close()
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp(result, 'return[0]/tray_open', False)
+ self.assert_qmp(result, 'return[0]/inserted/image/filename', new_img)
+
+ def test_eject(self):
+ result = self.vm.qmp('eject', device='drive0', force=True)
+ self.assert_qmp(result, 'return', {})
+
+ self.wait_for_open()
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp(result, 'return[0]/tray_open', True)
+ self.assert_qmp_absent(result, 'return[0]/inserted')
+
+ def test_tray_eject_change(self):
+ result = self.vm.qmp('eject', device='drive0', force=True)
+ self.assert_qmp(result, 'return', {})
+
+ self.wait_for_open()
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp(result, 'return[0]/tray_open', True)
+ self.assert_qmp_absent(result, 'return[0]/inserted')
+
+ result = self.vm.qmp('blockdev-change-medium', device='drive0',
+ filename=new_img,
+ format=iotests.imgfmt)
+ self.assert_qmp(result, 'return', {})
+
+ self.wait_for_close()
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp(result, 'return[0]/tray_open', False)
+ self.assert_qmp(result, 'return[0]/inserted/image/filename', new_img)
+
+ def test_tray_open_close(self):
+ result = self.vm.qmp('blockdev-open-tray', device='drive0', force=True)
+ self.assert_qmp(result, 'return', {})
+
+ self.wait_for_open()
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp(result, 'return[0]/tray_open', True)
+ if self.was_empty == True:
+ self.assert_qmp_absent(result, 'return[0]/inserted')
+ else:
+ self.assert_qmp(result, 'return[0]/inserted/image/filename', old_img)
+
+ result = self.vm.qmp('blockdev-close-tray', device='drive0')
+ self.assert_qmp(result, 'return', {})
+
+ if self.has_real_tray or not self.was_empty:
+ self.wait_for_close()
+
+ result = self.vm.qmp('query-block')
+ if self.has_real_tray or not self.was_empty:
+ self.assert_qmp(result, 'return[0]/tray_open', False)
+ else:
+ self.assert_qmp(result, 'return[0]/tray_open', True)
+ if self.was_empty == True:
+ self.assert_qmp_absent(result, 'return[0]/inserted')
+ else:
+ self.assert_qmp(result, 'return[0]/inserted/image/filename', old_img)
+
+ def test_tray_eject_close(self):
+ result = self.vm.qmp('eject', device='drive0', force=True)
+ self.assert_qmp(result, 'return', {})
+
+ self.wait_for_open()
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp(result, 'return[0]/tray_open', True)
+ self.assert_qmp_absent(result, 'return[0]/inserted')
+
+ result = self.vm.qmp('blockdev-close-tray', device='drive0')
+ self.assert_qmp(result, 'return', {})
+
+ if self.has_real_tray:
+ self.wait_for_close()
+
+ result = self.vm.qmp('query-block')
+ if self.has_real_tray:
+ self.assert_qmp(result, 'return[0]/tray_open', False)
+ else:
+ self.assert_qmp(result, 'return[0]/tray_open', True)
+ self.assert_qmp_absent(result, 'return[0]/inserted')
+
+ def test_tray_open_change(self):
+ result = self.vm.qmp('blockdev-open-tray', device='drive0', force=True)
+ self.assert_qmp(result, 'return', {})
+
+ self.wait_for_open()
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp(result, 'return[0]/tray_open', True)
+ if self.was_empty == True:
+ self.assert_qmp_absent(result, 'return[0]/inserted')
+ else:
+ self.assert_qmp(result, 'return[0]/inserted/image/filename', old_img)
+
+ result = self.vm.qmp('blockdev-change-medium', device='drive0',
+ filename=new_img,
+ format=iotests.imgfmt)
+ self.assert_qmp(result, 'return', {})
+
+ self.wait_for_close()
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp(result, 'return[0]/tray_open', False)
+ self.assert_qmp(result, 'return[0]/inserted/image/filename', new_img)
+
+ def test_cycle(self):
+ result = self.vm.qmp('blockdev-add',
+ options={'node-name': 'new',
+ 'driver': iotests.imgfmt,
+ 'file': {'filename': new_img,
+ 'driver': 'file'}})
+ self.assert_qmp(result, 'return', {})
+
+ result = self.vm.qmp('blockdev-open-tray', device='drive0', force=True)
+ self.assert_qmp(result, 'return', {})
+
+ self.wait_for_open()
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp(result, 'return[0]/tray_open', True)
+ if self.was_empty == True:
+ self.assert_qmp_absent(result, 'return[0]/inserted')
+ else:
+ self.assert_qmp(result, 'return[0]/inserted/image/filename', old_img)
+
+ result = self.vm.qmp('x-blockdev-remove-medium', device='drive0')
+ self.assert_qmp(result, 'return', {})
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp(result, 'return[0]/tray_open', True)
+ self.assert_qmp_absent(result, 'return[0]/inserted')
+
+ result = self.vm.qmp('x-blockdev-insert-medium', device='drive0',
+ node_name='new')
+ self.assert_qmp(result, 'return', {})
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp(result, 'return[0]/tray_open', True)
+ self.assert_qmp(result, 'return[0]/inserted/image/filename', new_img)
+
+ result = self.vm.qmp('blockdev-close-tray', device='drive0')
+ self.assert_qmp(result, 'return', {})
+
+ self.wait_for_close()
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp(result, 'return[0]/tray_open', False)
+ self.assert_qmp(result, 'return[0]/inserted/image/filename', new_img)
+
+ def test_close_on_closed(self):
+ result = self.vm.qmp('blockdev-close-tray', device='drive0')
+ # Should be a no-op
+ self.assert_qmp(result, 'return', {})
+ self.assertEquals(self.vm.get_qmp_events(wait=False), [])
+
+ def test_remove_on_closed(self):
+ if self.has_opened:
+ # Empty floppy drive
+ return
+
+ result = self.vm.qmp('x-blockdev-remove-medium', device='drive0')
+ self.assert_qmp(result, 'error/class', 'GenericError')
+
+ def test_insert_on_closed(self):
+ if self.has_opened:
+ # Empty floppy drive
+ return
+
+ result = self.vm.qmp('blockdev-add',
+ options={'node-name': 'new',
+ 'driver': iotests.imgfmt,
+ 'file': {'filename': new_img,
+ 'driver': 'file'}})
+ self.assert_qmp(result, 'return', {})
+
+ result = self.vm.qmp('x-blockdev-insert-medium', device='drive0',
+ node_name='new')
+ self.assert_qmp(result, 'error/class', 'GenericError')
+
+class TestInitiallyFilled(GeneralChangeTestsBaseClass):
+ was_empty = False
+
+ def setUp(self, media, interface):
+ qemu_img('create', '-f', iotests.imgfmt, old_img, '1440k')
+ qemu_img('create', '-f', iotests.imgfmt, new_img, '1440k')
+ self.vm = iotests.VM().add_drive(old_img, 'media=%s' % media, interface)
+ self.vm.launch()
+
+ def tearDown(self):
+ self.vm.shutdown()
+ os.remove(old_img)
+ os.remove(new_img)
+
+ def test_insert_on_filled(self):
+ result = self.vm.qmp('blockdev-add',
+ options={'node-name': 'new',
+ 'driver': iotests.imgfmt,
+ 'file': {'filename': new_img,
+ 'driver': 'file'}})
+ self.assert_qmp(result, 'return', {})
+
+ result = self.vm.qmp('blockdev-open-tray', device='drive0')
+ self.assert_qmp(result, 'return', {})
+
+ self.wait_for_open()
+
+ result = self.vm.qmp('x-blockdev-insert-medium', device='drive0',
+ node_name='new')
+ self.assert_qmp(result, 'error/class', 'GenericError')
+
+class TestInitiallyEmpty(GeneralChangeTestsBaseClass):
+ was_empty = True
+
+ def setUp(self, media, interface):
+ qemu_img('create', '-f', iotests.imgfmt, new_img, '1440k')
+ self.vm = iotests.VM().add_drive(None, 'media=%s' % media, interface)
+ self.vm.launch()
+
+ def tearDown(self):
+ self.vm.shutdown()
+ os.remove(new_img)
+
+ def test_remove_on_empty(self):
+ result = self.vm.qmp('blockdev-open-tray', device='drive0')
+ self.assert_qmp(result, 'return', {})
+
+ self.wait_for_open()
+
+ result = self.vm.qmp('x-blockdev-remove-medium', device='drive0')
+ # Should be a no-op
+ self.assert_qmp(result, 'return', {})
+
+class TestCDInitiallyFilled(TestInitiallyFilled):
+ TestInitiallyFilled = TestInitiallyFilled
+ has_real_tray = True
+
+ def setUp(self):
+ self.TestInitiallyFilled.setUp(self, 'cdrom', 'ide')
+
+class TestCDInitiallyEmpty(TestInitiallyEmpty):
+ TestInitiallyEmpty = TestInitiallyEmpty
+ has_real_tray = True
+
+ def setUp(self):
+ self.TestInitiallyEmpty.setUp(self, 'cdrom', 'ide')
+
+class TestFloppyInitiallyFilled(TestInitiallyFilled):
+ TestInitiallyFilled = TestInitiallyFilled
+ has_real_tray = False
+
+ def setUp(self):
+ self.TestInitiallyFilled.setUp(self, 'disk', 'floppy')
+
+class TestFloppyInitiallyEmpty(TestInitiallyEmpty):
+ TestInitiallyEmpty = TestInitiallyEmpty
+ has_real_tray = False
+
+ def setUp(self):
+ self.TestInitiallyEmpty.setUp(self, 'disk', 'floppy')
+ # FDDs not having a real tray and there not being a medium inside the
+ # tray at startup means the tray will be considered open
+ self.has_opened = True
+
+class TestChangeReadOnly(ChangeBaseClass):
+ def setUp(self):
+ qemu_img('create', '-f', iotests.imgfmt, old_img, '1440k')
+ qemu_img('create', '-f', iotests.imgfmt, new_img, '1440k')
+ self.vm = iotests.VM()
+
+ def tearDown(self):
+ self.vm.shutdown()
+ os.chmod(old_img, 0666)
+ os.chmod(new_img, 0666)
+ os.remove(old_img)
+ os.remove(new_img)
+
+ def test_ro_ro_retain(self):
+ os.chmod(old_img, 0444)
+ os.chmod(new_img, 0444)
+ self.vm.add_drive(old_img, 'media=disk,read-only=on', 'floppy')
+ self.vm.launch()
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp(result, 'return[0]/tray_open', False)
+ self.assert_qmp(result, 'return[0]/inserted/ro', True)
+ self.assert_qmp(result, 'return[0]/inserted/image/filename', old_img)
+
+ result = self.vm.qmp('blockdev-change-medium', device='drive0',
+ filename=new_img,
+ format=iotests.imgfmt,
+ read_only_mode='retain')
+ self.assert_qmp(result, 'return', {})
+
+ self.wait_for_open()
+ self.wait_for_close()
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp(result, 'return[0]/tray_open', False)
+ self.assert_qmp(result, 'return[0]/inserted/ro', True)
+ self.assert_qmp(result, 'return[0]/inserted/image/filename', new_img)
+
+ def test_ro_rw_retain(self):
+ os.chmod(old_img, 0444)
+ self.vm.add_drive(old_img, 'media=disk,read-only=on', 'floppy')
+ self.vm.launch()
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp(result, 'return[0]/tray_open', False)
+ self.assert_qmp(result, 'return[0]/inserted/ro', True)
+ self.assert_qmp(result, 'return[0]/inserted/image/filename', old_img)
+
+ result = self.vm.qmp('blockdev-change-medium', device='drive0',
+ filename=new_img,
+ format=iotests.imgfmt,
+ read_only_mode='retain')
+ self.assert_qmp(result, 'return', {})
+
+ self.wait_for_open()
+ self.wait_for_close()
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp(result, 'return[0]/tray_open', False)
+ self.assert_qmp(result, 'return[0]/inserted/ro', True)
+ self.assert_qmp(result, 'return[0]/inserted/image/filename', new_img)
+
+ def test_rw_ro_retain(self):
+ os.chmod(new_img, 0444)
+ self.vm.add_drive(old_img, 'media=disk', 'floppy')
+ self.vm.launch()
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp(result, 'return[0]/tray_open', False)
+ self.assert_qmp(result, 'return[0]/inserted/ro', False)
+ self.assert_qmp(result, 'return[0]/inserted/image/filename', old_img)
+
+ result = self.vm.qmp('blockdev-change-medium', device='drive0',
+ filename=new_img,
+ format=iotests.imgfmt,
+ read_only_mode='retain')
+ self.assert_qmp(result, 'error/class', 'GenericError')
+
+ self.assertEquals(self.vm.get_qmp_events(wait=False), [])
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp(result, 'return[0]/tray_open', False)
+ self.assert_qmp(result, 'return[0]/inserted/ro', False)
+ self.assert_qmp(result, 'return[0]/inserted/image/filename', old_img)
+
+ def test_ro_rw(self):
+ os.chmod(old_img, 0444)
+ self.vm.add_drive(old_img, 'media=disk,read-only=on', 'floppy')
+ self.vm.launch()
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp(result, 'return[0]/tray_open', False)
+ self.assert_qmp(result, 'return[0]/inserted/ro', True)
+ self.assert_qmp(result, 'return[0]/inserted/image/filename', old_img)
+
+ result = self.vm.qmp('blockdev-change-medium',
+ device='drive0',
+ filename=new_img,
+ format=iotests.imgfmt,
+ read_only_mode='read-write')
+ self.assert_qmp(result, 'return', {})
+
+ self.wait_for_open()
+ self.wait_for_close()
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp(result, 'return[0]/tray_open', False)
+ self.assert_qmp(result, 'return[0]/inserted/ro', False)
+ self.assert_qmp(result, 'return[0]/inserted/image/filename', new_img)
+
+ def test_rw_ro(self):
+ os.chmod(new_img, 0444)
+ self.vm.add_drive(old_img, 'media=disk', 'floppy')
+ self.vm.launch()
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp(result, 'return[0]/tray_open', False)
+ self.assert_qmp(result, 'return[0]/inserted/ro', False)
+ self.assert_qmp(result, 'return[0]/inserted/image/filename', old_img)
+
+ result = self.vm.qmp('blockdev-change-medium',
+ device='drive0',
+ filename=new_img,
+ format=iotests.imgfmt,
+ read_only_mode='read-only')
+ self.assert_qmp(result, 'return', {})
+
+ self.wait_for_open()
+ self.wait_for_close()
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp(result, 'return[0]/tray_open', False)
+ self.assert_qmp(result, 'return[0]/inserted/ro', True)
+ self.assert_qmp(result, 'return[0]/inserted/image/filename', new_img)
+
+ def test_make_rw_ro(self):
+ self.vm.add_drive(old_img, 'media=disk', 'floppy')
+ self.vm.launch()
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp(result, 'return[0]/tray_open', False)
+ self.assert_qmp(result, 'return[0]/inserted/ro', False)
+ self.assert_qmp(result, 'return[0]/inserted/image/filename', old_img)
+
+ result = self.vm.qmp('blockdev-change-medium',
+ device='drive0',
+ filename=new_img,
+ format=iotests.imgfmt,
+ read_only_mode='read-only')
+ self.assert_qmp(result, 'return', {})
+
+ self.wait_for_open()
+ self.wait_for_close()
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp(result, 'return[0]/tray_open', False)
+ self.assert_qmp(result, 'return[0]/inserted/ro', True)
+ self.assert_qmp(result, 'return[0]/inserted/image/filename', new_img)
+
+ def test_make_ro_rw(self):
+ os.chmod(new_img, 0444)
+ self.vm.add_drive(old_img, 'media=disk', 'floppy')
+ self.vm.launch()
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp(result, 'return[0]/tray_open', False)
+ self.assert_qmp(result, 'return[0]/inserted/ro', False)
+ self.assert_qmp(result, 'return[0]/inserted/image/filename', old_img)
+
+ result = self.vm.qmp('blockdev-change-medium',
+ device='drive0',
+ filename=new_img,
+ format=iotests.imgfmt,
+ read_only_mode='read-write')
+ self.assert_qmp(result, 'error/class', 'GenericError')
+
+ self.assertEquals(self.vm.get_qmp_events(wait=False), [])
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp(result, 'return[0]/tray_open', False)
+ self.assert_qmp(result, 'return[0]/inserted/ro', False)
+ self.assert_qmp(result, 'return[0]/inserted/image/filename', old_img)
+
+ def test_make_rw_ro_by_retain(self):
+ os.chmod(old_img, 0444)
+ self.vm.add_drive(old_img, 'media=disk,read-only=on', 'floppy')
+ self.vm.launch()
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp(result, 'return[0]/tray_open', False)
+ self.assert_qmp(result, 'return[0]/inserted/ro', True)
+ self.assert_qmp(result, 'return[0]/inserted/image/filename', old_img)
+
+ result = self.vm.qmp('blockdev-change-medium', device='drive0',
+ filename=new_img,
+ format=iotests.imgfmt,
+ read_only_mode='retain')
+ self.assert_qmp(result, 'return', {})
+
+ self.wait_for_open()
+ self.wait_for_close()
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp(result, 'return[0]/tray_open', False)
+ self.assert_qmp(result, 'return[0]/inserted/ro', True)
+ self.assert_qmp(result, 'return[0]/inserted/image/filename', new_img)
+
+ def test_make_ro_rw_by_retain(self):
+ os.chmod(new_img, 0444)
+ self.vm.add_drive(old_img, 'media=disk', 'floppy')
+ self.vm.launch()
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp(result, 'return[0]/tray_open', False)
+ self.assert_qmp(result, 'return[0]/inserted/ro', False)
+ self.assert_qmp(result, 'return[0]/inserted/image/filename', old_img)
+
+ result = self.vm.qmp('blockdev-change-medium', device='drive0',
+ filename=new_img,
+ format=iotests.imgfmt,
+ read_only_mode='retain')
+ self.assert_qmp(result, 'error/class', 'GenericError')
+
+ self.assertEquals(self.vm.get_qmp_events(wait=False), [])
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp(result, 'return[0]/tray_open', False)
+ self.assert_qmp(result, 'return[0]/inserted/ro', False)
+ self.assert_qmp(result, 'return[0]/inserted/image/filename', old_img)
+
+ def test_rw_ro_cycle(self):
+ os.chmod(new_img, 0444)
+ self.vm.add_drive(old_img, 'media=disk', 'floppy')
+ self.vm.launch()
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp(result, 'return[0]/tray_open', False)
+ self.assert_qmp(result, 'return[0]/inserted/ro', False)
+ self.assert_qmp(result, 'return[0]/inserted/image/filename', old_img)
+
+ result = self.vm.qmp('blockdev-add',
+ options={'node-name': 'new',
+ 'driver': iotests.imgfmt,
+ 'read-only': True,
+ 'file': {'filename': new_img,
+ 'driver': 'file'}})
+ self.assert_qmp(result, 'return', {})
+
+ result = self.vm.qmp('blockdev-open-tray', device='drive0', force=True)
+ self.assert_qmp(result, 'return', {})
+
+ self.wait_for_open()
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp(result, 'return[0]/tray_open', True)
+ self.assert_qmp(result, 'return[0]/inserted/ro', False)
+ self.assert_qmp(result, 'return[0]/inserted/image/filename', old_img)
+
+ result = self.vm.qmp('x-blockdev-remove-medium', device='drive0')
+ self.assert_qmp(result, 'return', {})
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp(result, 'return[0]/tray_open', True)
+ self.assert_qmp_absent(result, 'return[0]/inserted')
+
+ result = self.vm.qmp('x-blockdev-insert-medium', device='drive0',
+ node_name='new')
+ self.assert_qmp(result, 'return', {})
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp(result, 'return[0]/tray_open', True)
+ self.assert_qmp(result, 'return[0]/inserted/ro', True)
+ self.assert_qmp(result, 'return[0]/inserted/image/filename', new_img)
+
+ result = self.vm.qmp('blockdev-close-tray', device='drive0')
+ self.assert_qmp(result, 'return', {})
+
+ self.wait_for_close()
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp(result, 'return[0]/tray_open', False)
+ self.assert_qmp(result, 'return[0]/inserted/ro', True)
+ self.assert_qmp(result, 'return[0]/inserted/image/filename', new_img)
+
+GeneralChangeTestsBaseClass = None
+TestInitiallyFilled = None
+TestInitiallyEmpty = None
+
+
+class TestBlockJobsAfterCycle(ChangeBaseClass):
+ def setUp(self):
+ qemu_img('create', '-f', iotests.imgfmt, old_img, '1M')
+
+ self.vm = iotests.VM()
+ self.vm.launch()
+
+ result = self.vm.qmp('blockdev-add',
+ options={'id': 'drive0',
+ 'driver': 'null-co'})
+ self.assert_qmp(result, 'return', {})
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp(result, 'return[0]/tray_open', False)
+ self.assert_qmp(result, 'return[0]/inserted/image/format', 'null-co')
+
+ # For device-less BBs, calling blockdev-open-tray or blockdev-close-tray
+ # is not necessary
+ result = self.vm.qmp('x-blockdev-remove-medium', device='drive0')
+ self.assert_qmp(result, 'return', {})
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp_absent(result, 'return[0]/inserted')
+
+ result = self.vm.qmp('blockdev-add',
+ options={'node-name': 'node0',
+ 'driver': iotests.imgfmt,
+ 'file': {'filename': old_img,
+ 'driver': 'file'}})
+ self.assert_qmp(result, 'return', {})
+
+ result = self.vm.qmp('x-blockdev-insert-medium', device='drive0',
+ node_name='node0')
+ self.assert_qmp(result, 'return', {})
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp(result, 'return[0]/tray_open', False)
+ self.assert_qmp(result, 'return[0]/inserted/image/filename', old_img)
+
+ def tearDown(self):
+ self.vm.shutdown()
+ os.remove(old_img)
+ try:
+ os.remove(new_img)
+ except OSError:
+ pass
+
+ def test_snapshot_and_commit(self):
+ # We need backing file support
+ if iotests.imgfmt != 'qcow2' and iotests.imgfmt != 'qed':
+ return
+
+ result = self.vm.qmp('blockdev-snapshot-sync', device='drive0',
+ snapshot_file=new_img,
+ format=iotests.imgfmt)
+ self.assert_qmp(result, 'return', {})
+
+ result = self.vm.qmp('query-block')
+ self.assert_qmp(result, 'return[0]/inserted/image/filename', new_img)
+ self.assert_qmp(result,
+ 'return[0]/inserted/image/backing-image/filename',
+ old_img)
+
+ result = self.vm.qmp('block-commit', device='drive0')
+ self.assert_qmp(result, 'return', {})
+
+ self.vm.event_wait(name='BLOCK_JOB_READY')
+
+ result = self.vm.qmp('query-block-jobs')
+ self.assert_qmp(result, 'return[0]/device', 'drive0')
+
+ result = self.vm.qmp('block-job-complete', device='drive0')
+ self.assert_qmp(result, 'return', {})
+
+ self.vm.event_wait(name='BLOCK_JOB_COMPLETED')
+
+
+if __name__ == '__main__':
+ if iotests.qemu_default_machine != 'pc':
+ # We need floppy and IDE CD-ROM
+ iotests.notrun('not suitable for this machine type: %s' %
+ iotests.qemu_default_machine)
+ iotests.main()
diff --git a/tests/qemu-iotests/118.out b/tests/qemu-iotests/118.out
new file mode 100644
index 000000000..6a917130b
--- /dev/null
+++ b/tests/qemu-iotests/118.out
@@ -0,0 +1,5 @@
+...........................................................
+----------------------------------------------------------------------
+Ran 59 tests
+
+OK
diff --git a/tests/qemu-iotests/119 b/tests/qemu-iotests/119
index 9a11f1b92..cc6ec0770 100755
--- a/tests/qemu-iotests/119
+++ b/tests/qemu-iotests/119
@@ -49,7 +49,7 @@ echo "{'execute': 'qmp_capabilities'}
{'execute': 'human-monitor-command',
'arguments': {'command-line': 'qemu-io drv \"read -P 0 0 64k\"'}}
{'execute': 'quit'}" \
- | $QEMU -drive id=drv,if=none,file="$TEST_IMG",driver=nbd \
+ | $QEMU -nographic -drive id=drv,if=none,file="$TEST_IMG",driver=nbd \
-qmp stdio -nodefaults \
| _filter_qmp | _filter_qemu_io
diff --git a/tests/qemu-iotests/120 b/tests/qemu-iotests/120
index 9f1307876..d899a3f52 100755
--- a/tests/qemu-iotests/120
+++ b/tests/qemu-iotests/120
@@ -49,7 +49,7 @@ echo "{'execute': 'qmp_capabilities'}
{'execute': 'human-monitor-command',
'arguments': {'command-line': 'qemu-io drv \"write -P 42 0 64k\"'}}
{'execute': 'quit'}" \
- | $QEMU -qmp stdio -nodefaults \
+ | $QEMU -qmp stdio -nographic -nodefaults \
-drive id=drv,if=none,file="$TEST_IMG",driver=raw,file.driver=$IMGFMT \
| _filter_qmp | _filter_qemu_io
$QEMU_IO -c 'read -P 42 0 64k' "$TEST_IMG" | _filter_qemu_io
diff --git a/tests/qemu-iotests/121.out b/tests/qemu-iotests/121.out
index ff18e2c61..5961a44cd 100644
--- a/tests/qemu-iotests/121.out
+++ b/tests/qemu-iotests/121.out
@@ -4,7 +4,7 @@ QA output created by 121
--- Test 1 ---
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=66060288 preallocation='metadata'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=66060288 preallocation=metadata
Image resized.
wrote 1049600/1049600 bytes at offset 65011712
1.001 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
@@ -14,7 +14,7 @@ No errors were found on the image.
--- Test 2 ---
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=66061312 preallocation='metadata'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=66061312 preallocation=metadata
Image resized.
wrote 133120/133120 bytes at offset 66060288
130 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
diff --git a/tests/qemu-iotests/122.out b/tests/qemu-iotests/122.out
index 1f853b9e9..0068e9674 100644
--- a/tests/qemu-iotests/122.out
+++ b/tests/qemu-iotests/122.out
@@ -5,7 +5,7 @@ wrote 67108864/67108864 bytes at offset 0
=== Check allocation status regression with -B ===
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file='TEST_DIR/t.IMGFMT.base'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file=TEST_DIR/t.IMGFMT.base
wrote 3145728/3145728 bytes at offset 0
3 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
Offset Length File
@@ -14,7 +14,7 @@ Offset Length File
=== Check that zero clusters are kept in overlay ===
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file='TEST_DIR/t.IMGFMT.base'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file=TEST_DIR/t.IMGFMT.base
wrote 3145728/3145728 bytes at offset 0
3 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
read 3145728/3145728 bytes at offset 0
@@ -125,7 +125,7 @@ read 63963136/63963136 bytes at offset 3145728
Formatting 'TEST_DIR/t.IMGFMT.base', fmt=IMGFMT size=67108864
wrote 33554432/33554432 bytes at offset 0
32 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file='TEST_DIR/t.IMGFMT.base'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file=TEST_DIR/t.IMGFMT.base
wrote 3145728/3145728 bytes at offset 0
3 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
diff --git a/tests/qemu-iotests/124 b/tests/qemu-iotests/124
index 9ccd11809..c928f0101 100644
--- a/tests/qemu-iotests/124
+++ b/tests/qemu-iotests/124
@@ -36,6 +36,23 @@ def try_remove(img):
pass
+def transaction_action(action, **kwargs):
+ return {
+ 'type': action,
+ 'data': dict((k.replace('_', '-'), v) for k, v in kwargs.iteritems())
+ }
+
+
+def transaction_bitmap_clear(node, name, **kwargs):
+ return transaction_action('block-dirty-bitmap-clear',
+ node=node, name=name, **kwargs)
+
+
+def transaction_drive_backup(device, target, **kwargs):
+ return transaction_action('drive-backup', device=device, target=target,
+ **kwargs)
+
+
class Bitmap:
def __init__(self, name, drive):
self.name = name
@@ -122,9 +139,12 @@ class TestIncrementalBackup(iotests.QMPTestCase):
def do_qmp_backup(self, error='Input/output error', **kwargs):
res = self.vm.qmp('drive-backup', **kwargs)
self.assert_qmp(res, 'return', {})
+ return self.wait_qmp_backup(kwargs['device'], error)
+
+ def wait_qmp_backup(self, device, error='Input/output error'):
event = self.vm.event_wait(name="BLOCK_JOB_COMPLETED",
- match={'data': {'device': kwargs['device']}})
+ match={'data': {'device': device}})
self.assertNotEqual(event, None)
try:
@@ -139,6 +159,12 @@ class TestIncrementalBackup(iotests.QMPTestCase):
return False
+ def wait_qmp_backup_cancelled(self, device):
+ event = self.vm.event_wait(name='BLOCK_JOB_CANCELLED',
+ match={'data': {'device': device}})
+ self.assertNotEqual(event, None)
+
+
def create_anchor_backup(self, drive=None):
if drive is None:
drive = self.drives[-1]
@@ -264,6 +290,43 @@ class TestIncrementalBackup(iotests.QMPTestCase):
return self.do_incremental_simple(granularity=131072)
+ def test_incremental_transaction(self):
+ '''Test: Verify backups made from transactionally created bitmaps.
+
+ Create a bitmap "before" VM execution begins, then create a second
+ bitmap AFTER writes have already occurred. Use transactions to create
+ a full backup and synchronize both bitmaps to this backup.
+ Create an incremental backup through both bitmaps and verify that
+ both backups match the current drive0 image.
+ '''
+
+ drive0 = self.drives[0]
+ bitmap0 = self.add_bitmap('bitmap0', drive0)
+ self.hmp_io_writes(drive0['id'], (('0xab', 0, 512),
+ ('0xfe', '16M', '256k'),
+ ('0x64', '32736k', '64k')))
+ bitmap1 = self.add_bitmap('bitmap1', drive0)
+
+ result = self.vm.qmp('transaction', actions=[
+ transaction_bitmap_clear(bitmap0.drive['id'], bitmap0.name),
+ transaction_bitmap_clear(bitmap1.drive['id'], bitmap1.name),
+ transaction_drive_backup(drive0['id'], drive0['backup'],
+ sync='full', format=drive0['fmt'])
+ ])
+ self.assert_qmp(result, 'return', {})
+ self.wait_until_completed(drive0['id'])
+ self.files.append(drive0['backup'])
+
+ self.hmp_io_writes(drive0['id'], (('0x9a', 0, 512),
+ ('0x55', '8M', '352k'),
+ ('0x78', '15872k', '1M')))
+ # Both bitmaps should be correctly in sync.
+ self.create_incremental(bitmap0)
+ self.create_incremental(bitmap1)
+ self.vm.shutdown()
+ self.check_backups()
+
+
def test_incremental_failure(self):
'''Test: Verify backups made after a failure are correct.
@@ -321,6 +384,123 @@ class TestIncrementalBackup(iotests.QMPTestCase):
self.check_backups()
+ def test_transaction_failure(self):
+ '''Test: Verify backups made from a transaction that partially fails.
+
+ Add a second drive with its own unique pattern, and add a bitmap to each
+ drive. Use blkdebug to interfere with the backup on just one drive and
+ attempt to create a coherent incremental backup across both drives.
+
+ verify a failure in one but not both, then delete the failed stubs and
+ re-run the same transaction.
+
+ verify that both incrementals are created successfully.
+ '''
+
+ # Create a second drive, with pattern:
+ drive1 = self.add_node('drive1')
+ self.img_create(drive1['file'], drive1['fmt'])
+ io_write_patterns(drive1['file'], (('0x14', 0, 512),
+ ('0x5d', '1M', '32k'),
+ ('0xcd', '32M', '124k')))
+
+ # Create a blkdebug interface to this img as 'drive1'
+ result = self.vm.qmp('blockdev-add', options={
+ 'id': drive1['id'],
+ 'driver': drive1['fmt'],
+ 'file': {
+ 'driver': 'blkdebug',
+ 'image': {
+ 'driver': 'file',
+ 'filename': drive1['file']
+ },
+ 'set-state': [{
+ 'event': 'flush_to_disk',
+ 'state': 1,
+ 'new_state': 2
+ }],
+ 'inject-error': [{
+ 'event': 'read_aio',
+ 'errno': 5,
+ 'state': 2,
+ 'immediately': False,
+ 'once': True
+ }],
+ }
+ })
+ self.assert_qmp(result, 'return', {})
+
+ # Create bitmaps and full backups for both drives
+ drive0 = self.drives[0]
+ dr0bm0 = self.add_bitmap('bitmap0', drive0)
+ dr1bm0 = self.add_bitmap('bitmap0', drive1)
+ self.create_anchor_backup(drive0)
+ self.create_anchor_backup(drive1)
+ self.assert_no_active_block_jobs()
+ self.assertFalse(self.vm.get_qmp_events(wait=False))
+
+ # Emulate some writes
+ self.hmp_io_writes(drive0['id'], (('0xab', 0, 512),
+ ('0xfe', '16M', '256k'),
+ ('0x64', '32736k', '64k')))
+ self.hmp_io_writes(drive1['id'], (('0xba', 0, 512),
+ ('0xef', '16M', '256k'),
+ ('0x46', '32736k', '64k')))
+
+ # Create incremental backup targets
+ target0 = self.prepare_backup(dr0bm0)
+ target1 = self.prepare_backup(dr1bm0)
+
+ # Ask for a new incremental backup per-each drive,
+ # expecting drive1's backup to fail:
+ transaction = [
+ transaction_drive_backup(drive0['id'], target0, sync='incremental',
+ format=drive0['fmt'], mode='existing',
+ bitmap=dr0bm0.name),
+ transaction_drive_backup(drive1['id'], target1, sync='incremental',
+ format=drive1['fmt'], mode='existing',
+ bitmap=dr1bm0.name)
+ ]
+ result = self.vm.qmp('transaction', actions=transaction,
+ properties={'completion-mode': 'grouped'} )
+ self.assert_qmp(result, 'return', {})
+
+ # Observe that drive0's backup is cancelled and drive1 completes with
+ # an error.
+ self.wait_qmp_backup_cancelled(drive0['id'])
+ self.assertFalse(self.wait_qmp_backup(drive1['id']))
+ error = self.vm.event_wait('BLOCK_JOB_ERROR')
+ self.assert_qmp(error, 'data', {'device': drive1['id'],
+ 'action': 'report',
+ 'operation': 'read'})
+ self.assertFalse(self.vm.get_qmp_events(wait=False))
+ self.assert_no_active_block_jobs()
+
+ # Delete drive0's successful target and eliminate our record of the
+ # unsuccessful drive1 target. Then re-run the same transaction.
+ dr0bm0.del_target()
+ dr1bm0.del_target()
+ target0 = self.prepare_backup(dr0bm0)
+ target1 = self.prepare_backup(dr1bm0)
+
+ # Re-run the exact same transaction.
+ result = self.vm.qmp('transaction', actions=transaction,
+ properties={'completion-mode':'grouped'})
+ self.assert_qmp(result, 'return', {})
+
+ # Both should complete successfully this time.
+ self.assertTrue(self.wait_qmp_backup(drive0['id']))
+ self.assertTrue(self.wait_qmp_backup(drive1['id']))
+ self.make_reference_backup(dr0bm0)
+ self.make_reference_backup(dr1bm0)
+ self.assertFalse(self.vm.get_qmp_events(wait=False))
+ self.assert_no_active_block_jobs()
+
+ # And the images should of course validate.
+ self.vm.shutdown()
+ self.check_backups()
+
+
def test_sync_dirty_bitmap_missing(self):
self.assert_no_active_block_jobs()
self.files.append(self.err_img)
diff --git a/tests/qemu-iotests/124.out b/tests/qemu-iotests/124.out
index 2f7d3902f..dae404e27 100644
--- a/tests/qemu-iotests/124.out
+++ b/tests/qemu-iotests/124.out
@@ -1,5 +1,5 @@
-.......
+.........
----------------------------------------------------------------------
-Ran 7 tests
+Ran 9 tests
OK
diff --git a/tests/qemu-iotests/128 b/tests/qemu-iotests/128
index e2a0f2f89..3d8107d2a 100755
--- a/tests/qemu-iotests/128
+++ b/tests/qemu-iotests/128
@@ -31,6 +31,11 @@ status=1 # failure is the default!
devname="eiodev$$"
sudo=""
+_sudo_qemu_io_wrapper()
+{
+ (exec $sudo "$QEMU_IO_PROG" $QEMU_IO_OPTIONS "$@")
+}
+
_setup_eiodev()
{
# This test should either be run as root or with passwordless sudo
@@ -76,7 +81,9 @@ TEST_IMG="/dev/mapper/$devname"
echo
echo "== reading from error device =="
# Opening image should succeed but the read operation should fail
-$sudo $QEMU_IO --format "$IMGFMT" --nocache -c "read 0 65536" "$TEST_IMG" | _filter_qemu_io
+_sudo_qemu_io_wrapper --format "$IMGFMT" --nocache \
+ -c "read 0 65536" "$TEST_IMG" \
+ | _filter_qemu_io
# success, all done
echo "*** done"
diff --git a/tests/qemu-iotests/130 b/tests/qemu-iotests/130
index bc26247e3..9209992da 100755
--- a/tests/qemu-iotests/130
+++ b/tests/qemu-iotests/130
@@ -59,8 +59,8 @@ echo
# bdrv_make_empty() involves a header update for qcow2
# Test that a backing file isn't written
-_launch_qemu -drive file="$TEST_IMG",backing.file.filename="$TEST_IMG.base"
-_send_qemu_cmd $QEMU_HANDLE "commit ide0-hd0" "(qemu)"
+_launch_qemu -drive id=testdisk,file="$TEST_IMG",backing.file.filename="$TEST_IMG.base"
+_send_qemu_cmd $QEMU_HANDLE "commit testdisk" "(qemu)"
_send_qemu_cmd $QEMU_HANDLE '' '(qemu)'
_cleanup_qemu
_img_info | _filter_img_info
@@ -68,8 +68,8 @@ _img_info | _filter_img_info
# Make sure that if there was a backing file that was just overridden on the
# command line, that backing file is retained, with the right format
_make_test_img -F raw -b "$TEST_IMG.orig" 64M
-_launch_qemu -drive file="$TEST_IMG",backing.file.filename="$TEST_IMG.base",backing.driver=$IMGFMT
-_send_qemu_cmd $QEMU_HANDLE "commit ide0-hd0" "(qemu)"
+_launch_qemu -drive id=testdisk,file="$TEST_IMG",backing.file.filename="$TEST_IMG.base",backing.driver=$IMGFMT
+_send_qemu_cmd $QEMU_HANDLE "commit testdisk" "(qemu)"
_send_qemu_cmd $QEMU_HANDLE '' '(qemu)'
_cleanup_qemu
_img_info | _filter_img_info
diff --git a/tests/qemu-iotests/130.out b/tests/qemu-iotests/130.out
index ea68b5d28..ae95b5027 100644
--- a/tests/qemu-iotests/130.out
+++ b/tests/qemu-iotests/130.out
@@ -9,14 +9,14 @@ virtual size: 64M (67108864 bytes)
=== HMP commit ===
QEMU X.Y.Z monitor - type 'help' for more information
-(qemu) ccocomcommcommicommitcommit commit icommit idcommit idecommit ide0commit ide0-commit ide0-hcommit ide0-hdcommit ide0-hd0
+(qemu) ccocomcommcommicommitcommit commit tcommit tecommit tescommit testcommit testdcommit testdicommit testdiscommit testdisk
(qemu)
image: TEST_DIR/t.IMGFMT
file format: IMGFMT
virtual size: 64M (67108864 bytes)
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file='TEST_DIR/t.IMGFMT.orig' backing_fmt='raw'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file=TEST_DIR/t.IMGFMT.orig backing_fmt=raw
QEMU X.Y.Z monitor - type 'help' for more information
-(qemu) ccocomcommcommicommitcommit commit icommit idcommit idecommit ide0commit ide0-commit ide0-hcommit ide0-hdcommit ide0-hd0
+(qemu) ccocomcommcommicommitcommit commit tcommit tecommit tescommit testcommit testdcommit testdicommit testdiscommit testdisk
(qemu)
image: TEST_DIR/t.IMGFMT
file format: IMGFMT
@@ -32,7 +32,7 @@ wrote 4096/4096 bytes at offset 0
image: TEST_DIR/t.IMGFMT
file format: IMGFMT
virtual size: 64M (67108864 bytes)
-Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file='TEST_DIR/t.IMGFMT.orig' backing_fmt='raw'
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 backing_file=TEST_DIR/t.IMGFMT.orig backing_fmt=raw
wrote 4096/4096 bytes at offset 0
4 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
image: TEST_DIR/t.IMGFMT
diff --git a/tests/qemu-iotests/136 b/tests/qemu-iotests/136
new file mode 100644
index 000000000..e8c6937fc
--- /dev/null
+++ b/tests/qemu-iotests/136
@@ -0,0 +1,349 @@
+#!/usr/bin/env python
+#
+# Tests for block device statistics
+#
+# Copyright (C) 2015 Igalia, S.L.
+# Author: Alberto Garcia <berto@igalia.com>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+#
+
+import iotests
+import os
+
+interval_length = 10
+nsec_per_sec = 1000000000
+op_latency = nsec_per_sec / 1000 # See qtest_latency_ns in accounting.c
+bad_sector = 8192
+bad_offset = bad_sector * 512
+blkdebug_file = os.path.join(iotests.test_dir, 'blkdebug.conf')
+
+class BlockDeviceStatsTestCase(iotests.QMPTestCase):
+ test_img = "null-aio://"
+ total_rd_bytes = 0
+ total_rd_ops = 0
+ total_wr_bytes = 0
+ total_wr_ops = 0
+ total_wr_merged = 0
+ total_flush_ops = 0
+ failed_rd_ops = 0
+ failed_wr_ops = 0
+ invalid_rd_ops = 0
+ invalid_wr_ops = 0
+ wr_highest_offset = 0
+ account_invalid = False
+ account_failed = False
+
+ def blockstats(self, device):
+ result = self.vm.qmp("query-blockstats")
+ for r in result['return']:
+ if r['device'] == device:
+ return r['stats']
+ raise Exception("Device not found for blockstats: %s" % device)
+
+ def create_blkdebug_file(self):
+ file = open(blkdebug_file, 'w')
+ file.write('''
+[inject-error]
+event = "read_aio"
+errno = "5"
+sector = "%d"
+
+[inject-error]
+event = "write_aio"
+errno = "5"
+sector = "%d"
+''' % (bad_sector, bad_sector))
+ file.close()
+
+ def setUp(self):
+ drive_args = []
+ drive_args.append("stats-intervals.0=%d" % interval_length)
+ drive_args.append("stats-account-invalid=%s" %
+ (self.account_invalid and "on" or "off"))
+ drive_args.append("stats-account-failed=%s" %
+ (self.account_failed and "on" or "off"))
+ self.create_blkdebug_file()
+ self.vm = iotests.VM().add_drive('blkdebug:%s:%s ' %
+ (blkdebug_file, self.test_img),
+ ','.join(drive_args))
+ self.vm.launch()
+ # Set an initial value for the clock
+ self.vm.qtest("clock_step %d" % nsec_per_sec)
+
+ def tearDown(self):
+ self.vm.shutdown()
+ os.remove(blkdebug_file)
+
+ def accounted_ops(self, read = False, write = False, flush = False):
+ ops = 0
+ if write:
+ ops += self.total_wr_ops
+ if self.account_failed:
+ ops += self.failed_wr_ops
+ if self.account_invalid:
+ ops += self.invalid_wr_ops
+ if read:
+ ops += self.total_rd_ops
+ if self.account_failed:
+ ops += self.failed_rd_ops
+ if self.account_invalid:
+ ops += self.invalid_rd_ops
+ if flush:
+ ops += self.total_flush_ops
+ return ops
+
+ def accounted_latency(self, read = False, write = False, flush = False):
+ latency = 0
+ if write:
+ latency += self.total_wr_ops * op_latency
+ if self.account_failed:
+ latency += self.failed_wr_ops * op_latency
+ if read:
+ latency += self.total_rd_ops * op_latency
+ if self.account_failed:
+ latency += self.failed_rd_ops * op_latency
+ if flush:
+ latency += self.total_flush_ops * op_latency
+ return latency
+
+ def check_values(self):
+ stats = self.blockstats('drive0')
+
+ # Check that the totals match with what we have calculated
+ self.assertEqual(self.total_rd_bytes, stats['rd_bytes'])
+ self.assertEqual(self.total_wr_bytes, stats['wr_bytes'])
+ self.assertEqual(self.total_rd_ops, stats['rd_operations'])
+ self.assertEqual(self.total_wr_ops, stats['wr_operations'])
+ self.assertEqual(self.total_flush_ops, stats['flush_operations'])
+ self.assertEqual(self.wr_highest_offset, stats['wr_highest_offset'])
+ self.assertEqual(self.failed_rd_ops, stats['failed_rd_operations'])
+ self.assertEqual(self.failed_wr_ops, stats['failed_wr_operations'])
+ self.assertEqual(self.invalid_rd_ops, stats['invalid_rd_operations'])
+ self.assertEqual(self.invalid_wr_ops, stats['invalid_wr_operations'])
+ self.assertEqual(self.account_invalid, stats['account_invalid'])
+ self.assertEqual(self.account_failed, stats['account_failed'])
+ self.assertEqual(self.total_wr_merged, stats['wr_merged'])
+
+ # Check that there's exactly one interval with the length we defined
+ self.assertEqual(1, len(stats['timed_stats']))
+ timed_stats = stats['timed_stats'][0]
+ self.assertEqual(interval_length, timed_stats['interval_length'])
+
+ total_rd_latency = self.accounted_latency(read = True)
+ if (total_rd_latency != 0):
+ self.assertEqual(total_rd_latency, stats['rd_total_time_ns'])
+ self.assertEqual(op_latency, timed_stats['min_rd_latency_ns'])
+ self.assertEqual(op_latency, timed_stats['max_rd_latency_ns'])
+ self.assertEqual(op_latency, timed_stats['avg_rd_latency_ns'])
+ self.assertLess(0, timed_stats['avg_rd_queue_depth'])
+ else:
+ self.assertEqual(0, stats['rd_total_time_ns'])
+ self.assertEqual(0, timed_stats['min_rd_latency_ns'])
+ self.assertEqual(0, timed_stats['max_rd_latency_ns'])
+ self.assertEqual(0, timed_stats['avg_rd_latency_ns'])
+ self.assertEqual(0, timed_stats['avg_rd_queue_depth'])
+
+ # min read latency <= avg read latency <= max read latency
+ self.assertLessEqual(timed_stats['min_rd_latency_ns'],
+ timed_stats['avg_rd_latency_ns'])
+ self.assertLessEqual(timed_stats['avg_rd_latency_ns'],
+ timed_stats['max_rd_latency_ns'])
+
+ total_wr_latency = self.accounted_latency(write = True)
+ if (total_wr_latency != 0):
+ self.assertEqual(total_wr_latency, stats['wr_total_time_ns'])
+ self.assertEqual(op_latency, timed_stats['min_wr_latency_ns'])
+ self.assertEqual(op_latency, timed_stats['max_wr_latency_ns'])
+ self.assertEqual(op_latency, timed_stats['avg_wr_latency_ns'])
+ self.assertLess(0, timed_stats['avg_wr_queue_depth'])
+ else:
+ self.assertEqual(0, stats['wr_total_time_ns'])
+ self.assertEqual(0, timed_stats['min_wr_latency_ns'])
+ self.assertEqual(0, timed_stats['max_wr_latency_ns'])
+ self.assertEqual(0, timed_stats['avg_wr_latency_ns'])
+ self.assertEqual(0, timed_stats['avg_wr_queue_depth'])
+
+ # min write latency <= avg write latency <= max write latency
+ self.assertLessEqual(timed_stats['min_wr_latency_ns'],
+ timed_stats['avg_wr_latency_ns'])
+ self.assertLessEqual(timed_stats['avg_wr_latency_ns'],
+ timed_stats['max_wr_latency_ns'])
+
+ total_flush_latency = self.accounted_latency(flush = True)
+ if (total_flush_latency != 0):
+ self.assertEqual(total_flush_latency, stats['flush_total_time_ns'])
+ self.assertEqual(op_latency, timed_stats['min_flush_latency_ns'])
+ self.assertEqual(op_latency, timed_stats['max_flush_latency_ns'])
+ self.assertEqual(op_latency, timed_stats['avg_flush_latency_ns'])
+ else:
+ self.assertEqual(0, stats['flush_total_time_ns'])
+ self.assertEqual(0, timed_stats['min_flush_latency_ns'])
+ self.assertEqual(0, timed_stats['max_flush_latency_ns'])
+ self.assertEqual(0, timed_stats['avg_flush_latency_ns'])
+
+ # min flush latency <= avg flush latency <= max flush latency
+ self.assertLessEqual(timed_stats['min_flush_latency_ns'],
+ timed_stats['avg_flush_latency_ns'])
+ self.assertLessEqual(timed_stats['avg_flush_latency_ns'],
+ timed_stats['max_flush_latency_ns'])
+
+ # idle_time_ns must be > 0 if we have performed any operation
+ if (self.accounted_ops(read = True, write = True, flush = True) != 0):
+ self.assertLess(0, stats['idle_time_ns'])
+ else:
+ self.assertFalse(stats.has_key('idle_time_ns'))
+
+ # This test does not alter these, so they must be all 0
+ self.assertEqual(0, stats['rd_merged'])
+ self.assertEqual(0, stats['failed_flush_operations'])
+ self.assertEqual(0, stats['invalid_flush_operations'])
+
+ def do_test_stats(self, rd_size = 0, rd_ops = 0, wr_size = 0, wr_ops = 0,
+ flush_ops = 0, invalid_rd_ops = 0, invalid_wr_ops = 0,
+ failed_rd_ops = 0, failed_wr_ops = 0, wr_merged = 0):
+ # The 'ops' list will contain all the requested I/O operations
+ ops = []
+ for i in range(rd_ops):
+ ops.append("aio_read %d %d" % (i * rd_size, rd_size))
+
+ for i in range(wr_ops):
+ ops.append("aio_write %d %d" % (i * wr_size, wr_size))
+
+ for i in range(flush_ops):
+ ops.append("aio_flush")
+
+ highest_offset = wr_ops * wr_size
+
+ # Two types of invalid operations: unaligned length and unaligned offset
+ for i in range(invalid_rd_ops / 2):
+ ops.append("aio_read 0 511")
+
+ for i in range(invalid_rd_ops / 2, invalid_rd_ops):
+ ops.append("aio_read 13 512")
+
+ for i in range(invalid_wr_ops / 2):
+ ops.append("aio_write 0 511")
+
+ for i in range(invalid_wr_ops / 2, invalid_wr_ops):
+ ops.append("aio_write 13 512")
+
+ for i in range(failed_rd_ops):
+ ops.append("aio_read %d 512" % bad_offset)
+
+ for i in range(failed_wr_ops):
+ ops.append("aio_write %d 512" % bad_offset)
+
+ if failed_wr_ops > 0:
+ highest_offset = max(highest_offset, bad_offset + 512)
+
+ for i in range(wr_merged):
+ first = i * wr_size * 2
+ second = first + wr_size
+ ops.append("multiwrite %d %d ; %d %d" %
+ (first, wr_size, second, wr_size))
+
+ highest_offset = max(highest_offset, wr_merged * wr_size * 2)
+
+ # Now perform all operations
+ for op in ops:
+ self.vm.hmp_qemu_io("drive0", op)
+
+ # Update the expected totals
+ self.total_rd_bytes += rd_ops * rd_size
+ self.total_rd_ops += rd_ops
+ self.total_wr_bytes += wr_ops * wr_size
+ self.total_wr_ops += wr_ops
+ self.total_wr_merged += wr_merged
+ self.total_flush_ops += flush_ops
+ self.invalid_rd_ops += invalid_rd_ops
+ self.invalid_wr_ops += invalid_wr_ops
+ self.failed_rd_ops += failed_rd_ops
+ self.failed_wr_ops += failed_wr_ops
+
+ self.wr_highest_offset = max(self.wr_highest_offset, highest_offset)
+
+ # Advance the clock so idle_time_ns has a meaningful value
+ self.vm.qtest("clock_step %d" % nsec_per_sec)
+
+ # And check that the actual statistics match the expected ones
+ self.check_values()
+
+ def test_read_only(self):
+ test_values = [[512, 1],
+ [65536, 1],
+ [512, 12],
+ [65536, 12]]
+ for i in test_values:
+ self.do_test_stats(rd_size = i[0], rd_ops = i[1])
+
+ def test_write_only(self):
+ test_values = [[512, 1],
+ [65536, 1],
+ [512, 12],
+ [65536, 12]]
+ for i in test_values:
+ self.do_test_stats(wr_size = i[0], wr_ops = i[1])
+
+ def test_invalid(self):
+ self.do_test_stats(invalid_rd_ops = 7)
+ self.do_test_stats(invalid_wr_ops = 3)
+ self.do_test_stats(invalid_rd_ops = 4, invalid_wr_ops = 5)
+
+ def test_failed(self):
+ self.do_test_stats(failed_rd_ops = 8)
+ self.do_test_stats(failed_wr_ops = 6)
+ self.do_test_stats(failed_rd_ops = 5, failed_wr_ops = 12)
+
+ def test_flush(self):
+ self.do_test_stats(flush_ops = 8)
+
+ def test_merged(self):
+ for i in range(5):
+ self.do_test_stats(wr_merged = i * 3)
+
+ def test_all(self):
+ # rd_size, rd_ops, wr_size, wr_ops, flush_ops
+ # invalid_rd_ops, invalid_wr_ops,
+ # failed_rd_ops, failed_wr_ops
+ # wr_merged
+ test_values = [[512, 1, 512, 1, 1, 4, 7, 5, 2, 1],
+ [65536, 1, 2048, 12, 7, 7, 5, 2, 5, 5],
+ [32768, 9, 8192, 1, 4, 3, 2, 4, 6, 4],
+ [16384, 11, 3584, 16, 9, 8, 6, 7, 3, 4]]
+ for i in test_values:
+ self.do_test_stats(*i)
+
+ def test_no_op(self):
+ # All values must be sane before doing any I/O
+ self.check_values()
+
+
+class BlockDeviceStatsTestAccountInvalid(BlockDeviceStatsTestCase):
+ account_invalid = True
+ account_failed = False
+
+class BlockDeviceStatsTestAccountFailed(BlockDeviceStatsTestCase):
+ account_invalid = False
+ account_failed = True
+
+class BlockDeviceStatsTestAccountBoth(BlockDeviceStatsTestCase):
+ account_invalid = True
+ account_failed = True
+
+class BlockDeviceStatsTestCoroutine(BlockDeviceStatsTestCase):
+ test_img = "null-co://"
+
+if __name__ == '__main__':
+ iotests.main(supported_fmts=["raw"])
diff --git a/tests/qemu-iotests/136.out b/tests/qemu-iotests/136.out
new file mode 100644
index 000000000..0a5e9583a
--- /dev/null
+++ b/tests/qemu-iotests/136.out
@@ -0,0 +1,5 @@
+........................................
+----------------------------------------------------------------------
+Ran 40 tests
+
+OK
diff --git a/tests/qemu-iotests/137 b/tests/qemu-iotests/137
new file mode 100755
index 000000000..9a6597cf9
--- /dev/null
+++ b/tests/qemu-iotests/137
@@ -0,0 +1,145 @@
+#!/bin/bash
+#
+# Test qcow2 reopen
+#
+# Copyright (C) 2015 Red Hat, Inc.
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+#
+
+# creator
+owner=kwolf@redhat.com
+
+seq="$(basename $0)"
+echo "QA output created by $seq"
+
+here="$PWD"
+tmp=/tmp/$$
+status=1 # failure is the default!
+
+_cleanup()
+{
+ _cleanup_test_img
+}
+trap "_cleanup; exit \$status" 0 1 2 3 15
+
+# get standard environment, filters and checks
+. ./common.rc
+. ./common.filter
+. ./common.qemu
+
+_supported_fmt qcow2
+_supported_proto generic
+_supported_os Linux
+
+
+_make_test_img 64M
+
+echo === Try setting valid values for all options ===
+echo
+
+# Try all options and then check that all of the basic I/O operations still
+# work on this image.
+$QEMU_IO \
+ -c "reopen -o lazy-refcounts=on,pass-discard-request=on" \
+ -c "reopen -o lazy-refcounts=off,pass-discard-request=off" \
+ -c "reopen -o pass-discard-snapshot=on,pass-discard-other=on" \
+ -c "reopen -o pass-discard-snapshot=off,pass-discard-other=off" \
+ -c "reopen -o overlap-check=all" \
+ -c "reopen -o overlap-check=none" \
+ -c "reopen -o overlap-check=cached" \
+ -c "reopen -o overlap-check=constant" \
+ -c "reopen -o overlap-check.template=all" \
+ -c "reopen -o overlap-check.template=none" \
+ -c "reopen -o overlap-check.template=cached" \
+ -c "reopen -o overlap-check.template=constant" \
+ -c "reopen -o overlap-check.main-header=on" \
+ -c "reopen -o overlap-check.main-header=off" \
+ -c "reopen -o overlap-check.active-l1=on" \
+ -c "reopen -o overlap-check.active-l1=off" \
+ -c "reopen -o overlap-check.active-l2=on" \
+ -c "reopen -o overlap-check.active-l2=off" \
+ -c "reopen -o overlap-check.refcount-table=on" \
+ -c "reopen -o overlap-check.refcount-table=off" \
+ -c "reopen -o overlap-check.refcount-block=on" \
+ -c "reopen -o overlap-check.refcount-block=off" \
+ -c "reopen -o overlap-check.snapshot-table=on" \
+ -c "reopen -o overlap-check.snapshot-table=off" \
+ -c "reopen -o overlap-check.inactive-l1=on" \
+ -c "reopen -o overlap-check.inactive-l1=off" \
+ -c "reopen -o overlap-check.inactive-l2=on" \
+ -c "reopen -o overlap-check.inactive-l2=off" \
+ -c "reopen -o cache-size=1M" \
+ -c "reopen -o l2-cache-size=512k" \
+ -c "reopen -o refcount-cache-size=128k" \
+ -c "reopen -o cache-clean-interval=5" \
+ -c "reopen -o cache-clean-interval=0" \
+ -c "reopen -o cache-clean-interval=10" \
+ \
+ -c "write -P 55 0 32M" \
+ -c "read -P 55 0 32M" \
+ -c "discard 0 32M" \
+ -c "write -z 0 32M" \
+ -c "read -P 0 0 32M" \
+ \
+ "$TEST_IMG" | _filter_qemu_io
+
+
+echo
+echo === Try setting some invalid values ===
+echo
+
+$QEMU_IO \
+ -c "reopen -o lazy-refcounts=42" \
+ -c "reopen -o cache-size=1M,l2-cache-size=64k,refcount-cache-size=64k" \
+ -c "reopen -o cache-size=1M,l2-cache-size=2M" \
+ -c "reopen -o cache-size=1M,refcount-cache-size=2M" \
+ -c "reopen -o l2-cache-size=256T" \
+ -c "reopen -o refcount-cache-size=256T" \
+ -c "reopen -o overlap-check=constant,overlap-check.template=all" \
+ -c "reopen -o overlap-check=blubb" \
+ -c "reopen -o overlap-check.template=blubb" \
+ -c "reopen -o cache-clean-interval=-1" \
+ "$TEST_IMG" | _filter_qemu_io
+
+echo
+echo === Test transaction semantics ===
+echo
+
+# Whether lazy-refcounts was actually enabled can easily be tested: Check if
+# the dirty bit is set after a crash
+$QEMU_IO \
+ -c "reopen -o lazy-refcounts=on,overlap-check=blubb" \
+ -c "write -P 0x5a 0 512" \
+ -c "sigraise $(kill -l KILL)" \
+ "$TEST_IMG" 2>&1 | _filter_qemu_io
+
+# The dirty bit must not be set
+$PYTHON qcow2.py "$TEST_IMG" dump-header | grep incompatible_features
+
+# Similarly we can test whether corruption detection has been enabled:
+# Create L1/L2, overwrite first entry in refcount block, allocate something.
+# Disabling the checks should fail, so the corruption must be detected.
+_make_test_img 64M
+$QEMU_IO -c "write 0 64k" "$TEST_IMG" | _filter_qemu_io
+poke_file "$TEST_IMG" "$((0x20000))" "\x00\x00"
+$QEMU_IO \
+ -c "reopen -o overlap-check=none,lazy-refcounts=42" \
+ -c "write 64k 64k" \
+ "$TEST_IMG" 2>&1 | _filter_qemu_io
+
+# success, all done
+echo '*** done'
+rm -f $seq.full
+status=0
diff --git a/tests/qemu-iotests/137.out b/tests/qemu-iotests/137.out
new file mode 100644
index 000000000..88c702cf7
--- /dev/null
+++ b/tests/qemu-iotests/137.out
@@ -0,0 +1,46 @@
+QA output created by 137
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864
+=== Try setting valid values for all options ===
+
+wrote 33554432/33554432 bytes at offset 0
+32 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
+read 33554432/33554432 bytes at offset 0
+32 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
+discard 33554432/33554432 bytes at offset 0
+32 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
+wrote 33554432/33554432 bytes at offset 0
+32 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
+read 33554432/33554432 bytes at offset 0
+32 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
+
+=== Try setting some invalid values ===
+
+Parameter 'lazy-refcounts' expects 'on' or 'off'
+cache-size, l2-cache-size and refcount-cache-size may not be set the same time
+l2-cache-size may not exceed cache-size
+refcount-cache-size may not exceed cache-size
+L2 cache size too big
+L2 cache size too big
+Conflicting values for qcow2 options 'overlap-check' ('constant') and 'overlap-check.template' ('all')
+Unsupported value 'blubb' for qcow2 option 'overlap-check'. Allowed are any of the following: none, constant, cached, all
+Unsupported value 'blubb' for qcow2 option 'overlap-check'. Allowed are any of the following: none, constant, cached, all
+Cache clean interval too big
+
+=== Test transaction semantics ===
+
+Unsupported value 'blubb' for qcow2 option 'overlap-check'. Allowed are any of the following: none, constant, cached, all
+wrote 512/512 bytes at offset 0
+512 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
+./common.config: Killed ( if [ "${VALGRIND_QEMU}" == "y" ]; then
+ exec valgrind --log-file="${VALGRIND_LOGFILE}" --error-exitcode=99 "$QEMU_IO_PROG" $QEMU_IO_OPTIONS "$@";
+else
+ exec "$QEMU_IO_PROG" $QEMU_IO_OPTIONS "$@";
+fi )
+incompatible_features 0x0
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864
+wrote 65536/65536 bytes at offset 0
+64 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
+Parameter 'lazy-refcounts' expects 'on' or 'off'
+qcow2: Marking image as corrupt: Preventing invalid write on metadata (overlaps with qcow2_header); further corruption events will be suppressed
+write failed: Input/output error
+*** done
diff --git a/tests/qemu-iotests/138 b/tests/qemu-iotests/138
new file mode 100755
index 000000000..a5c3464d5
--- /dev/null
+++ b/tests/qemu-iotests/138
@@ -0,0 +1,73 @@
+#!/bin/bash
+#
+# General test case for qcow2's image check
+#
+# Copyright (C) 2015 Red Hat, Inc.
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+#
+
+# creator
+owner=mreitz@redhat.com
+
+seq="$(basename $0)"
+echo "QA output created by $seq"
+
+here="$PWD"
+tmp=/tmp/$$
+status=1 # failure is the default!
+
+_cleanup()
+{
+ _cleanup_test_img
+}
+trap "_cleanup; exit \$status" 0 1 2 3 15
+
+# get standard environment, filters and checks
+. ./common.rc
+. ./common.filter
+
+# This tests qocw2-specific low-level functionality
+_supported_fmt qcow2
+_supported_proto file
+_supported_os Linux
+
+echo
+echo '=== Check on an image with a multiple of 2^32 clusters ==='
+echo
+
+IMGOPTS=$(_optstr_add "$IMGOPTS" "cluster_size=512") \
+ _make_test_img 512
+
+# Allocate L2 table
+$QEMU_IO -c 'write 0 512' "$TEST_IMG" | _filter_qemu_io
+
+# Put the data cluster at a multiple of 2 TB, resulting in the image apparently
+# having a multiple of 2^32 clusters
+# (To be more specific: It is at 32 PB)
+poke_file "$TEST_IMG" 2048 "\x80\x80\x00\x00\x00\x00\x00\x00"
+
+# An offset of 32 PB results in qemu-img check having to allocate an in-memory
+# refcount table of 128 TB (16 bit refcounts, 512 byte clusters).
+# This should be generally too much for any system and thus fail.
+# What this test is checking is that the qcow2 driver actually tries to allocate
+# such a large amount of memory (and is consequently aborting) instead of having
+# truncated the cluster count somewhere (which would result in much less memory
+# being allocated and then a segfault occurring).
+_check_test_img
+
+# success, all done
+echo "*** done"
+rm -f $seq.full
+status=0
diff --git a/tests/qemu-iotests/138.out b/tests/qemu-iotests/138.out
new file mode 100644
index 000000000..3fe911f85
--- /dev/null
+++ b/tests/qemu-iotests/138.out
@@ -0,0 +1,9 @@
+QA output created by 138
+
+=== Check on an image with a multiple of 2^32 clusters ===
+
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=512
+wrote 512/512 bytes at offset 0
+512 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
+qemu-img: Check failed: Cannot allocate memory
+*** done
diff --git a/tests/qemu-iotests/139 b/tests/qemu-iotests/139
new file mode 100644
index 000000000..a4b969499
--- /dev/null
+++ b/tests/qemu-iotests/139
@@ -0,0 +1,416 @@
+#!/usr/bin/env python
+#
+# Test cases for the QMP 'x-blockdev-del' command
+#
+# Copyright (C) 2015 Igalia, S.L.
+# Author: Alberto Garcia <berto@igalia.com>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+#
+
+import os
+import iotests
+import time
+
+base_img = os.path.join(iotests.test_dir, 'base.img')
+new_img = os.path.join(iotests.test_dir, 'new.img')
+
+class TestBlockdevDel(iotests.QMPTestCase):
+
+ def setUp(self):
+ iotests.qemu_img('create', '-f', iotests.imgfmt, base_img, '1M')
+ self.vm = iotests.VM()
+ self.vm.launch()
+
+ def tearDown(self):
+ self.vm.shutdown()
+ os.remove(base_img)
+ if os.path.isfile(new_img):
+ os.remove(new_img)
+
+ # Check whether a BlockBackend exists
+ def checkBlockBackend(self, backend, node, must_exist = True):
+ result = self.vm.qmp('query-block')
+ backends = filter(lambda x: x['device'] == backend, result['return'])
+ self.assertLessEqual(len(backends), 1)
+ self.assertEqual(must_exist, len(backends) == 1)
+ if must_exist:
+ if node:
+ self.assertEqual(backends[0]['inserted']['node-name'], node)
+ else:
+ self.assertFalse(backends[0].has_key('inserted'))
+
+ # Check whether a BlockDriverState exists
+ def checkBlockDriverState(self, node, must_exist = True):
+ result = self.vm.qmp('query-named-block-nodes')
+ nodes = filter(lambda x: x['node-name'] == node, result['return'])
+ self.assertLessEqual(len(nodes), 1)
+ self.assertEqual(must_exist, len(nodes) == 1)
+
+ # Add a new BlockBackend (with its attached BlockDriverState)
+ def addBlockBackend(self, backend, node):
+ file_node = '%s_file' % node
+ self.checkBlockBackend(backend, node, False)
+ self.checkBlockDriverState(node, False)
+ self.checkBlockDriverState(file_node, False)
+ opts = {'driver': iotests.imgfmt,
+ 'id': backend,
+ 'node-name': node,
+ 'file': {'driver': 'file',
+ 'node-name': file_node,
+ 'filename': base_img}}
+ result = self.vm.qmp('blockdev-add', conv_keys = False, options = opts)
+ self.assert_qmp(result, 'return', {})
+ self.checkBlockBackend(backend, node)
+ self.checkBlockDriverState(node)
+ self.checkBlockDriverState(file_node)
+
+ # Add a BlockDriverState without a BlockBackend
+ def addBlockDriverState(self, node):
+ file_node = '%s_file' % node
+ self.checkBlockDriverState(node, False)
+ self.checkBlockDriverState(file_node, False)
+ opts = {'driver': iotests.imgfmt,
+ 'node-name': node,
+ 'file': {'driver': 'file',
+ 'node-name': file_node,
+ 'filename': base_img}}
+ result = self.vm.qmp('blockdev-add', conv_keys = False, options = opts)
+ self.assert_qmp(result, 'return', {})
+ self.checkBlockDriverState(node)
+ self.checkBlockDriverState(file_node)
+
+ # Add a BlockDriverState that will be used as overlay for the base_img BDS
+ def addBlockDriverStateOverlay(self, node):
+ self.checkBlockDriverState(node, False)
+ iotests.qemu_img('create', '-f', iotests.imgfmt,
+ '-b', base_img, new_img, '1M')
+ opts = {'driver': iotests.imgfmt,
+ 'node-name': node,
+ 'backing': '',
+ 'file': {'driver': 'file',
+ 'filename': new_img}}
+ result = self.vm.qmp('blockdev-add', conv_keys = False, options = opts)
+ self.assert_qmp(result, 'return', {})
+ self.checkBlockDriverState(node)
+
+ # Delete a BlockBackend
+ def delBlockBackend(self, backend, node, expect_error = False,
+ destroys_media = True):
+ self.checkBlockBackend(backend, node)
+ if node:
+ self.checkBlockDriverState(node)
+ result = self.vm.qmp('x-blockdev-del', id = backend)
+ if expect_error:
+ self.assert_qmp(result, 'error/class', 'GenericError')
+ if node:
+ self.checkBlockDriverState(node)
+ else:
+ self.assert_qmp(result, 'return', {})
+ if node:
+ self.checkBlockDriverState(node, not destroys_media)
+ self.checkBlockBackend(backend, node, must_exist = expect_error)
+
+ # Delete a BlockDriverState
+ def delBlockDriverState(self, node, expect_error = False):
+ self.checkBlockDriverState(node)
+ result = self.vm.qmp('x-blockdev-del', node_name = node)
+ if expect_error:
+ self.assert_qmp(result, 'error/class', 'GenericError')
+ else:
+ self.assert_qmp(result, 'return', {})
+ self.checkBlockDriverState(node, expect_error)
+
+ # Add a device model
+ def addDeviceModel(self, device, backend):
+ result = self.vm.qmp('device_add', id = device,
+ driver = 'virtio-blk-pci', drive = backend)
+ self.assert_qmp(result, 'return', {})
+
+ # Delete a device model
+ def delDeviceModel(self, device):
+ result = self.vm.qmp('device_del', id = device)
+ self.assert_qmp(result, 'return', {})
+
+ result = self.vm.qmp('system_reset')
+ self.assert_qmp(result, 'return', {})
+
+ device_path = '/machine/peripheral/%s/virtio-backend' % device
+ event = self.vm.event_wait(name="DEVICE_DELETED",
+ match={'data': {'path': device_path}})
+ self.assertNotEqual(event, None)
+
+ event = self.vm.event_wait(name="DEVICE_DELETED",
+ match={'data': {'device': device}})
+ self.assertNotEqual(event, None)
+
+ # Remove a BlockDriverState
+ def ejectDrive(self, backend, node, expect_error = False,
+ destroys_media = True):
+ self.checkBlockBackend(backend, node)
+ self.checkBlockDriverState(node)
+ result = self.vm.qmp('eject', device = backend)
+ if expect_error:
+ self.assert_qmp(result, 'error/class', 'GenericError')
+ self.checkBlockDriverState(node)
+ self.checkBlockBackend(backend, node)
+ else:
+ self.assert_qmp(result, 'return', {})
+ self.checkBlockDriverState(node, not destroys_media)
+ self.checkBlockBackend(backend, None)
+
+ # Insert a BlockDriverState
+ def insertDrive(self, backend, node):
+ self.checkBlockBackend(backend, None)
+ self.checkBlockDriverState(node)
+ result = self.vm.qmp('x-blockdev-insert-medium',
+ device = backend, node_name = node)
+ self.assert_qmp(result, 'return', {})
+ self.checkBlockBackend(backend, node)
+ self.checkBlockDriverState(node)
+
+ # Create a snapshot using 'blockdev-snapshot-sync'
+ def createSnapshotSync(self, node, overlay):
+ self.checkBlockDriverState(node)
+ self.checkBlockDriverState(overlay, False)
+ opts = {'node-name': node,
+ 'snapshot-file': new_img,
+ 'snapshot-node-name': overlay,
+ 'format': iotests.imgfmt}
+ result = self.vm.qmp('blockdev-snapshot-sync', conv_keys=False, **opts)
+ self.assert_qmp(result, 'return', {})
+ self.checkBlockDriverState(node)
+ self.checkBlockDriverState(overlay)
+
+ # Create a snapshot using 'blockdev-snapshot'
+ def createSnapshot(self, node, overlay):
+ self.checkBlockDriverState(node)
+ self.checkBlockDriverState(overlay)
+ result = self.vm.qmp('blockdev-snapshot',
+ node = node, overlay = overlay)
+ self.assert_qmp(result, 'return', {})
+ self.checkBlockDriverState(node)
+ self.checkBlockDriverState(overlay)
+
+ # Create a mirror
+ def createMirror(self, backend, node, new_node):
+ self.checkBlockBackend(backend, node)
+ self.checkBlockDriverState(new_node, False)
+ opts = {'device': backend,
+ 'target': new_img,
+ 'node-name': new_node,
+ 'sync': 'top',
+ 'format': iotests.imgfmt}
+ result = self.vm.qmp('drive-mirror', conv_keys=False, **opts)
+ self.assert_qmp(result, 'return', {})
+ self.checkBlockBackend(backend, node)
+ self.checkBlockDriverState(new_node)
+
+ # Complete an existing block job
+ def completeBlockJob(self, backend, node_before, node_after):
+ self.checkBlockBackend(backend, node_before)
+ result = self.vm.qmp('block-job-complete', device=backend)
+ self.assert_qmp(result, 'return', {})
+ self.wait_until_completed(backend)
+ self.checkBlockBackend(backend, node_after)
+
+ # Add a BlkDebug node
+ # Note that the purpose of this is to test the x-blockdev-del
+ # sanity checks, not to create a usable blkdebug drive
+ def addBlkDebug(self, debug, node):
+ self.checkBlockDriverState(node, False)
+ self.checkBlockDriverState(debug, False)
+ image = {'driver': iotests.imgfmt,
+ 'node-name': node,
+ 'file': {'driver': 'file',
+ 'filename': base_img}}
+ opts = {'driver': 'blkdebug',
+ 'node-name': debug,
+ 'image': image}
+ result = self.vm.qmp('blockdev-add', conv_keys = False, options = opts)
+ self.assert_qmp(result, 'return', {})
+ self.checkBlockDriverState(node)
+ self.checkBlockDriverState(debug)
+
+ # Add a BlkVerify node
+ # Note that the purpose of this is to test the x-blockdev-del
+ # sanity checks, not to create a usable blkverify drive
+ def addBlkVerify(self, blkverify, test, raw):
+ self.checkBlockDriverState(test, False)
+ self.checkBlockDriverState(raw, False)
+ self.checkBlockDriverState(blkverify, False)
+ iotests.qemu_img('create', '-f', iotests.imgfmt, new_img, '1M')
+ node_0 = {'driver': iotests.imgfmt,
+ 'node-name': test,
+ 'file': {'driver': 'file',
+ 'filename': base_img}}
+ node_1 = {'driver': iotests.imgfmt,
+ 'node-name': raw,
+ 'file': {'driver': 'file',
+ 'filename': new_img}}
+ opts = {'driver': 'blkverify',
+ 'node-name': blkverify,
+ 'test': node_0,
+ 'raw': node_1}
+ result = self.vm.qmp('blockdev-add', conv_keys = False, options = opts)
+ self.assert_qmp(result, 'return', {})
+ self.checkBlockDriverState(test)
+ self.checkBlockDriverState(raw)
+ self.checkBlockDriverState(blkverify)
+
+ # Add a Quorum node
+ def addQuorum(self, quorum, child0, child1):
+ self.checkBlockDriverState(child0, False)
+ self.checkBlockDriverState(child1, False)
+ self.checkBlockDriverState(quorum, False)
+ iotests.qemu_img('create', '-f', iotests.imgfmt, new_img, '1M')
+ child_0 = {'driver': iotests.imgfmt,
+ 'node-name': child0,
+ 'file': {'driver': 'file',
+ 'filename': base_img}}
+ child_1 = {'driver': iotests.imgfmt,
+ 'node-name': child1,
+ 'file': {'driver': 'file',
+ 'filename': new_img}}
+ opts = {'driver': 'quorum',
+ 'node-name': quorum,
+ 'vote-threshold': 1,
+ 'children': [ child_0, child_1 ]}
+ result = self.vm.qmp('blockdev-add', conv_keys = False, options = opts)
+ self.assert_qmp(result, 'return', {})
+ self.checkBlockDriverState(child0)
+ self.checkBlockDriverState(child1)
+ self.checkBlockDriverState(quorum)
+
+ ########################
+ # The tests start here #
+ ########################
+
+ def testWrongParameters(self):
+ self.addBlockBackend('drive0', 'node0')
+ result = self.vm.qmp('x-blockdev-del')
+ self.assert_qmp(result, 'error/class', 'GenericError')
+ result = self.vm.qmp('x-blockdev-del', id='drive0', node_name='node0')
+ self.assert_qmp(result, 'error/class', 'GenericError')
+ self.delBlockBackend('drive0', 'node0')
+
+ def testBlockBackend(self):
+ self.addBlockBackend('drive0', 'node0')
+ # You cannot delete a BDS that is attached to a backend
+ self.delBlockDriverState('node0', expect_error = True)
+ self.delBlockBackend('drive0', 'node0')
+
+ def testBlockDriverState(self):
+ self.addBlockDriverState('node0')
+ # You cannot delete a file BDS directly
+ self.delBlockDriverState('node0_file', expect_error = True)
+ self.delBlockDriverState('node0')
+
+ def testEject(self):
+ self.addBlockBackend('drive0', 'node0')
+ self.ejectDrive('drive0', 'node0')
+ self.delBlockBackend('drive0', None)
+
+ def testDeviceModel(self):
+ self.addBlockBackend('drive0', 'node0')
+ self.addDeviceModel('device0', 'drive0')
+ self.ejectDrive('drive0', 'node0', expect_error = True)
+ self.delBlockBackend('drive0', 'node0', expect_error = True)
+ self.delDeviceModel('device0')
+ self.delBlockBackend('drive0', 'node0')
+
+ def testAttachMedia(self):
+ # This creates a BlockBackend and removes its media
+ self.addBlockBackend('drive0', 'node0')
+ self.ejectDrive('drive0', 'node0')
+ # This creates a new BlockDriverState and inserts it into the backend
+ self.addBlockDriverState('node1')
+ self.insertDrive('drive0', 'node1')
+ # The backend can't be removed: the new BDS has an extra reference
+ self.delBlockBackend('drive0', 'node1', expect_error = True)
+ self.delBlockDriverState('node1', expect_error = True)
+ # The BDS still exists after being ejected, but now it can be removed
+ self.ejectDrive('drive0', 'node1', destroys_media = False)
+ self.delBlockDriverState('node1')
+ self.delBlockBackend('drive0', None)
+
+ def testSnapshotSync(self):
+ self.addBlockBackend('drive0', 'node0')
+ self.createSnapshotSync('node0', 'overlay0')
+ # This fails because node0 is now being used as a backing image
+ self.delBlockDriverState('node0', expect_error = True)
+ # This succeeds because overlay0 only has the backend reference
+ self.delBlockBackend('drive0', 'overlay0')
+ self.checkBlockDriverState('node0', False)
+
+ def testSnapshot(self):
+ self.addBlockBackend('drive0', 'node0')
+ self.addBlockDriverStateOverlay('overlay0')
+ self.createSnapshot('node0', 'overlay0')
+ self.delBlockBackend('drive0', 'overlay0', expect_error = True)
+ self.delBlockDriverState('node0', expect_error = True)
+ self.delBlockDriverState('overlay0', expect_error = True)
+ self.ejectDrive('drive0', 'overlay0', destroys_media = False)
+ self.delBlockBackend('drive0', None)
+ self.delBlockDriverState('node0', expect_error = True)
+ self.delBlockDriverState('overlay0')
+ self.checkBlockDriverState('node0', False)
+
+ def testMirror(self):
+ self.addBlockBackend('drive0', 'node0')
+ self.createMirror('drive0', 'node0', 'mirror0')
+ # The block job prevents removing the device
+ self.delBlockBackend('drive0', 'node0', expect_error = True)
+ self.delBlockDriverState('node0', expect_error = True)
+ self.delBlockDriverState('mirror0', expect_error = True)
+ self.wait_ready('drive0')
+ self.completeBlockJob('drive0', 'node0', 'mirror0')
+ self.assert_no_active_block_jobs()
+ self.checkBlockDriverState('node0', False)
+ # This succeeds because the backend now points to mirror0
+ self.delBlockBackend('drive0', 'mirror0')
+
+ def testBlkDebug(self):
+ self.addBlkDebug('debug0', 'node0')
+ # 'node0' is used by the blkdebug node
+ self.delBlockDriverState('node0', expect_error = True)
+ # But we can remove the blkdebug node directly
+ self.delBlockDriverState('debug0')
+ self.checkBlockDriverState('node0', False)
+
+ def testBlkVerify(self):
+ self.addBlkVerify('verify0', 'node0', 'node1')
+ # We cannot remove the children of a blkverify device
+ self.delBlockDriverState('node0', expect_error = True)
+ self.delBlockDriverState('node1', expect_error = True)
+ # But we can remove the blkverify node directly
+ self.delBlockDriverState('verify0')
+ self.checkBlockDriverState('node0', False)
+ self.checkBlockDriverState('node1', False)
+
+ def testQuorum(self):
+ if not 'quorum' in iotests.qemu_img_pipe('--help'):
+ return
+ self.addQuorum('quorum0', 'node0', 'node1')
+ # We cannot remove the children of a Quorum device
+ self.delBlockDriverState('node0', expect_error = True)
+ self.delBlockDriverState('node1', expect_error = True)
+ # But we can remove the Quorum node directly
+ self.delBlockDriverState('quorum0')
+ self.checkBlockDriverState('node0', False)
+ self.checkBlockDriverState('node1', False)
+
+
+if __name__ == '__main__':
+ iotests.main(supported_fmts=["qcow2"])
diff --git a/tests/qemu-iotests/139.out b/tests/qemu-iotests/139.out
new file mode 100644
index 000000000..281b69efe
--- /dev/null
+++ b/tests/qemu-iotests/139.out
@@ -0,0 +1,5 @@
+............
+----------------------------------------------------------------------
+Ran 12 tests
+
+OK
diff --git a/tests/qemu-iotests/144 b/tests/qemu-iotests/144
new file mode 100755
index 000000000..00de3c33c
--- /dev/null
+++ b/tests/qemu-iotests/144
@@ -0,0 +1,114 @@
+#!/bin/bash
+# Check live snapshot, followed by active commit, and another snapshot.
+#
+# This test is to catch the error case of BZ #1300209:
+# https://bugzilla.redhat.com/show_bug.cgi?id=1300209
+#
+# Copyright (C) 2016 Red Hat, Inc.
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+#
+
+# creator
+owner=jcody@redhat.com
+
+seq=`basename $0`
+echo "QA output created by $seq"
+
+here=`pwd`
+status=1 # failure is the default!
+
+TMP_SNAP1=${TEST_DIR}/tmp.qcow2
+TMP_SNAP2=${TEST_DIR}/tmp2.qcow2
+
+_cleanup()
+{
+ _cleanup_qemu
+ rm -f "${TEST_IMG}" "${TMP_SNAP1}" "${TMP_SNAP2}"
+}
+
+trap "_cleanup; exit \$status" 0 1 2 3 15
+
+# get standard environment, filters and checks
+. ./common.rc
+. ./common.filter
+. ./common.qemu
+
+_supported_fmt qcow2
+_supported_proto file
+_supported_os Linux
+
+size=512M
+
+_make_test_img $size
+
+echo
+echo === Launching QEMU ===
+echo
+
+qemu_comm_method="qmp"
+_launch_qemu -drive file="${TEST_IMG}",if=virtio
+h=$QEMU_HANDLE
+
+
+echo
+echo === Performing Live Snapshot 1 ===
+echo
+
+_send_qemu_cmd $h "{ 'execute': 'qmp_capabilities' }" "return"
+
+
+# First live snapshot, new overlay as active layer
+_send_qemu_cmd $h "{ 'execute': 'blockdev-snapshot-sync',
+ 'arguments': {
+ 'device': 'virtio0',
+ 'snapshot-file':'${TMP_SNAP1}',
+ 'format': 'qcow2'
+ }
+ }" "return"
+
+echo
+echo === Performing block-commit on active layer ===
+echo
+
+# Block commit on active layer, push the new overlay into base
+_send_qemu_cmd $h "{ 'execute': 'block-commit',
+ 'arguments': {
+ 'device': 'virtio0'
+ }
+ }" "READY"
+
+_send_qemu_cmd $h "{ 'execute': 'block-job-complete',
+ 'arguments': {
+ 'device': 'virtio0'
+ }
+ }" "COMPLETED"
+
+echo
+echo === Performing Live Snapshot 2 ===
+echo
+
+# New live snapshot, new overlays as active layer
+_send_qemu_cmd $h "{ 'execute': 'blockdev-snapshot-sync',
+ 'arguments': {
+ 'device': 'virtio0',
+ 'snapshot-file':'${TMP_SNAP2}',
+ 'format': 'qcow2'
+ }
+ }" "return"
+
+# success, all done
+echo "*** done"
+rm -f $seq.full
+status=0
diff --git a/tests/qemu-iotests/144.out b/tests/qemu-iotests/144.out
new file mode 100644
index 000000000..410d74180
--- /dev/null
+++ b/tests/qemu-iotests/144.out
@@ -0,0 +1,24 @@
+QA output created by 144
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=536870912
+
+=== Launching QEMU ===
+
+
+=== Performing Live Snapshot 1 ===
+
+{"return": {}}
+Formatting 'TEST_DIR/tmp.qcow2', fmt=qcow2 size=536870912 backing_file=TEST_DIR/t.qcow2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
+{"return": {}}
+
+=== Performing block-commit on active layer ===
+
+{"return": {}}
+{"timestamp": {"seconds": TIMESTAMP, "microseconds": TIMESTAMP}, "event": "BLOCK_JOB_READY", "data": {"device": "virtio0", "len": 0, "offset": 0, "speed": 0, "type": "commit"}}
+{"return": {}}
+{"timestamp": {"seconds": TIMESTAMP, "microseconds": TIMESTAMP}, "event": "BLOCK_JOB_COMPLETED", "data": {"device": "virtio0", "len": 0, "offset": 0, "speed": 0, "type": "commit"}}
+
+=== Performing Live Snapshot 2 ===
+
+Formatting 'TEST_DIR/tmp2.qcow2', fmt=qcow2 size=536870912 backing_file=TEST_DIR/t.qcow2 backing_fmt=qcow2 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
+{"return": {}}
+*** done
diff --git a/tests/qemu-iotests/check b/tests/qemu-iotests/check
index 1fa63193b..c350f16b6 100755
--- a/tests/qemu-iotests/check
+++ b/tests/qemu-iotests/check
@@ -231,10 +231,10 @@ FULL_HOST_DETAILS=`_full_platform_details`
#FULL_MOUNT_OPTIONS=`_scratch_mount_options`
cat <<EOF
-QEMU -- $QEMU
-QEMU_IMG -- $QEMU_IMG
-QEMU_IO -- $QEMU_IO
-QEMU_NBD -- $QEMU_NBD
+QEMU -- "$QEMU_PROG" $QEMU_OPTIONS
+QEMU_IMG -- "$QEMU_IMG_PROG" $QEMU_IMG_OPTIONS
+QEMU_IO -- "$QEMU_IO_PROG" $QEMU_IO_OPTIONS
+QEMU_NBD -- "$QEMU_NBD_PROG" $QEMU_NBD_OPTIONS
IMGFMT -- $FULL_IMGFMT_DETAILS
IMGPROTO -- $FULL_IMGPROTO_DETAILS
PLATFORM -- $FULL_HOST_DETAILS
@@ -330,6 +330,11 @@ do
fi
reference="$source_iotests/$seq.out"
+ reference_machine="$source_iotests/$seq.$QEMU_DEFAULT_MACHINE.out"
+ if [ -f "$reference_machine" ]; then
+ reference="$reference_machine"
+ fi
+
if [ "$CACHEMODE" = "none" ]; then
[ -f "$source_iotests/$seq.out.nocache" ] && reference="$source_iotests/$seq.out.nocache"
fi
diff --git a/tests/qemu-iotests/common b/tests/qemu-iotests/common
index 1030aaf25..ff84f4b0d 100644
--- a/tests/qemu-iotests/common
+++ b/tests/qemu-iotests/common
@@ -41,7 +41,6 @@ sortme=false
expunge=true
have_test_arg=false
randomize=false
-valgrind=false
cachemode=false
rm -f $tmp.list $tmp.tmp $tmp.sed
@@ -52,6 +51,8 @@ export IMGOPTS=""
export CACHEMODE="writeback"
export QEMU_IO_OPTIONS=""
export CACHEMODE_IS_DEFAULT=true
+export QEMU_OPTIONS="-nodefaults"
+export VALGRIND_QEMU=
for r
do
@@ -277,7 +278,7 @@ testlist options
;;
-valgrind)
- valgrind=true
+ VALGRIND_QEMU='y'
xpand=false
;;
@@ -435,8 +436,3 @@ fi
if [ "$IMGPROTO" = "nbd" ] ; then
[ "$QEMU_NBD" = "" ] && _fatal "qemu-nbd not found"
fi
-
-if $valgrind; then
- export REAL_QEMU_IO="$QEMU_IO_PROG"
- export QEMU_IO_PROG=valgrind_qemu_io
-fi
diff --git a/tests/qemu-iotests/common.config b/tests/qemu-iotests/common.config
index a1973ad9d..3ed51b8ba 100644
--- a/tests/qemu-iotests/common.config
+++ b/tests/qemu-iotests/common.config
@@ -44,6 +44,8 @@ export HOST_OPTIONS=${HOST_OPTIONS:=local.config}
export CHECK_OPTIONS=${CHECK_OPTIONS:="-g auto"}
export PWD=`pwd`
+export _QEMU_HANDLE=0
+
# $1 = prog to look for, $2* = default pathnames if not found in $PATH
set_prog_path()
{
@@ -103,10 +105,64 @@ if [ -z "$QEMU_NBD_PROG" ]; then
export QEMU_NBD_PROG="`set_prog_path qemu-nbd`"
fi
-export QEMU=$QEMU_PROG
-export QEMU_IMG=$QEMU_IMG_PROG
-export QEMU_IO="$QEMU_IO_PROG $QEMU_IO_OPTIONS"
-export QEMU_NBD=$QEMU_NBD_PROG
+_qemu_wrapper()
+{
+ (
+ if [ -n "${QEMU_NEED_PID}" ]; then
+ echo $BASHPID > "${TEST_DIR}/qemu-${_QEMU_HANDLE}.pid"
+ fi
+ exec "$QEMU_PROG" $QEMU_OPTIONS "$@"
+ )
+}
+
+_qemu_img_wrapper()
+{
+ (exec "$QEMU_IMG_PROG" $QEMU_IMG_OPTIONS "$@")
+}
+
+_qemu_io_wrapper()
+{
+ local VALGRIND_LOGFILE=/tmp/$$.valgrind
+ local RETVAL
+ (
+ if [ "${VALGRIND_QEMU}" == "y" ]; then
+ exec valgrind --log-file="${VALGRIND_LOGFILE}" --error-exitcode=99 "$QEMU_IO_PROG" $QEMU_IO_OPTIONS "$@"
+ else
+ exec "$QEMU_IO_PROG" $QEMU_IO_OPTIONS "$@"
+ fi
+ )
+ RETVAL=$?
+ if [ "${VALGRIND_QEMU}" == "y" ]; then
+ if [ $RETVAL == 99 ]; then
+ cat "${VALGRIND_LOGFILE}"
+ fi
+ rm -f "${VALGRIND_LOGFILE}"
+ fi
+ (exit $RETVAL)
+}
+
+_qemu_nbd_wrapper()
+{
+ (
+ echo $BASHPID > "${TEST_DIR}/qemu-nbd.pid"
+ exec "$QEMU_NBD_PROG" $QEMU_NBD_OPTIONS "$@"
+ )
+}
+
+export QEMU=_qemu_wrapper
+export QEMU_IMG=_qemu_img_wrapper
+export QEMU_IO=_qemu_io_wrapper
+export QEMU_NBD=_qemu_nbd_wrapper
+
+default_machine=$($QEMU -machine \? | awk '/(default)/{print $1}')
+default_alias_machine=$($QEMU -machine \? |\
+ awk -v var_default_machine="$default_machine"\)\
+ '{if ($(NF-2)=="(alias"&&$(NF-1)=="of"&&$(NF)==var_default_machine){print $1}}')
+if [ ! -z "$default_alias_machine" ]; then
+ default_machine="$default_alias_machine"
+fi
+
+export QEMU_DEFAULT_MACHINE="$default_machine"
[ -f /etc/qemu-iotest.config ] && . /etc/qemu-iotest.config
diff --git a/tests/qemu-iotests/common.filter b/tests/qemu-iotests/common.filter
index 012a8122d..cfdb6338a 100644
--- a/tests/qemu-iotests/common.filter
+++ b/tests/qemu-iotests/common.filter
@@ -128,6 +128,11 @@ _filter_date()
-e 's/[A-Z][a-z][a-z] [A-z][a-z][a-z] *[0-9][0-9]* [0-9][0-9]:[0-9][0-9]:[0-9][0-9] [0-9][0-9][0-9][0-9]$/DATE/'
}
+_filter_generated_node_ids()
+{
+ sed -re 's/\#block[0-9]{3,}/NODE_NAME/'
+}
+
# replace occurrences of the actual TEST_DIR value with TEST_DIR
_filter_testdir()
{
@@ -182,7 +187,7 @@ _filter_img_create()
-e "s# encryption=off##g" \
-e "s# cluster_size=[0-9]\\+##g" \
-e "s# table_size=[0-9]\\+##g" \
- -e "s# compat='[^']*'##g" \
+ -e "s# compat=[^ ]*##g" \
-e "s# compat6=\\(on\\|off\\)##g" \
-e "s# static=\\(on\\|off\\)##g" \
-e "s# zeroed_grain=\\(on\\|off\\)##g" \
diff --git a/tests/qemu-iotests/common.qemu b/tests/qemu-iotests/common.qemu
index 4e1996c3e..8bf396941 100644
--- a/tests/qemu-iotests/common.qemu
+++ b/tests/qemu-iotests/common.qemu
@@ -30,8 +30,6 @@ QEMU_COMM_TIMEOUT=10
QEMU_FIFO_IN="${TEST_DIR}/qmp-in-$$"
QEMU_FIFO_OUT="${TEST_DIR}/qmp-out-$$"
-QEMU_PID=
-_QEMU_HANDLE=0
QEMU_HANDLE=0
# If bash version is >= 4.1, these will be overwritten and dynamic
@@ -153,11 +151,11 @@ function _launch_qemu()
mkfifo "${fifo_out}"
mkfifo "${fifo_in}"
- "${QEMU}" -nographic -serial none ${comm} -machine accel=qtest "${@}" \
+ QEMU_NEED_PID='y'\
+ ${QEMU} -nographic -serial none ${comm} -machine accel=qtest "${@}" \
>"${fifo_out}" \
2>&1 \
<"${fifo_in}" &
- QEMU_PID[${_QEMU_HANDLE}]=$!
if [[ "${BASH_VERSINFO[0]}" -ge "5" ||
("${BASH_VERSINFO[0]}" -ge "4" && "${BASH_VERSINFO[1]}" -ge "1") ]]
@@ -196,10 +194,18 @@ function _cleanup_qemu()
# QEMU_PID[], QEMU_IN[], QEMU_OUT[] all use same indices
for i in "${!QEMU_OUT[@]}"
do
- if [ -z "${wait}" ]; then
- kill -KILL ${QEMU_PID[$i]} 2>/dev/null
+ local QEMU_PID
+ if [ -f "${TEST_DIR}/qemu-${i}.pid" ]; then
+ read QEMU_PID < "${TEST_DIR}/qemu-${i}.pid"
+ rm -f "${TEST_DIR}/qemu-${i}.pid"
+ if [ -z "${wait}" ] && [ -n "${QEMU_PID}" ]; then
+ kill -KILL ${QEMU_PID} 2>/dev/null
+ fi
+ if [ -n "${QEMU_PID}" ]; then
+ wait ${QEMU_PID} 2>/dev/null # silent kill
+ fi
fi
- wait ${QEMU_PID[$i]} 2>/dev/null # silent kill
+
if [ -n "${wait}" ]; then
cat <&${QEMU_OUT[$i]} | _filter_testdir | _filter_qemu \
| _filter_qemu_io | _filter_qmp
diff --git a/tests/qemu-iotests/common.rc b/tests/qemu-iotests/common.rc
index 22d351404..d9913f849 100644
--- a/tests/qemu-iotests/common.rc
+++ b/tests/qemu-iotests/common.rc
@@ -70,16 +70,6 @@ else
TEST_IMG=$IMGPROTO:$TEST_DIR/t.$IMGFMT
fi
-function valgrind_qemu_io()
-{
- valgrind --log-file=/tmp/$$.valgrind --error-exitcode=99 $REAL_QEMU_IO "$@"
- if [ $? != 0 ]; then
- cat /tmp/$$.valgrind
- fi
- rm -f /tmp/$$.valgrind
-}
-
-
_optstr_add()
{
if [ -n "$1" ]; then
@@ -154,7 +144,6 @@ _make_test_img()
# Start an NBD server on the image file, which is what we'll be talking to
if [ $IMGPROTO = "nbd" ]; then
eval "$QEMU_NBD -v -t -b 127.0.0.1 -p 10810 -f $IMGFMT $TEST_IMG_FILE &"
- QEMU_NBD_PID=$!
sleep 1 # FIXME: qemu-nbd needs to be listening before we continue
fi
}
@@ -175,8 +164,11 @@ _cleanup_test_img()
case "$IMGPROTO" in
nbd)
- if [ -n "$QEMU_NBD_PID" ]; then
- kill $QEMU_NBD_PID
+ if [ -f "${TEST_DIR}/qemu-nbd.pid" ]; then
+ local QEMU_NBD_PID
+ read QEMU_NBD_PID < "${TEST_DIR}/qemu-nbd.pid"
+ kill ${QEMU_NBD_PID}
+ rm -f "${TEST_DIR}/qemu-nbd.pid"
fi
rm -f "$TEST_IMG_FILE"
;;
@@ -439,7 +431,17 @@ _unsupported_imgopts()
#
_require_command()
{
- eval c=\$$1
+ if [ "$1" = "QEMU" ]; then
+ c=$QEMU_PROG
+ elif [ "$1" = "QEMU_IMG" ]; then
+ c=$QEMU_IMG_PROG
+ elif [ "$1" = "QEMU_IO" ]; then
+ c=$QEMU_IO_PROG
+ elif [ "$1" = "QEMU_NBD" ]; then
+ c=$QEMU_NBD_PROG
+ else
+ eval c=\$$1
+ fi
[ -x "$c" ] || _notrun "$1 utility required, skipped this test"
}
diff --git a/tests/qemu-iotests/group b/tests/qemu-iotests/group
index c430b6c23..d90629fc3 100644
--- a/tests/qemu-iotests/group
+++ b/tests/qemu-iotests/group
@@ -102,6 +102,7 @@
093 auto
094 rw auto quick
095 rw auto quick
+096 rw auto quick
097 rw auto backing
098 rw auto backing quick
099 rw auto quick
@@ -121,6 +122,7 @@
114 rw auto quick
115 rw auto
116 rw auto quick
+118 rw auto
119 rw auto quick
120 rw auto quick
121 rw auto
@@ -134,3 +136,8 @@
132 rw auto quick
134 rw auto quick
135 rw auto
+136 rw auto
+137 rw auto
+138 rw auto quick
+139 rw auto quick
+144 rw auto quick
diff --git a/tests/qemu-iotests/iotests.py b/tests/qemu-iotests/iotests.py
index 8615b1075..e02245ed0 100644
--- a/tests/qemu-iotests/iotests.py
+++ b/tests/qemu-iotests/iotests.py
@@ -31,37 +31,60 @@ import struct
__all__ = ['imgfmt', 'imgproto', 'test_dir' 'qemu_img', 'qemu_io',
'VM', 'QMPTestCase', 'notrun', 'main']
-# This will not work if arguments or path contain spaces but is necessary if we
+# This will not work if arguments contain spaces but is necessary if we
# want to support the override options that ./check supports.
-qemu_img_args = os.environ.get('QEMU_IMG', 'qemu-img').strip().split(' ')
-qemu_io_args = os.environ.get('QEMU_IO', 'qemu-io').strip().split(' ')
-qemu_args = os.environ.get('QEMU', 'qemu').strip().split(' ')
+qemu_img_args = [os.environ.get('QEMU_IMG_PROG', 'qemu-img')]
+if os.environ.get('QEMU_IMG_OPTIONS'):
+ qemu_img_args += os.environ['QEMU_IMG_OPTIONS'].strip().split(' ')
+
+qemu_io_args = [os.environ.get('QEMU_IO_PROG', 'qemu-io')]
+if os.environ.get('QEMU_IO_OPTIONS'):
+ qemu_io_args += os.environ['QEMU_IO_OPTIONS'].strip().split(' ')
+
+qemu_args = [os.environ.get('QEMU_PROG', 'qemu')]
+if os.environ.get('QEMU_OPTIONS'):
+ qemu_args += os.environ['QEMU_OPTIONS'].strip().split(' ')
imgfmt = os.environ.get('IMGFMT', 'raw')
imgproto = os.environ.get('IMGPROTO', 'file')
test_dir = os.environ.get('TEST_DIR', '/var/tmp')
output_dir = os.environ.get('OUTPUT_DIR', '.')
cachemode = os.environ.get('CACHEMODE')
+qemu_default_machine = os.environ.get('QEMU_DEFAULT_MACHINE')
socket_scm_helper = os.environ.get('SOCKET_SCM_HELPER', 'socket_scm_helper')
def qemu_img(*args):
'''Run qemu-img and return the exit code'''
devnull = open('/dev/null', 'r+')
- return subprocess.call(qemu_img_args + list(args), stdin=devnull, stdout=devnull)
+ exitcode = subprocess.call(qemu_img_args + list(args), stdin=devnull, stdout=devnull)
+ if exitcode < 0:
+ sys.stderr.write('qemu-img received signal %i: %s\n' % (-exitcode, ' '.join(qemu_img_args + list(args))))
+ return exitcode
def qemu_img_verbose(*args):
'''Run qemu-img without suppressing its output and return the exit code'''
- return subprocess.call(qemu_img_args + list(args))
+ exitcode = subprocess.call(qemu_img_args + list(args))
+ if exitcode < 0:
+ sys.stderr.write('qemu-img received signal %i: %s\n' % (-exitcode, ' '.join(qemu_img_args + list(args))))
+ return exitcode
def qemu_img_pipe(*args):
'''Run qemu-img and return its output'''
- return subprocess.Popen(qemu_img_args + list(args), stdout=subprocess.PIPE).communicate()[0]
+ subp = subprocess.Popen(qemu_img_args + list(args), stdout=subprocess.PIPE)
+ exitcode = subp.wait()
+ if exitcode < 0:
+ sys.stderr.write('qemu-img received signal %i: %s\n' % (-exitcode, ' '.join(qemu_img_args + list(args))))
+ return subp.communicate()[0]
def qemu_io(*args):
'''Run qemu-io and return the stdout data'''
args = qemu_io_args + list(args)
- return subprocess.Popen(args, stdout=subprocess.PIPE).communicate()[0]
+ subp = subprocess.Popen(args, stdout=subprocess.PIPE)
+ exitcode = subp.wait()
+ if exitcode < 0:
+ sys.stderr.write('qemu-io received signal %i: %s\n' % (-exitcode, ' '.join(args)))
+ return subp.communicate()[0]
def compare_images(img1, img2):
'''Return True if two image files are identical'''
@@ -117,13 +140,21 @@ class VM(object):
self._args.append('-monitor')
self._args.append(args)
- def add_drive(self, path, opts=''):
+ def add_drive_raw(self, opts):
+ self._args.append('-drive')
+ self._args.append(opts)
+ return self
+
+ def add_drive(self, path, opts='', interface='virtio'):
'''Add a virtio-blk drive to the VM'''
- options = ['if=virtio',
+ options = ['if=%s' % interface,
'format=%s' % imgfmt,
'cache=%s' % cachemode,
- 'file=%s' % path,
'id=drive%d' % self._num_drives]
+
+ if path is not None:
+ options.append('file=%s' % path)
+
if opts:
options.append(opts)
@@ -196,7 +227,9 @@ class VM(object):
'''Terminate the VM and clean up'''
if not self._popen is None:
self._qmp.cmd('quit')
- self._popen.wait()
+ exitcode = self._popen.wait()
+ if exitcode < 0:
+ sys.stderr.write('qemu received signal %i: %s\n' % (-exitcode, ' '.join(self._args)))
os.remove(self._monitor_path)
os.remove(self._qtest_path)
os.remove(self._qemu_log_path)
diff --git a/tests/qom-test.c b/tests/qom-test.c
index fde04e7a1..3e5e8730e 100644
--- a/tests/qom-test.c
+++ b/tests/qom-test.c
@@ -47,7 +47,7 @@ static bool is_blacklisted(const char *arch, const char *mach)
static void test_properties(const char *path, bool recurse)
{
char *child_path;
- QDict *response, *tuple;
+ QDict *response, *tuple, *tmp;
QList *list;
QListEntry *entry;
@@ -57,6 +57,7 @@ static void test_properties(const char *path, bool recurse)
g_assert(response);
if (!recurse) {
+ QDECREF(response);
return;
}
@@ -75,14 +76,16 @@ static void test_properties(const char *path, bool recurse)
} else {
const char *prop = qdict_get_str(tuple, "name");
g_test_message("Testing property %s.%s", path, prop);
- response = qmp("{ 'execute': 'qom-get',"
- " 'arguments': { 'path': %s,"
- " 'property': %s } }",
- path, prop);
+ tmp = qmp("{ 'execute': 'qom-get',"
+ " 'arguments': { 'path': %s,"
+ " 'property': %s } }",
+ path, prop);
/* qom-get may fail but should not, e.g., segfault. */
- g_assert(response);
+ g_assert(tmp);
+ QDECREF(tmp);
}
}
+ QDECREF(response);
}
static void test_machine(gconstpointer data)
@@ -98,9 +101,11 @@ static void test_machine(gconstpointer data)
response = qmp("{ 'execute': 'quit' }");
g_assert(qdict_haskey(response, "return"));
+ QDECREF(response);
qtest_end();
g_free(args);
+ g_free((void *)machine);
}
static void add_machine_test_cases(void)
@@ -129,10 +134,12 @@ static void add_machine_test_cases(void)
mname = qstring_get_str(qstr);
if (!is_blacklisted(arch, mname)) {
path = g_strdup_printf("qom/%s", mname);
- qtest_add_data_func(path, mname, test_machine);
+ qtest_add_data_func(path, g_strdup(mname), test_machine);
}
}
+
qtest_end();
+ QDECREF(response);
}
int main(int argc, char **argv)
diff --git a/tests/rtl8139-test.c b/tests/rtl8139-test.c
index e749be38e..ba62851ca 100644
--- a/tests/rtl8139-test.c
+++ b/tests/rtl8139-test.c
@@ -20,7 +20,7 @@ static void nop(void)
{
}
-#define CLK 33000000
+#define CLK 33333333
static QPCIBus *pcibus;
static QPCIDevice *dev;
diff --git a/tests/tcg/testthread.c b/tests/tcg/testthread.c
index 2679af119..810ba5de6 100644
--- a/tests/tcg/testthread.c
+++ b/tests/tcg/testthread.c
@@ -2,7 +2,6 @@
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
-#include <signal.h>
#include <unistd.h>
#include <inttypes.h>
#include <pthread.h>
diff --git a/tests/test-aio.c b/tests/test-aio.c
index 217e33772..e188d8c13 100644
--- a/tests/test-aio.c
+++ b/tests/test-aio.c
@@ -118,6 +118,12 @@ static void *test_acquire_thread(void *opaque)
return NULL;
}
+static void set_event_notifier(AioContext *ctx, EventNotifier *notifier,
+ EventNotifierHandler *handler)
+{
+ aio_set_event_notifier(ctx, notifier, false, handler);
+}
+
static void dummy_notifier_read(EventNotifier *unused)
{
g_assert(false); /* should never be invoked */
@@ -131,7 +137,7 @@ static void test_acquire(void)
/* Dummy event notifier ensures aio_poll() will block */
event_notifier_init(&notifier, false);
- aio_set_event_notifier(ctx, &notifier, dummy_notifier_read);
+ set_event_notifier(ctx, &notifier, dummy_notifier_read);
g_assert(!aio_poll(ctx, false)); /* consume aio_notify() */
qemu_mutex_init(&data.start_lock);
@@ -149,7 +155,7 @@ static void test_acquire(void)
aio_context_release(ctx);
qemu_thread_join(&thread);
- aio_set_event_notifier(ctx, &notifier, NULL);
+ set_event_notifier(ctx, &notifier, NULL);
event_notifier_cleanup(&notifier);
g_assert(data.thread_acquired);
@@ -308,11 +314,11 @@ static void test_set_event_notifier(void)
{
EventNotifierTestData data = { .n = 0, .active = 0 };
event_notifier_init(&data.e, false);
- aio_set_event_notifier(ctx, &data.e, event_ready_cb);
+ set_event_notifier(ctx, &data.e, event_ready_cb);
g_assert(!aio_poll(ctx, false));
g_assert_cmpint(data.n, ==, 0);
- aio_set_event_notifier(ctx, &data.e, NULL);
+ set_event_notifier(ctx, &data.e, NULL);
g_assert(!aio_poll(ctx, false));
g_assert_cmpint(data.n, ==, 0);
event_notifier_cleanup(&data.e);
@@ -322,7 +328,7 @@ static void test_wait_event_notifier(void)
{
EventNotifierTestData data = { .n = 0, .active = 1 };
event_notifier_init(&data.e, false);
- aio_set_event_notifier(ctx, &data.e, event_ready_cb);
+ set_event_notifier(ctx, &data.e, event_ready_cb);
while (aio_poll(ctx, false));
g_assert_cmpint(data.n, ==, 0);
g_assert_cmpint(data.active, ==, 1);
@@ -336,7 +342,7 @@ static void test_wait_event_notifier(void)
g_assert_cmpint(data.n, ==, 1);
g_assert_cmpint(data.active, ==, 0);
- aio_set_event_notifier(ctx, &data.e, NULL);
+ set_event_notifier(ctx, &data.e, NULL);
g_assert(!aio_poll(ctx, false));
g_assert_cmpint(data.n, ==, 1);
@@ -347,7 +353,7 @@ static void test_flush_event_notifier(void)
{
EventNotifierTestData data = { .n = 0, .active = 10, .auto_set = true };
event_notifier_init(&data.e, false);
- aio_set_event_notifier(ctx, &data.e, event_ready_cb);
+ set_event_notifier(ctx, &data.e, event_ready_cb);
while (aio_poll(ctx, false));
g_assert_cmpint(data.n, ==, 0);
g_assert_cmpint(data.active, ==, 10);
@@ -363,18 +369,42 @@ static void test_flush_event_notifier(void)
g_assert_cmpint(data.active, ==, 0);
g_assert(!aio_poll(ctx, false));
- aio_set_event_notifier(ctx, &data.e, NULL);
+ set_event_notifier(ctx, &data.e, NULL);
g_assert(!aio_poll(ctx, false));
event_notifier_cleanup(&data.e);
}
+static void test_aio_external_client(void)
+{
+ int i, j;
+
+ for (i = 1; i < 3; i++) {
+ EventNotifierTestData data = { .n = 0, .active = 10, .auto_set = true };
+ event_notifier_init(&data.e, false);
+ aio_set_event_notifier(ctx, &data.e, true, event_ready_cb);
+ event_notifier_set(&data.e);
+ for (j = 0; j < i; j++) {
+ aio_disable_external(ctx);
+ }
+ for (j = 0; j < i; j++) {
+ assert(!aio_poll(ctx, false));
+ assert(event_notifier_test_and_clear(&data.e));
+ event_notifier_set(&data.e);
+ aio_enable_external(ctx);
+ }
+ assert(aio_poll(ctx, false));
+ set_event_notifier(ctx, &data.e, NULL);
+ event_notifier_cleanup(&data.e);
+ }
+}
+
static void test_wait_event_notifier_noflush(void)
{
EventNotifierTestData data = { .n = 0 };
EventNotifierTestData dummy = { .n = 0, .active = 1 };
event_notifier_init(&data.e, false);
- aio_set_event_notifier(ctx, &data.e, event_ready_cb);
+ set_event_notifier(ctx, &data.e, event_ready_cb);
g_assert(!aio_poll(ctx, false));
g_assert_cmpint(data.n, ==, 0);
@@ -387,7 +417,7 @@ static void test_wait_event_notifier_noflush(void)
/* An active event notifier forces aio_poll to look at EventNotifiers. */
event_notifier_init(&dummy.e, false);
- aio_set_event_notifier(ctx, &dummy.e, event_ready_cb);
+ set_event_notifier(ctx, &dummy.e, event_ready_cb);
event_notifier_set(&data.e);
g_assert(aio_poll(ctx, false));
@@ -407,10 +437,10 @@ static void test_wait_event_notifier_noflush(void)
g_assert_cmpint(dummy.n, ==, 1);
g_assert_cmpint(dummy.active, ==, 0);
- aio_set_event_notifier(ctx, &dummy.e, NULL);
+ set_event_notifier(ctx, &dummy.e, NULL);
event_notifier_cleanup(&dummy.e);
- aio_set_event_notifier(ctx, &data.e, NULL);
+ set_event_notifier(ctx, &data.e, NULL);
g_assert(!aio_poll(ctx, false));
g_assert_cmpint(data.n, ==, 2);
@@ -428,7 +458,7 @@ static void test_timer_schedule(void)
* an fd to wait on. Fixing this breaks other tests. So create a dummy one.
*/
event_notifier_init(&e, false);
- aio_set_event_notifier(ctx, &e, dummy_io_handler_read);
+ set_event_notifier(ctx, &e, dummy_io_handler_read);
aio_poll(ctx, false);
aio_timer_init(ctx, &data.timer, data.clock_type,
@@ -467,7 +497,7 @@ static void test_timer_schedule(void)
g_assert(!aio_poll(ctx, false));
g_assert_cmpint(data.n, ==, 2);
- aio_set_event_notifier(ctx, &e, NULL);
+ set_event_notifier(ctx, &e, NULL);
event_notifier_cleanup(&e);
timer_del(&data.timer);
@@ -638,11 +668,11 @@ static void test_source_set_event_notifier(void)
{
EventNotifierTestData data = { .n = 0, .active = 0 };
event_notifier_init(&data.e, false);
- aio_set_event_notifier(ctx, &data.e, event_ready_cb);
+ set_event_notifier(ctx, &data.e, event_ready_cb);
while (g_main_context_iteration(NULL, false));
g_assert_cmpint(data.n, ==, 0);
- aio_set_event_notifier(ctx, &data.e, NULL);
+ set_event_notifier(ctx, &data.e, NULL);
while (g_main_context_iteration(NULL, false));
g_assert_cmpint(data.n, ==, 0);
event_notifier_cleanup(&data.e);
@@ -652,7 +682,7 @@ static void test_source_wait_event_notifier(void)
{
EventNotifierTestData data = { .n = 0, .active = 1 };
event_notifier_init(&data.e, false);
- aio_set_event_notifier(ctx, &data.e, event_ready_cb);
+ set_event_notifier(ctx, &data.e, event_ready_cb);
while (g_main_context_iteration(NULL, false));
g_assert_cmpint(data.n, ==, 0);
g_assert_cmpint(data.active, ==, 1);
@@ -666,7 +696,7 @@ static void test_source_wait_event_notifier(void)
g_assert_cmpint(data.n, ==, 1);
g_assert_cmpint(data.active, ==, 0);
- aio_set_event_notifier(ctx, &data.e, NULL);
+ set_event_notifier(ctx, &data.e, NULL);
while (g_main_context_iteration(NULL, false));
g_assert_cmpint(data.n, ==, 1);
@@ -677,7 +707,7 @@ static void test_source_flush_event_notifier(void)
{
EventNotifierTestData data = { .n = 0, .active = 10, .auto_set = true };
event_notifier_init(&data.e, false);
- aio_set_event_notifier(ctx, &data.e, event_ready_cb);
+ set_event_notifier(ctx, &data.e, event_ready_cb);
while (g_main_context_iteration(NULL, false));
g_assert_cmpint(data.n, ==, 0);
g_assert_cmpint(data.active, ==, 10);
@@ -693,7 +723,7 @@ static void test_source_flush_event_notifier(void)
g_assert_cmpint(data.active, ==, 0);
g_assert(!g_main_context_iteration(NULL, false));
- aio_set_event_notifier(ctx, &data.e, NULL);
+ set_event_notifier(ctx, &data.e, NULL);
while (g_main_context_iteration(NULL, false));
event_notifier_cleanup(&data.e);
}
@@ -704,7 +734,7 @@ static void test_source_wait_event_notifier_noflush(void)
EventNotifierTestData dummy = { .n = 0, .active = 1 };
event_notifier_init(&data.e, false);
- aio_set_event_notifier(ctx, &data.e, event_ready_cb);
+ set_event_notifier(ctx, &data.e, event_ready_cb);
while (g_main_context_iteration(NULL, false));
g_assert_cmpint(data.n, ==, 0);
@@ -717,7 +747,7 @@ static void test_source_wait_event_notifier_noflush(void)
/* An active event notifier forces aio_poll to look at EventNotifiers. */
event_notifier_init(&dummy.e, false);
- aio_set_event_notifier(ctx, &dummy.e, event_ready_cb);
+ set_event_notifier(ctx, &dummy.e, event_ready_cb);
event_notifier_set(&data.e);
g_assert(g_main_context_iteration(NULL, false));
@@ -737,10 +767,10 @@ static void test_source_wait_event_notifier_noflush(void)
g_assert_cmpint(dummy.n, ==, 1);
g_assert_cmpint(dummy.active, ==, 0);
- aio_set_event_notifier(ctx, &dummy.e, NULL);
+ set_event_notifier(ctx, &dummy.e, NULL);
event_notifier_cleanup(&dummy.e);
- aio_set_event_notifier(ctx, &data.e, NULL);
+ set_event_notifier(ctx, &data.e, NULL);
while (g_main_context_iteration(NULL, false));
g_assert_cmpint(data.n, ==, 2);
@@ -759,7 +789,7 @@ static void test_source_timer_schedule(void)
* an fd to wait on. Fixing this breaks other tests. So create a dummy one.
*/
event_notifier_init(&e, false);
- aio_set_event_notifier(ctx, &e, dummy_io_handler_read);
+ set_event_notifier(ctx, &e, dummy_io_handler_read);
do {} while (g_main_context_iteration(NULL, false));
aio_timer_init(ctx, &data.timer, data.clock_type,
@@ -784,7 +814,7 @@ static void test_source_timer_schedule(void)
g_assert_cmpint(data.n, ==, 2);
g_assert(qemu_clock_get_ns(data.clock_type) > expiry);
- aio_set_event_notifier(ctx, &e, NULL);
+ set_event_notifier(ctx, &e, NULL);
event_notifier_cleanup(&e);
timer_del(&data.timer);
@@ -826,6 +856,7 @@ int main(int argc, char **argv)
g_test_add_func("/aio/event/wait", test_wait_event_notifier);
g_test_add_func("/aio/event/wait/no-flush-cb", test_wait_event_notifier_noflush);
g_test_add_func("/aio/event/flush", test_flush_event_notifier);
+ g_test_add_func("/aio/external-client", test_aio_external_client);
g_test_add_func("/aio/timer/schedule", test_timer_schedule);
g_test_add_func("/aio-gsource/flush", test_source_flush);
diff --git a/tests/test-blockjob-txn.c b/tests/test-blockjob-txn.c
new file mode 100644
index 000000000..34747e924
--- /dev/null
+++ b/tests/test-blockjob-txn.c
@@ -0,0 +1,250 @@
+/*
+ * Blockjob transactions tests
+ *
+ * Copyright Red Hat, Inc. 2015
+ *
+ * Authors:
+ * Stefan Hajnoczi <stefanha@redhat.com>
+ *
+ * This work is licensed under the terms of the GNU LGPL, version 2 or later.
+ * See the COPYING.LIB file in the top-level directory.
+ */
+
+#include <glib.h>
+#include "qapi/error.h"
+#include "qemu/main-loop.h"
+#include "block/blockjob.h"
+
+typedef struct {
+ BlockJob common;
+ unsigned int iterations;
+ bool use_timer;
+ int rc;
+ int *result;
+} TestBlockJob;
+
+static const BlockJobDriver test_block_job_driver = {
+ .instance_size = sizeof(TestBlockJob),
+};
+
+static void test_block_job_complete(BlockJob *job, void *opaque)
+{
+ BlockDriverState *bs = job->bs;
+ int rc = (intptr_t)opaque;
+
+ if (block_job_is_cancelled(job)) {
+ rc = -ECANCELED;
+ }
+
+ block_job_completed(job, rc);
+ bdrv_unref(bs);
+}
+
+static void coroutine_fn test_block_job_run(void *opaque)
+{
+ TestBlockJob *s = opaque;
+ BlockJob *job = &s->common;
+
+ while (s->iterations--) {
+ if (s->use_timer) {
+ block_job_sleep_ns(job, QEMU_CLOCK_REALTIME, 0);
+ } else {
+ block_job_yield(job);
+ }
+
+ if (block_job_is_cancelled(job)) {
+ break;
+ }
+ }
+
+ block_job_defer_to_main_loop(job, test_block_job_complete,
+ (void *)(intptr_t)s->rc);
+}
+
+typedef struct {
+ TestBlockJob *job;
+ int *result;
+} TestBlockJobCBData;
+
+static void test_block_job_cb(void *opaque, int ret)
+{
+ TestBlockJobCBData *data = opaque;
+ if (!ret && block_job_is_cancelled(&data->job->common)) {
+ ret = -ECANCELED;
+ }
+ *data->result = ret;
+ g_free(data);
+}
+
+/* Create a block job that completes with a given return code after a given
+ * number of event loop iterations. The return code is stored in the given
+ * result pointer.
+ *
+ * The event loop iterations can either be handled automatically with a 0 delay
+ * timer, or they can be stepped manually by entering the coroutine.
+ */
+static BlockJob *test_block_job_start(unsigned int iterations,
+ bool use_timer,
+ int rc, int *result)
+{
+ BlockDriverState *bs;
+ TestBlockJob *s;
+ TestBlockJobCBData *data;
+
+ data = g_new0(TestBlockJobCBData, 1);
+ bs = bdrv_new();
+ s = block_job_create(&test_block_job_driver, bs, 0, test_block_job_cb,
+ data, &error_abort);
+ s->iterations = iterations;
+ s->use_timer = use_timer;
+ s->rc = rc;
+ s->result = result;
+ s->common.co = qemu_coroutine_create(test_block_job_run);
+ data->job = s;
+ data->result = result;
+ qemu_coroutine_enter(s->common.co, s);
+ return &s->common;
+}
+
+static void test_single_job(int expected)
+{
+ BlockJob *job;
+ BlockJobTxn *txn;
+ int result = -EINPROGRESS;
+
+ txn = block_job_txn_new();
+ job = test_block_job_start(1, true, expected, &result);
+ block_job_txn_add_job(txn, job);
+
+ if (expected == -ECANCELED) {
+ block_job_cancel(job);
+ }
+
+ while (result == -EINPROGRESS) {
+ aio_poll(qemu_get_aio_context(), true);
+ }
+ g_assert_cmpint(result, ==, expected);
+
+ block_job_txn_unref(txn);
+}
+
+static void test_single_job_success(void)
+{
+ test_single_job(0);
+}
+
+static void test_single_job_failure(void)
+{
+ test_single_job(-EIO);
+}
+
+static void test_single_job_cancel(void)
+{
+ test_single_job(-ECANCELED);
+}
+
+static void test_pair_jobs(int expected1, int expected2)
+{
+ BlockJob *job1;
+ BlockJob *job2;
+ BlockJobTxn *txn;
+ int result1 = -EINPROGRESS;
+ int result2 = -EINPROGRESS;
+
+ txn = block_job_txn_new();
+ job1 = test_block_job_start(1, true, expected1, &result1);
+ block_job_txn_add_job(txn, job1);
+ job2 = test_block_job_start(2, true, expected2, &result2);
+ block_job_txn_add_job(txn, job2);
+
+ if (expected1 == -ECANCELED) {
+ block_job_cancel(job1);
+ }
+ if (expected2 == -ECANCELED) {
+ block_job_cancel(job2);
+ }
+
+ while (result1 == -EINPROGRESS || result2 == -EINPROGRESS) {
+ aio_poll(qemu_get_aio_context(), true);
+ }
+
+ /* Failure or cancellation of one job cancels the other job */
+ if (expected1 != 0) {
+ expected2 = -ECANCELED;
+ } else if (expected2 != 0) {
+ expected1 = -ECANCELED;
+ }
+
+ g_assert_cmpint(result1, ==, expected1);
+ g_assert_cmpint(result2, ==, expected2);
+
+ block_job_txn_unref(txn);
+}
+
+static void test_pair_jobs_success(void)
+{
+ test_pair_jobs(0, 0);
+}
+
+static void test_pair_jobs_failure(void)
+{
+ /* Test both orderings. The two jobs run for a different number of
+ * iterations so the code path is different depending on which job fails
+ * first.
+ */
+ test_pair_jobs(-EIO, 0);
+ test_pair_jobs(0, -EIO);
+}
+
+static void test_pair_jobs_cancel(void)
+{
+ test_pair_jobs(-ECANCELED, 0);
+ test_pair_jobs(0, -ECANCELED);
+}
+
+static void test_pair_jobs_fail_cancel_race(void)
+{
+ BlockJob *job1;
+ BlockJob *job2;
+ BlockJobTxn *txn;
+ int result1 = -EINPROGRESS;
+ int result2 = -EINPROGRESS;
+
+ txn = block_job_txn_new();
+ job1 = test_block_job_start(1, true, -ECANCELED, &result1);
+ block_job_txn_add_job(txn, job1);
+ job2 = test_block_job_start(2, false, 0, &result2);
+ block_job_txn_add_job(txn, job2);
+
+ block_job_cancel(job1);
+
+ /* Now make job2 finish before the main loop kicks jobs. This simulates
+ * the race between a pending kick and another job completing.
+ */
+ block_job_enter(job2);
+ block_job_enter(job2);
+
+ while (result1 == -EINPROGRESS || result2 == -EINPROGRESS) {
+ aio_poll(qemu_get_aio_context(), true);
+ }
+
+ g_assert_cmpint(result1, ==, -ECANCELED);
+ g_assert_cmpint(result2, ==, -ECANCELED);
+
+ block_job_txn_unref(txn);
+}
+
+int main(int argc, char **argv)
+{
+ qemu_init_main_loop(&error_abort);
+
+ g_test_init(&argc, &argv, NULL);
+ g_test_add_func("/single/success", test_single_job_success);
+ g_test_add_func("/single/failure", test_single_job_failure);
+ g_test_add_func("/single/cancel", test_single_job_cancel);
+ g_test_add_func("/pair/success", test_pair_jobs_success);
+ g_test_add_func("/pair/failure", test_pair_jobs_failure);
+ g_test_add_func("/pair/cancel", test_pair_jobs_cancel);
+ g_test_add_func("/pair/fail-cancel-race", test_pair_jobs_fail_cancel_race);
+ return g_test_run();
+}
diff --git a/tests/test-coroutine.c b/tests/test-coroutine.c
index b552d9f5e..f5951cb1f 100644
--- a/tests/test-coroutine.c
+++ b/tests/test-coroutine.c
@@ -12,8 +12,8 @@
*/
#include <glib.h>
-#include "block/coroutine.h"
-#include "block/coroutine_int.h"
+#include "qemu/coroutine.h"
+#include "qemu/coroutine_int.h"
/*
* Check that qemu_in_coroutine() works
diff --git a/tests/test-crypto-cipher.c b/tests/test-crypto-cipher.c
index 9d38d2640..f4946a0af 100644
--- a/tests/test-crypto-cipher.c
+++ b/tests/test-crypto-cipher.c
@@ -287,6 +287,79 @@ static void test_cipher(const void *opaque)
qcrypto_cipher_free(cipher);
}
+
+static void test_cipher_null_iv(void)
+{
+ QCryptoCipher *cipher;
+ uint8_t key[32] = { 0 };
+ uint8_t plaintext[32] = { 0 };
+ uint8_t ciphertext[32] = { 0 };
+
+ cipher = qcrypto_cipher_new(
+ QCRYPTO_CIPHER_ALG_AES_256,
+ QCRYPTO_CIPHER_MODE_CBC,
+ key, sizeof(key),
+ &error_abort);
+ g_assert(cipher != NULL);
+
+ /* Don't call qcrypto_cipher_setiv */
+
+ qcrypto_cipher_encrypt(cipher,
+ plaintext,
+ ciphertext,
+ sizeof(plaintext),
+ &error_abort);
+
+ qcrypto_cipher_free(cipher);
+}
+
+static void test_cipher_short_plaintext(void)
+{
+ Error *err = NULL;
+ QCryptoCipher *cipher;
+ uint8_t key[32] = { 0 };
+ uint8_t plaintext1[20] = { 0 };
+ uint8_t ciphertext1[20] = { 0 };
+ uint8_t plaintext2[40] = { 0 };
+ uint8_t ciphertext2[40] = { 0 };
+ int ret;
+
+ cipher = qcrypto_cipher_new(
+ QCRYPTO_CIPHER_ALG_AES_256,
+ QCRYPTO_CIPHER_MODE_CBC,
+ key, sizeof(key),
+ &error_abort);
+ g_assert(cipher != NULL);
+
+ /* Should report an error as plaintext is shorter
+ * than block size
+ */
+ ret = qcrypto_cipher_encrypt(cipher,
+ plaintext1,
+ ciphertext1,
+ sizeof(plaintext1),
+ &err);
+ g_assert(ret == -1);
+ g_assert(err != NULL);
+
+ error_free(err);
+ err = NULL;
+
+ /* Should report an error as plaintext is larger than
+ * block size, but not a multiple of block size
+ */
+ ret = qcrypto_cipher_encrypt(cipher,
+ plaintext2,
+ ciphertext2,
+ sizeof(plaintext2),
+ &err);
+ g_assert(ret == -1);
+ g_assert(err != NULL);
+
+ error_free(err);
+ qcrypto_cipher_free(cipher);
+}
+
int main(int argc, char **argv)
{
size_t i;
@@ -298,5 +371,12 @@ int main(int argc, char **argv)
for (i = 0; i < G_N_ELEMENTS(test_data); i++) {
g_test_add_data_func(test_data[i].path, &test_data[i], test_cipher);
}
+
+ g_test_add_func("/crypto/cipher/null-iv",
+ test_cipher_null_iv);
+
+ g_test_add_func("/crypto/cipher/short-plaintext",
+ test_cipher_short_plaintext);
+
return g_test_run();
}
diff --git a/tests/test-crypto-tlscredsx509.c b/tests/test-crypto-tlscredsx509.c
new file mode 100644
index 000000000..c70aa5563
--- /dev/null
+++ b/tests/test-crypto-tlscredsx509.c
@@ -0,0 +1,731 @@
+/*
+ * Copyright (C) 2015 Red Hat, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library. If not, see
+ * <http://www.gnu.org/licenses/>.
+ *
+ * Author: Daniel P. Berrange <berrange@redhat.com>
+ */
+
+#include <stdlib.h>
+#include <fcntl.h>
+
+#include "config-host.h"
+#include "crypto-tls-x509-helpers.h"
+#include "crypto/tlscredsx509.h"
+
+#ifdef QCRYPTO_HAVE_TLS_TEST_SUPPORT
+
+#define WORKDIR "tests/test-crypto-tlscredsx509-work/"
+#define KEYFILE WORKDIR "key-ctx.pem"
+
+struct QCryptoTLSCredsTestData {
+ bool isServer;
+ const char *cacrt;
+ const char *crt;
+ bool expectFail;
+};
+
+
+static QCryptoTLSCreds *test_tls_creds_create(QCryptoTLSCredsEndpoint endpoint,
+ const char *certdir,
+ Error **errp)
+{
+ Object *parent = object_get_objects_root();
+ Object *creds = object_new_with_props(
+ TYPE_QCRYPTO_TLS_CREDS_X509,
+ parent,
+ "testtlscreds",
+ errp,
+ "endpoint", (endpoint == QCRYPTO_TLS_CREDS_ENDPOINT_SERVER ?
+ "server" : "client"),
+ "dir", certdir,
+ "verify-peer", "yes",
+ "sanity-check", "yes",
+ NULL);
+
+ if (*errp) {
+ return NULL;
+ }
+ return QCRYPTO_TLS_CREDS(creds);
+}
+
+/*
+ * This tests sanity checking of our own certificates
+ *
+ * The code being tested is used when TLS creds are created,
+ * and aim to ensure QMEU has been configured with sane
+ * certificates. This allows us to give much much much
+ * clearer error messages to the admin when they misconfigure
+ * things.
+ */
+static void test_tls_creds(const void *opaque)
+{
+ struct QCryptoTLSCredsTestData *data =
+ (struct QCryptoTLSCredsTestData *)opaque;
+ QCryptoTLSCreds *creds;
+ Error *err = NULL;
+
+#define CERT_DIR "tests/test-crypto-tlscredsx509-certs/"
+ mkdir(CERT_DIR, 0700);
+
+ unlink(CERT_DIR QCRYPTO_TLS_CREDS_X509_CA_CERT);
+ if (data->isServer) {
+ unlink(CERT_DIR QCRYPTO_TLS_CREDS_X509_SERVER_CERT);
+ unlink(CERT_DIR QCRYPTO_TLS_CREDS_X509_SERVER_KEY);
+ } else {
+ unlink(CERT_DIR QCRYPTO_TLS_CREDS_X509_CLIENT_CERT);
+ unlink(CERT_DIR QCRYPTO_TLS_CREDS_X509_CLIENT_KEY);
+ }
+
+ if (access(data->cacrt, R_OK) == 0) {
+ g_assert(link(data->cacrt,
+ CERT_DIR QCRYPTO_TLS_CREDS_X509_CA_CERT) == 0);
+ }
+ if (data->isServer) {
+ if (access(data->crt, R_OK) == 0) {
+ g_assert(link(data->crt,
+ CERT_DIR QCRYPTO_TLS_CREDS_X509_SERVER_CERT) == 0);
+ }
+ g_assert(link(KEYFILE,
+ CERT_DIR QCRYPTO_TLS_CREDS_X509_SERVER_KEY) == 0);
+ } else {
+ if (access(data->crt, R_OK) == 0) {
+ g_assert(link(data->crt,
+ CERT_DIR QCRYPTO_TLS_CREDS_X509_CLIENT_CERT) == 0);
+ }
+ g_assert(link(KEYFILE,
+ CERT_DIR QCRYPTO_TLS_CREDS_X509_CLIENT_KEY) == 0);
+ }
+
+ creds = test_tls_creds_create(
+ (data->isServer ?
+ QCRYPTO_TLS_CREDS_ENDPOINT_SERVER :
+ QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT),
+ CERT_DIR,
+ &err);
+
+ if (data->expectFail) {
+ error_free(err);
+ g_assert(creds == NULL);
+ } else {
+ if (err) {
+ g_printerr("Failed to generate creds: %s\n",
+ error_get_pretty(err));
+ error_free(err);
+ }
+ g_assert(creds != NULL);
+ }
+
+ unlink(CERT_DIR QCRYPTO_TLS_CREDS_X509_CA_CERT);
+ if (data->isServer) {
+ unlink(CERT_DIR QCRYPTO_TLS_CREDS_X509_SERVER_CERT);
+ unlink(CERT_DIR QCRYPTO_TLS_CREDS_X509_SERVER_KEY);
+ } else {
+ unlink(CERT_DIR QCRYPTO_TLS_CREDS_X509_CLIENT_CERT);
+ unlink(CERT_DIR QCRYPTO_TLS_CREDS_X509_CLIENT_KEY);
+ }
+ rmdir(CERT_DIR);
+ if (creds) {
+ object_unparent(OBJECT(creds));
+ }
+}
+
+int main(int argc, char **argv)
+{
+ int ret;
+
+ module_call_init(MODULE_INIT_QOM);
+ g_test_init(&argc, &argv, NULL);
+ setenv("GNUTLS_FORCE_FIPS_MODE", "2", 1);
+
+ mkdir(WORKDIR, 0700);
+
+ test_tls_init(KEYFILE);
+
+# define TLS_TEST_REG(name, isServer, caCrt, crt, expectFail) \
+ struct QCryptoTLSCredsTestData name = { \
+ isServer, caCrt, crt, expectFail \
+ }; \
+ g_test_add_data_func("/qcrypto/tlscredsx509/" # name, \
+ &name, test_tls_creds); \
+
+ /* A perfect CA, perfect client & perfect server */
+
+ /* Basic:CA:critical */
+ TLS_ROOT_REQ(cacertreq,
+ "UK", "qemu CA", NULL, NULL, NULL, NULL,
+ true, true, true,
+ true, true, GNUTLS_KEY_KEY_CERT_SIGN,
+ false, false, NULL, NULL,
+ 0, 0);
+
+ TLS_CERT_REQ(servercertreq, cacertreq,
+ "UK", "qemu.org", NULL, NULL, NULL, NULL,
+ true, true, false,
+ true, true,
+ GNUTLS_KEY_DIGITAL_SIGNATURE | GNUTLS_KEY_KEY_ENCIPHERMENT,
+ true, true, GNUTLS_KP_TLS_WWW_SERVER, NULL,
+ 0, 0);
+ TLS_CERT_REQ(clientcertreq, cacertreq,
+ "UK", "qemu", NULL, NULL, NULL, NULL,
+ true, true, false,
+ true, true,
+ GNUTLS_KEY_DIGITAL_SIGNATURE | GNUTLS_KEY_KEY_ENCIPHERMENT,
+ true, true, GNUTLS_KP_TLS_WWW_CLIENT, NULL,
+ 0, 0);
+
+ TLS_TEST_REG(perfectserver, true,
+ cacertreq.filename, servercertreq.filename, false);
+ TLS_TEST_REG(perfectclient, false,
+ cacertreq.filename, clientcertreq.filename, false);
+
+
+ /* Some other CAs which are good */
+
+ /* Basic:CA:critical */
+ TLS_ROOT_REQ(cacert1req,
+ "UK", "qemu CA 1", NULL, NULL, NULL, NULL,
+ true, true, true,
+ false, false, 0,
+ false, false, NULL, NULL,
+ 0, 0);
+ TLS_CERT_REQ(servercert1req, cacert1req,
+ "UK", "qemu.org", NULL, NULL, NULL, NULL,
+ true, true, false,
+ true, true,
+ GNUTLS_KEY_DIGITAL_SIGNATURE | GNUTLS_KEY_KEY_ENCIPHERMENT,
+ true, true, GNUTLS_KP_TLS_WWW_SERVER, NULL,
+ 0, 0);
+
+ /* Basic:CA:not-critical */
+ TLS_ROOT_REQ(cacert2req,
+ "UK", "qemu CA 2", NULL, NULL, NULL, NULL,
+ true, false, true,
+ false, false, 0,
+ false, false, NULL, NULL,
+ 0, 0);
+ TLS_CERT_REQ(servercert2req, cacert2req,
+ "UK", "qemu.org", NULL, NULL, NULL, NULL,
+ true, true, false,
+ true, true,
+ GNUTLS_KEY_DIGITAL_SIGNATURE | GNUTLS_KEY_KEY_ENCIPHERMENT,
+ true, true, GNUTLS_KP_TLS_WWW_SERVER, NULL,
+ 0, 0);
+
+ /* Key usage:cert-sign:critical */
+ TLS_ROOT_REQ(cacert3req,
+ "UK", "qemu CA 3", NULL, NULL, NULL, NULL,
+ true, true, true,
+ true, true, GNUTLS_KEY_KEY_CERT_SIGN,
+ false, false, NULL, NULL,
+ 0, 0);
+ TLS_CERT_REQ(servercert3req, cacert3req,
+ "UK", "qemu.org", NULL, NULL, NULL, NULL,
+ true, true, false,
+ true, true,
+ GNUTLS_KEY_DIGITAL_SIGNATURE | GNUTLS_KEY_KEY_ENCIPHERMENT,
+ true, true, GNUTLS_KP_TLS_WWW_SERVER, NULL,
+ 0, 0);
+
+ TLS_TEST_REG(goodca1, true,
+ cacert1req.filename, servercert1req.filename, false);
+ TLS_TEST_REG(goodca2, true,
+ cacert2req.filename, servercert2req.filename, false);
+ TLS_TEST_REG(goodca3, true,
+ cacert3req.filename, servercert3req.filename, false);
+
+ /* Now some bad certs */
+
+ /* Key usage:dig-sig:not-critical */
+ TLS_ROOT_REQ(cacert4req,
+ "UK", "qemu CA 4", NULL, NULL, NULL, NULL,
+ true, true, true,
+ true, false, GNUTLS_KEY_DIGITAL_SIGNATURE,
+ false, false, NULL, NULL,
+ 0, 0);
+ TLS_CERT_REQ(servercert4req, cacert4req,
+ "UK", "qemu.org", NULL, NULL, NULL, NULL,
+ true, true, false,
+ true, true,
+ GNUTLS_KEY_DIGITAL_SIGNATURE | GNUTLS_KEY_KEY_ENCIPHERMENT,
+ true, true, GNUTLS_KP_TLS_WWW_SERVER, NULL,
+ 0, 0);
+ /* no-basic */
+ TLS_ROOT_REQ(cacert5req,
+ "UK", "qemu CA 5", NULL, NULL, NULL, NULL,
+ false, false, false,
+ false, false, 0,
+ false, false, NULL, NULL,
+ 0, 0);
+ TLS_CERT_REQ(servercert5req, cacert5req,
+ "UK", "qemu.org", NULL, NULL, NULL, NULL,
+ true, true, false,
+ true, true,
+ GNUTLS_KEY_DIGITAL_SIGNATURE | GNUTLS_KEY_KEY_ENCIPHERMENT,
+ true, true, GNUTLS_KP_TLS_WWW_SERVER, NULL,
+ 0, 0);
+ /* Key usage:dig-sig:critical */
+ TLS_ROOT_REQ(cacert6req,
+ "UK", "qemu CA 6", NULL, NULL, NULL, NULL,
+ true, true, true,
+ true, true, GNUTLS_KEY_DIGITAL_SIGNATURE,
+ false, false, NULL, NULL,
+ 0, 0);
+ TLS_CERT_REQ(servercert6req, cacert6req,
+ "UK", "qemu.org", NULL, NULL, NULL, NULL,
+ true, true, false,
+ true, true,
+ GNUTLS_KEY_DIGITAL_SIGNATURE | GNUTLS_KEY_KEY_ENCIPHERMENT,
+ true, true, GNUTLS_KP_TLS_WWW_SERVER, NULL,
+ 0, 0);
+
+ /* Technically a CA cert with basic constraints
+ * key purpose == key signing + non-critical should
+ * be rejected. GNUTLS < 3.1 does not reject it and
+ * we don't anticipate them changing this behaviour
+ */
+ TLS_TEST_REG(badca1, true, cacert4req.filename, servercert4req.filename,
+ (GNUTLS_VERSION_MAJOR == 3 && GNUTLS_VERSION_MINOR >= 1) ||
+ GNUTLS_VERSION_MAJOR > 3);
+ TLS_TEST_REG(badca2, true,
+ cacert5req.filename, servercert5req.filename, true);
+ TLS_TEST_REG(badca3, true,
+ cacert6req.filename, servercert6req.filename, true);
+
+
+ /* Various good servers */
+ /* no usage or purpose */
+ TLS_CERT_REQ(servercert7req, cacertreq,
+ "UK", "qemu", NULL, NULL, NULL, NULL,
+ true, true, false,
+ false, false, 0,
+ false, false, NULL, NULL,
+ 0, 0);
+ /* usage:cert-sign+dig-sig+encipher:critical */
+ TLS_CERT_REQ(servercert8req, cacertreq,
+ "UK", "qemu", NULL, NULL, NULL, NULL,
+ true, true, false,
+ true, true,
+ GNUTLS_KEY_DIGITAL_SIGNATURE | GNUTLS_KEY_KEY_ENCIPHERMENT |
+ GNUTLS_KEY_KEY_CERT_SIGN,
+ false, false, NULL, NULL,
+ 0, 0);
+ /* usage:cert-sign:not-critical */
+ TLS_CERT_REQ(servercert9req, cacertreq,
+ "UK", "qemu", NULL, NULL, NULL, NULL,
+ true, true, false,
+ true, false, GNUTLS_KEY_KEY_CERT_SIGN,
+ false, false, NULL, NULL,
+ 0, 0);
+ /* purpose:server:critical */
+ TLS_CERT_REQ(servercert10req, cacertreq,
+ "UK", "qemu", NULL, NULL, NULL, NULL,
+ true, true, false,
+ false, false, 0,
+ true, true, GNUTLS_KP_TLS_WWW_SERVER, NULL,
+ 0, 0);
+ /* purpose:server:not-critical */
+ TLS_CERT_REQ(servercert11req, cacertreq,
+ "UK", "qemu", NULL, NULL, NULL, NULL,
+ true, true, false,
+ false, false, 0,
+ true, false, GNUTLS_KP_TLS_WWW_SERVER, NULL,
+ 0, 0);
+ /* purpose:client+server:critical */
+ TLS_CERT_REQ(servercert12req, cacertreq,
+ "UK", "qemu", NULL, NULL, NULL, NULL,
+ true, true, false,
+ false, false, 0,
+ true, true,
+ GNUTLS_KP_TLS_WWW_CLIENT, GNUTLS_KP_TLS_WWW_SERVER,
+ 0, 0);
+ /* purpose:client+server:not-critical */
+ TLS_CERT_REQ(servercert13req, cacertreq,
+ "UK", "qemu", NULL, NULL, NULL, NULL,
+ true, true, false,
+ false, false, 0,
+ true, false,
+ GNUTLS_KP_TLS_WWW_CLIENT, GNUTLS_KP_TLS_WWW_SERVER,
+ 0, 0);
+
+ TLS_TEST_REG(goodserver1, true,
+ cacertreq.filename, servercert7req.filename, false);
+ TLS_TEST_REG(goodserver2, true,
+ cacertreq.filename, servercert8req.filename, false);
+ TLS_TEST_REG(goodserver3, true,
+ cacertreq.filename, servercert9req.filename, false);
+ TLS_TEST_REG(goodserver4, true,
+ cacertreq.filename, servercert10req.filename, false);
+ TLS_TEST_REG(goodserver5, true,
+ cacertreq.filename, servercert11req.filename, false);
+ TLS_TEST_REG(goodserver6, true,
+ cacertreq.filename, servercert12req.filename, false);
+ TLS_TEST_REG(goodserver7, true,
+ cacertreq.filename, servercert13req.filename, false);
+
+ /* Bad servers */
+
+ /* usage:cert-sign:critical */
+ TLS_CERT_REQ(servercert14req, cacertreq,
+ "UK", "qemu", NULL, NULL, NULL, NULL,
+ true, true, false,
+ true, true, GNUTLS_KEY_KEY_CERT_SIGN,
+ false, false, NULL, NULL,
+ 0, 0);
+ /* purpose:client:critical */
+ TLS_CERT_REQ(servercert15req, cacertreq,
+ "UK", "qemu", NULL, NULL, NULL, NULL,
+ true, true, false,
+ false, false, 0,
+ true, true, GNUTLS_KP_TLS_WWW_CLIENT, NULL,
+ 0, 0);
+ /* usage: none:critical */
+ TLS_CERT_REQ(servercert16req, cacertreq,
+ "UK", "qemu", NULL, NULL, NULL, NULL,
+ true, true, false,
+ true, true, 0,
+ false, false, NULL, NULL,
+ 0, 0);
+
+ TLS_TEST_REG(badserver1, true,
+ cacertreq.filename, servercert14req.filename, true);
+ TLS_TEST_REG(badserver2, true,
+ cacertreq.filename, servercert15req.filename, true);
+ TLS_TEST_REG(badserver3, true,
+ cacertreq.filename, servercert16req.filename, true);
+
+
+
+ /* Various good clients */
+ /* no usage or purpose */
+ TLS_CERT_REQ(clientcert1req, cacertreq,
+ "UK", "qemu", NULL, NULL, NULL, NULL,
+ true, true, false,
+ false, false, 0,
+ false, false, NULL, NULL,
+ 0, 0);
+ /* usage:cert-sign+dig-sig+encipher:critical */
+ TLS_CERT_REQ(clientcert2req, cacertreq,
+ "UK", "qemu", NULL, NULL, NULL, NULL,
+ true, true, false,
+ true, true,
+ GNUTLS_KEY_DIGITAL_SIGNATURE | GNUTLS_KEY_KEY_ENCIPHERMENT |
+ GNUTLS_KEY_KEY_CERT_SIGN,
+ false, false, NULL, NULL,
+ 0, 0);
+ /* usage:cert-sign:not-critical */
+ TLS_CERT_REQ(clientcert3req, cacertreq,
+ "UK", "qemu", NULL, NULL, NULL, NULL,
+ true, true, false,
+ true, false, GNUTLS_KEY_KEY_CERT_SIGN,
+ false, false, NULL, NULL,
+ 0, 0);
+ /* purpose:client:critical */
+ TLS_CERT_REQ(clientcert4req, cacertreq,
+ "UK", "qemu", NULL, NULL, NULL, NULL,
+ true, true, false,
+ false, false, 0,
+ true, true, GNUTLS_KP_TLS_WWW_CLIENT, NULL,
+ 0, 0);
+ /* purpose:client:not-critical */
+ TLS_CERT_REQ(clientcert5req, cacertreq,
+ "UK", "qemu", NULL, NULL, NULL, NULL,
+ true, true, false,
+ false, false, 0,
+ true, false, GNUTLS_KP_TLS_WWW_CLIENT, NULL,
+ 0, 0);
+ /* purpose:client+client:critical */
+ TLS_CERT_REQ(clientcert6req, cacertreq,
+ "UK", "qemu", NULL, NULL, NULL, NULL,
+ true, true, false,
+ false, false, 0,
+ true, true,
+ GNUTLS_KP_TLS_WWW_CLIENT, GNUTLS_KP_TLS_WWW_SERVER,
+ 0, 0);
+ /* purpose:client+client:not-critical */
+ TLS_CERT_REQ(clientcert7req, cacertreq,
+ "UK", "qemu", NULL, NULL, NULL, NULL,
+ true, true, false,
+ false, false, 0,
+ true, false,
+ GNUTLS_KP_TLS_WWW_CLIENT, GNUTLS_KP_TLS_WWW_SERVER,
+ 0, 0);
+
+ TLS_TEST_REG(goodclient1, false,
+ cacertreq.filename, clientcert1req.filename, false);
+ TLS_TEST_REG(goodclient2, false,
+ cacertreq.filename, clientcert2req.filename, false);
+ TLS_TEST_REG(goodclient3, false,
+ cacertreq.filename, clientcert3req.filename, false);
+ TLS_TEST_REG(goodclient4, false,
+ cacertreq.filename, clientcert4req.filename, false);
+ TLS_TEST_REG(goodclient5, false,
+ cacertreq.filename, clientcert5req.filename, false);
+ TLS_TEST_REG(goodclient6, false,
+ cacertreq.filename, clientcert6req.filename, false);
+ TLS_TEST_REG(goodclient7, false,
+ cacertreq.filename, clientcert7req.filename, false);
+
+ /* Bad clients */
+
+ /* usage:cert-sign:critical */
+ TLS_CERT_REQ(clientcert8req, cacertreq,
+ "UK", "qemu", NULL, NULL, NULL, NULL,
+ true, true, false,
+ true, true, GNUTLS_KEY_KEY_CERT_SIGN,
+ false, false, NULL, NULL,
+ 0, 0);
+ /* purpose:client:critical */
+ TLS_CERT_REQ(clientcert9req, cacertreq,
+ "UK", "qemu", NULL, NULL, NULL, NULL,
+ true, true, false,
+ false, false, 0,
+ true, true, GNUTLS_KP_TLS_WWW_SERVER, NULL,
+ 0, 0);
+ /* usage: none:critical */
+ TLS_CERT_REQ(clientcert10req, cacertreq,
+ "UK", "qemu", NULL, NULL, NULL, NULL,
+ true, true, false,
+ true, true, 0,
+ false, false, NULL, NULL,
+ 0, 0);
+
+ TLS_TEST_REG(badclient1, false,
+ cacertreq.filename, clientcert8req.filename, true);
+ TLS_TEST_REG(badclient2, false,
+ cacertreq.filename, clientcert9req.filename, true);
+ TLS_TEST_REG(badclient3, false,
+ cacertreq.filename, clientcert10req.filename, true);
+
+
+
+ /* Expired stuff */
+
+ TLS_ROOT_REQ(cacertexpreq,
+ "UK", "qemu", NULL, NULL, NULL, NULL,
+ true, true, true,
+ true, true, GNUTLS_KEY_KEY_CERT_SIGN,
+ false, false, NULL, NULL,
+ 0, -1);
+ TLS_CERT_REQ(servercertexpreq, cacertexpreq,
+ "UK", "qemu.org", NULL, NULL, NULL, NULL,
+ true, true, false,
+ true, true,
+ GNUTLS_KEY_DIGITAL_SIGNATURE | GNUTLS_KEY_KEY_ENCIPHERMENT,
+ true, true, GNUTLS_KP_TLS_WWW_SERVER, NULL,
+ 0, 0);
+ TLS_CERT_REQ(servercertexp1req, cacertreq,
+ "UK", "qemu", NULL, NULL, NULL, NULL,
+ true, true, false,
+ true, true,
+ GNUTLS_KEY_DIGITAL_SIGNATURE | GNUTLS_KEY_KEY_ENCIPHERMENT,
+ true, true, GNUTLS_KP_TLS_WWW_SERVER, NULL,
+ 0, -1);
+ TLS_CERT_REQ(clientcertexp1req, cacertreq,
+ "UK", "qemu", NULL, NULL, NULL, NULL,
+ true, true, false,
+ true, true,
+ GNUTLS_KEY_DIGITAL_SIGNATURE | GNUTLS_KEY_KEY_ENCIPHERMENT,
+ true, true, GNUTLS_KP_TLS_WWW_CLIENT, NULL,
+ 0, -1);
+
+ TLS_TEST_REG(expired1, true,
+ cacertexpreq.filename, servercertexpreq.filename, true);
+ TLS_TEST_REG(expired2, true,
+ cacertreq.filename, servercertexp1req.filename, true);
+ TLS_TEST_REG(expired3, false,
+ cacertreq.filename, clientcertexp1req.filename, true);
+
+
+ /* Not activated stuff */
+
+ TLS_ROOT_REQ(cacertnewreq,
+ "UK", "qemu", NULL, NULL, NULL, NULL,
+ true, true, true,
+ true, true, GNUTLS_KEY_KEY_CERT_SIGN,
+ false, false, NULL, NULL,
+ 1, 2);
+ TLS_CERT_REQ(servercertnewreq, cacertnewreq,
+ "UK", "qemu", NULL, NULL, NULL, NULL,
+ true, true, false,
+ true, true,
+ GNUTLS_KEY_DIGITAL_SIGNATURE | GNUTLS_KEY_KEY_ENCIPHERMENT,
+ true, true, GNUTLS_KP_TLS_WWW_SERVER, NULL,
+ 0, 0);
+ TLS_CERT_REQ(servercertnew1req, cacertreq,
+ "UK", "qemu", NULL, NULL, NULL, NULL,
+ true, true, false,
+ true, true,
+ GNUTLS_KEY_DIGITAL_SIGNATURE | GNUTLS_KEY_KEY_ENCIPHERMENT,
+ true, true, GNUTLS_KP_TLS_WWW_SERVER, NULL,
+ 1, 2);
+ TLS_CERT_REQ(clientcertnew1req, cacertreq,
+ "UK", "qemu", NULL, NULL, NULL, NULL,
+ true, true, false,
+ true, true,
+ GNUTLS_KEY_DIGITAL_SIGNATURE | GNUTLS_KEY_KEY_ENCIPHERMENT,
+ true, true, GNUTLS_KP_TLS_WWW_CLIENT, NULL,
+ 1, 2);
+
+ TLS_TEST_REG(inactive1, true,
+ cacertnewreq.filename, servercertnewreq.filename, true);
+ TLS_TEST_REG(inactive2, true,
+ cacertreq.filename, servercertnew1req.filename, true);
+ TLS_TEST_REG(inactive3, false,
+ cacertreq.filename, clientcertnew1req.filename, true);
+
+ TLS_ROOT_REQ(cacertrootreq,
+ "UK", "qemu root", NULL, NULL, NULL, NULL,
+ true, true, true,
+ true, true, GNUTLS_KEY_KEY_CERT_SIGN,
+ false, false, NULL, NULL,
+ 0, 0);
+ TLS_CERT_REQ(cacertlevel1areq, cacertrootreq,
+ "UK", "qemu level 1a", NULL, NULL, NULL, NULL,
+ true, true, true,
+ true, true, GNUTLS_KEY_KEY_CERT_SIGN,
+ false, false, NULL, NULL,
+ 0, 0);
+ TLS_CERT_REQ(cacertlevel1breq, cacertrootreq,
+ "UK", "qemu level 1b", NULL, NULL, NULL, NULL,
+ true, true, true,
+ true, true, GNUTLS_KEY_KEY_CERT_SIGN,
+ false, false, NULL, NULL,
+ 0, 0);
+ TLS_CERT_REQ(cacertlevel2areq, cacertlevel1areq,
+ "UK", "qemu level 2a", NULL, NULL, NULL, NULL,
+ true, true, true,
+ true, true, GNUTLS_KEY_KEY_CERT_SIGN,
+ false, false, NULL, NULL,
+ 0, 0);
+ TLS_CERT_REQ(servercertlevel3areq, cacertlevel2areq,
+ "UK", "qemu.org", NULL, NULL, NULL, NULL,
+ true, true, false,
+ true, true,
+ GNUTLS_KEY_DIGITAL_SIGNATURE | GNUTLS_KEY_KEY_ENCIPHERMENT,
+ true, true, GNUTLS_KP_TLS_WWW_SERVER, NULL,
+ 0, 0);
+ TLS_CERT_REQ(clientcertlevel2breq, cacertlevel1breq,
+ "UK", "qemu client level 2b", NULL, NULL, NULL, NULL,
+ true, true, false,
+ true, true,
+ GNUTLS_KEY_DIGITAL_SIGNATURE | GNUTLS_KEY_KEY_ENCIPHERMENT,
+ true, true, GNUTLS_KP_TLS_WWW_CLIENT, NULL,
+ 0, 0);
+
+ gnutls_x509_crt_t certchain[] = {
+ cacertrootreq.crt,
+ cacertlevel1areq.crt,
+ cacertlevel1breq.crt,
+ cacertlevel2areq.crt,
+ };
+
+ test_tls_write_cert_chain(WORKDIR "cacertchain-ctx.pem",
+ certchain,
+ G_N_ELEMENTS(certchain));
+
+ TLS_TEST_REG(chain1, true,
+ WORKDIR "cacertchain-ctx.pem",
+ servercertlevel3areq.filename, false);
+ TLS_TEST_REG(chain2, false,
+ WORKDIR "cacertchain-ctx.pem",
+ clientcertlevel2breq.filename, false);
+
+ /* Some missing certs - first two are fatal, the last
+ * is ok
+ */
+ TLS_TEST_REG(missingca, true,
+ "cacertdoesnotexist.pem",
+ servercert1req.filename, true);
+ TLS_TEST_REG(missingserver, true,
+ cacert1req.filename,
+ "servercertdoesnotexist.pem", true);
+ TLS_TEST_REG(missingclient, false,
+ cacert1req.filename,
+ "clientcertdoesnotexist.pem", false);
+
+ ret = g_test_run();
+
+ test_tls_discard_cert(&cacertreq);
+ test_tls_discard_cert(&cacert1req);
+ test_tls_discard_cert(&cacert2req);
+ test_tls_discard_cert(&cacert3req);
+ test_tls_discard_cert(&cacert4req);
+ test_tls_discard_cert(&cacert5req);
+ test_tls_discard_cert(&cacert6req);
+
+ test_tls_discard_cert(&servercertreq);
+ test_tls_discard_cert(&servercert1req);
+ test_tls_discard_cert(&servercert2req);
+ test_tls_discard_cert(&servercert3req);
+ test_tls_discard_cert(&servercert4req);
+ test_tls_discard_cert(&servercert5req);
+ test_tls_discard_cert(&servercert6req);
+ test_tls_discard_cert(&servercert7req);
+ test_tls_discard_cert(&servercert8req);
+ test_tls_discard_cert(&servercert9req);
+ test_tls_discard_cert(&servercert10req);
+ test_tls_discard_cert(&servercert11req);
+ test_tls_discard_cert(&servercert12req);
+ test_tls_discard_cert(&servercert13req);
+ test_tls_discard_cert(&servercert14req);
+ test_tls_discard_cert(&servercert15req);
+ test_tls_discard_cert(&servercert16req);
+
+ test_tls_discard_cert(&clientcertreq);
+ test_tls_discard_cert(&clientcert1req);
+ test_tls_discard_cert(&clientcert2req);
+ test_tls_discard_cert(&clientcert3req);
+ test_tls_discard_cert(&clientcert4req);
+ test_tls_discard_cert(&clientcert5req);
+ test_tls_discard_cert(&clientcert6req);
+ test_tls_discard_cert(&clientcert7req);
+ test_tls_discard_cert(&clientcert8req);
+ test_tls_discard_cert(&clientcert9req);
+ test_tls_discard_cert(&clientcert10req);
+
+ test_tls_discard_cert(&cacertexpreq);
+ test_tls_discard_cert(&servercertexpreq);
+ test_tls_discard_cert(&servercertexp1req);
+ test_tls_discard_cert(&clientcertexp1req);
+
+ test_tls_discard_cert(&cacertnewreq);
+ test_tls_discard_cert(&servercertnewreq);
+ test_tls_discard_cert(&servercertnew1req);
+ test_tls_discard_cert(&clientcertnew1req);
+
+ test_tls_discard_cert(&cacertrootreq);
+ test_tls_discard_cert(&cacertlevel1areq);
+ test_tls_discard_cert(&cacertlevel1breq);
+ test_tls_discard_cert(&cacertlevel2areq);
+ test_tls_discard_cert(&servercertlevel3areq);
+ test_tls_discard_cert(&clientcertlevel2breq);
+ unlink(WORKDIR "cacertchain-ctx.pem");
+
+ test_tls_cleanup(KEYFILE);
+ rmdir(WORKDIR);
+
+ return ret == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
+}
+
+#else /* ! QCRYPTO_HAVE_TLS_TEST_SUPPORT */
+
+int
+main(void)
+{
+ return EXIT_SUCCESS;
+}
+
+#endif /* ! QCRYPTO_HAVE_TLS_TEST_SUPPORT */
diff --git a/tests/test-crypto-tlssession.c b/tests/test-crypto-tlssession.c
new file mode 100644
index 000000000..4524128fc
--- /dev/null
+++ b/tests/test-crypto-tlssession.c
@@ -0,0 +1,535 @@
+/*
+ * Copyright (C) 2015 Red Hat, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library. If not, see
+ * <http://www.gnu.org/licenses/>.
+ *
+ * Author: Daniel P. Berrange <berrange@redhat.com>
+ */
+
+#include <stdlib.h>
+#include <fcntl.h>
+
+#include "config-host.h"
+#include "crypto-tls-x509-helpers.h"
+#include "crypto/tlscredsx509.h"
+#include "crypto/tlssession.h"
+#include "qom/object_interfaces.h"
+#include "qemu/sockets.h"
+#include "qemu/acl.h"
+
+#ifdef QCRYPTO_HAVE_TLS_TEST_SUPPORT
+
+#define WORKDIR "tests/test-crypto-tlssession-work/"
+#define KEYFILE WORKDIR "key-ctx.pem"
+
+struct QCryptoTLSSessionTestData {
+ const char *servercacrt;
+ const char *clientcacrt;
+ const char *servercrt;
+ const char *clientcrt;
+ bool expectServerFail;
+ bool expectClientFail;
+ const char *hostname;
+ const char *const *wildcards;
+};
+
+
+static ssize_t testWrite(const char *buf, size_t len, void *opaque)
+{
+ int *fd = opaque;
+
+ return write(*fd, buf, len);
+}
+
+static ssize_t testRead(char *buf, size_t len, void *opaque)
+{
+ int *fd = opaque;
+
+ return read(*fd, buf, len);
+}
+
+static QCryptoTLSCreds *test_tls_creds_create(QCryptoTLSCredsEndpoint endpoint,
+ const char *certdir,
+ Error **errp)
+{
+ Error *err = NULL;
+ Object *parent = object_get_objects_root();
+ Object *creds = object_new_with_props(
+ TYPE_QCRYPTO_TLS_CREDS_X509,
+ parent,
+ (endpoint == QCRYPTO_TLS_CREDS_ENDPOINT_SERVER ?
+ "testtlscredsserver" : "testtlscredsclient"),
+ &err,
+ "endpoint", (endpoint == QCRYPTO_TLS_CREDS_ENDPOINT_SERVER ?
+ "server" : "client"),
+ "dir", certdir,
+ "verify-peer", "yes",
+ /* We skip initial sanity checks here because we
+ * want to make sure that problems are being
+ * detected at the TLS session validation stage,
+ * and the test-crypto-tlscreds test already
+ * validate the sanity check code.
+ */
+ "sanity-check", "no",
+ NULL
+ );
+
+ if (err) {
+ error_propagate(errp, err);
+ return NULL;
+ }
+ return QCRYPTO_TLS_CREDS(creds);
+}
+
+
+/*
+ * This tests validation checking of peer certificates
+ *
+ * This is replicating the checks that are done for an
+ * active TLS session after handshake completes. To
+ * simulate that we create our TLS contexts, skipping
+ * sanity checks. We then get a socketpair, and
+ * initiate a TLS session across them. Finally do
+ * do actual cert validation tests
+ */
+static void test_crypto_tls_session(const void *opaque)
+{
+ struct QCryptoTLSSessionTestData *data =
+ (struct QCryptoTLSSessionTestData *)opaque;
+ QCryptoTLSCreds *clientCreds;
+ QCryptoTLSCreds *serverCreds;
+ QCryptoTLSSession *clientSess = NULL;
+ QCryptoTLSSession *serverSess = NULL;
+ qemu_acl *acl;
+ const char * const *wildcards;
+ int channel[2];
+ bool clientShake = false;
+ bool serverShake = false;
+ Error *err = NULL;
+ int ret;
+
+ /* We'll use this for our fake client-server connection */
+ ret = socketpair(AF_UNIX, SOCK_STREAM, 0, channel);
+ g_assert(ret == 0);
+
+ /*
+ * We have an evil loop to do the handshake in a single
+ * thread, so we need these non-blocking to avoid deadlock
+ * of ourselves
+ */
+ qemu_set_nonblock(channel[0]);
+ qemu_set_nonblock(channel[1]);
+
+#define CLIENT_CERT_DIR "tests/test-crypto-tlssession-client/"
+#define SERVER_CERT_DIR "tests/test-crypto-tlssession-server/"
+ mkdir(CLIENT_CERT_DIR, 0700);
+ mkdir(SERVER_CERT_DIR, 0700);
+
+ unlink(SERVER_CERT_DIR QCRYPTO_TLS_CREDS_X509_CA_CERT);
+ unlink(SERVER_CERT_DIR QCRYPTO_TLS_CREDS_X509_SERVER_CERT);
+ unlink(SERVER_CERT_DIR QCRYPTO_TLS_CREDS_X509_SERVER_KEY);
+
+ unlink(CLIENT_CERT_DIR QCRYPTO_TLS_CREDS_X509_CA_CERT);
+ unlink(CLIENT_CERT_DIR QCRYPTO_TLS_CREDS_X509_CLIENT_CERT);
+ unlink(CLIENT_CERT_DIR QCRYPTO_TLS_CREDS_X509_CLIENT_KEY);
+
+ g_assert(link(data->servercacrt,
+ SERVER_CERT_DIR QCRYPTO_TLS_CREDS_X509_CA_CERT) == 0);
+ g_assert(link(data->servercrt,
+ SERVER_CERT_DIR QCRYPTO_TLS_CREDS_X509_SERVER_CERT) == 0);
+ g_assert(link(KEYFILE,
+ SERVER_CERT_DIR QCRYPTO_TLS_CREDS_X509_SERVER_KEY) == 0);
+
+ g_assert(link(data->clientcacrt,
+ CLIENT_CERT_DIR QCRYPTO_TLS_CREDS_X509_CA_CERT) == 0);
+ g_assert(link(data->clientcrt,
+ CLIENT_CERT_DIR QCRYPTO_TLS_CREDS_X509_CLIENT_CERT) == 0);
+ g_assert(link(KEYFILE,
+ CLIENT_CERT_DIR QCRYPTO_TLS_CREDS_X509_CLIENT_KEY) == 0);
+
+ clientCreds = test_tls_creds_create(
+ QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT,
+ CLIENT_CERT_DIR,
+ &err);
+ g_assert(clientCreds != NULL);
+
+ serverCreds = test_tls_creds_create(
+ QCRYPTO_TLS_CREDS_ENDPOINT_SERVER,
+ SERVER_CERT_DIR,
+ &err);
+ g_assert(serverCreds != NULL);
+
+ acl = qemu_acl_init("tlssessionacl");
+ qemu_acl_reset(acl);
+ wildcards = data->wildcards;
+ while (wildcards && *wildcards) {
+ qemu_acl_append(acl, 0, *wildcards);
+ wildcards++;
+ }
+
+ /* Now the real part of the test, setup the sessions */
+ clientSess = qcrypto_tls_session_new(
+ clientCreds, data->hostname, NULL,
+ QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT, &err);
+ serverSess = qcrypto_tls_session_new(
+ serverCreds, NULL,
+ data->wildcards ? "tlssessionacl" : NULL,
+ QCRYPTO_TLS_CREDS_ENDPOINT_SERVER, &err);
+
+ g_assert(clientSess != NULL);
+ g_assert(serverSess != NULL);
+
+ /* For handshake to work, we need to set the I/O callbacks
+ * to read/write over the socketpair
+ */
+ qcrypto_tls_session_set_callbacks(serverSess,
+ testWrite, testRead,
+ &channel[0]);
+ qcrypto_tls_session_set_callbacks(clientSess,
+ testWrite, testRead,
+ &channel[1]);
+
+ /*
+ * Finally we loop around & around doing handshake on each
+ * session until we get an error, or the handshake completes.
+ * This relies on the socketpair being nonblocking to avoid
+ * deadlocking ourselves upon handshake
+ */
+ do {
+ int rv;
+ if (!serverShake) {
+ rv = qcrypto_tls_session_handshake(serverSess,
+ &err);
+ g_assert(rv >= 0);
+ if (qcrypto_tls_session_get_handshake_status(serverSess) ==
+ QCRYPTO_TLS_HANDSHAKE_COMPLETE) {
+ serverShake = true;
+ }
+ }
+ if (!clientShake) {
+ rv = qcrypto_tls_session_handshake(clientSess,
+ &err);
+ g_assert(rv >= 0);
+ if (qcrypto_tls_session_get_handshake_status(clientSess) ==
+ QCRYPTO_TLS_HANDSHAKE_COMPLETE) {
+ clientShake = true;
+ }
+ }
+ } while (!clientShake && !serverShake);
+
+
+ /* Finally make sure the server validation does what
+ * we were expecting
+ */
+ if (qcrypto_tls_session_check_credentials(serverSess, &err) < 0) {
+ g_assert(data->expectServerFail);
+ error_free(err);
+ err = NULL;
+ } else {
+ g_assert(!data->expectServerFail);
+ }
+
+ /*
+ * And the same for the client validation check
+ */
+ if (qcrypto_tls_session_check_credentials(clientSess, &err) < 0) {
+ g_assert(data->expectClientFail);
+ error_free(err);
+ err = NULL;
+ } else {
+ g_assert(!data->expectClientFail);
+ }
+
+ unlink(SERVER_CERT_DIR QCRYPTO_TLS_CREDS_X509_CA_CERT);
+ unlink(SERVER_CERT_DIR QCRYPTO_TLS_CREDS_X509_SERVER_CERT);
+ unlink(SERVER_CERT_DIR QCRYPTO_TLS_CREDS_X509_SERVER_KEY);
+
+ unlink(CLIENT_CERT_DIR QCRYPTO_TLS_CREDS_X509_CA_CERT);
+ unlink(CLIENT_CERT_DIR QCRYPTO_TLS_CREDS_X509_CLIENT_CERT);
+ unlink(CLIENT_CERT_DIR QCRYPTO_TLS_CREDS_X509_CLIENT_KEY);
+
+ rmdir(CLIENT_CERT_DIR);
+ rmdir(SERVER_CERT_DIR);
+
+ object_unparent(OBJECT(serverCreds));
+ object_unparent(OBJECT(clientCreds));
+
+ qcrypto_tls_session_free(serverSess);
+ qcrypto_tls_session_free(clientSess);
+
+ close(channel[0]);
+ close(channel[1]);
+}
+
+
+int main(int argc, char **argv)
+{
+ int ret;
+
+ module_call_init(MODULE_INIT_QOM);
+ g_test_init(&argc, &argv, NULL);
+ setenv("GNUTLS_FORCE_FIPS_MODE", "2", 1);
+
+ mkdir(WORKDIR, 0700);
+
+ test_tls_init(KEYFILE);
+
+# define TEST_SESS_REG(name, caCrt, \
+ serverCrt, clientCrt, \
+ expectServerFail, expectClientFail, \
+ hostname, wildcards) \
+ struct QCryptoTLSSessionTestData name = { \
+ caCrt, caCrt, serverCrt, clientCrt, \
+ expectServerFail, expectClientFail, \
+ hostname, wildcards \
+ }; \
+ g_test_add_data_func("/qcrypto/tlssession/" # name, \
+ &name, test_crypto_tls_session); \
+
+
+# define TEST_SESS_REG_EXT(name, serverCaCrt, clientCaCrt, \
+ serverCrt, clientCrt, \
+ expectServerFail, expectClientFail, \
+ hostname, wildcards) \
+ struct QCryptoTLSSessionTestData name = { \
+ serverCaCrt, clientCaCrt, serverCrt, clientCrt, \
+ expectServerFail, expectClientFail, \
+ hostname, wildcards \
+ }; \
+ g_test_add_data_func("/qcrypto/tlssession/" # name, \
+ &name, test_crypto_tls_session); \
+
+ /* A perfect CA, perfect client & perfect server */
+
+ /* Basic:CA:critical */
+ TLS_ROOT_REQ(cacertreq,
+ "UK", "qemu CA", NULL, NULL, NULL, NULL,
+ true, true, true,
+ true, true, GNUTLS_KEY_KEY_CERT_SIGN,
+ false, false, NULL, NULL,
+ 0, 0);
+
+ TLS_ROOT_REQ(altcacertreq,
+ "UK", "qemu CA 1", NULL, NULL, NULL, NULL,
+ true, true, true,
+ false, false, 0,
+ false, false, NULL, NULL,
+ 0, 0);
+
+ TLS_CERT_REQ(servercertreq, cacertreq,
+ "UK", "qemu.org", NULL, NULL, NULL, NULL,
+ true, true, false,
+ true, true,
+ GNUTLS_KEY_DIGITAL_SIGNATURE | GNUTLS_KEY_KEY_ENCIPHERMENT,
+ true, true, GNUTLS_KP_TLS_WWW_SERVER, NULL,
+ 0, 0);
+ TLS_CERT_REQ(clientcertreq, cacertreq,
+ "UK", "qemu", NULL, NULL, NULL, NULL,
+ true, true, false,
+ true, true,
+ GNUTLS_KEY_DIGITAL_SIGNATURE | GNUTLS_KEY_KEY_ENCIPHERMENT,
+ true, true, GNUTLS_KP_TLS_WWW_CLIENT, NULL,
+ 0, 0);
+
+ TLS_CERT_REQ(clientcertaltreq, altcacertreq,
+ "UK", "qemu", NULL, NULL, NULL, NULL,
+ true, true, false,
+ true, true,
+ GNUTLS_KEY_DIGITAL_SIGNATURE | GNUTLS_KEY_KEY_ENCIPHERMENT,
+ true, true, GNUTLS_KP_TLS_WWW_CLIENT, NULL,
+ 0, 0);
+
+ TEST_SESS_REG(basicca, cacertreq.filename,
+ servercertreq.filename, clientcertreq.filename,
+ false, false, "qemu.org", NULL);
+ TEST_SESS_REG_EXT(differentca, cacertreq.filename,
+ altcacertreq.filename, servercertreq.filename,
+ clientcertaltreq.filename, true, true, "qemu.org", NULL);
+
+
+ /* When an altname is set, the CN is ignored, so it must be duplicated
+ * as an altname for it to match */
+ TLS_CERT_REQ(servercertalt1req, cacertreq,
+ "UK", "qemu.org", "www.qemu.org", "qemu.org",
+ "192.168.122.1", "fec0::dead:beaf",
+ true, true, false,
+ true, true,
+ GNUTLS_KEY_DIGITAL_SIGNATURE | GNUTLS_KEY_KEY_ENCIPHERMENT,
+ true, true, GNUTLS_KP_TLS_WWW_SERVER, NULL,
+ 0, 0);
+ /* This intentionally doesn't replicate */
+ TLS_CERT_REQ(servercertalt2req, cacertreq,
+ "UK", "qemu.org", "www.qemu.org", "wiki.qemu.org",
+ "192.168.122.1", "fec0::dead:beaf",
+ true, true, false,
+ true, true,
+ GNUTLS_KEY_DIGITAL_SIGNATURE | GNUTLS_KEY_KEY_ENCIPHERMENT,
+ true, true, GNUTLS_KP_TLS_WWW_SERVER, NULL,
+ 0, 0);
+
+ TEST_SESS_REG(altname1, cacertreq.filename,
+ servercertalt1req.filename, clientcertreq.filename,
+ false, false, "qemu.org", NULL);
+ TEST_SESS_REG(altname2, cacertreq.filename,
+ servercertalt1req.filename, clientcertreq.filename,
+ false, false, "www.qemu.org", NULL);
+ TEST_SESS_REG(altname3, cacertreq.filename,
+ servercertalt1req.filename, clientcertreq.filename,
+ false, true, "wiki.qemu.org", NULL);
+
+ TEST_SESS_REG(altname4, cacertreq.filename,
+ servercertalt2req.filename, clientcertreq.filename,
+ false, true, "qemu.org", NULL);
+ TEST_SESS_REG(altname5, cacertreq.filename,
+ servercertalt2req.filename, clientcertreq.filename,
+ false, false, "www.qemu.org", NULL);
+ TEST_SESS_REG(altname6, cacertreq.filename,
+ servercertalt2req.filename, clientcertreq.filename,
+ false, false, "wiki.qemu.org", NULL);
+
+ const char *const wildcards1[] = {
+ "C=UK,CN=dogfood",
+ NULL,
+ };
+ const char *const wildcards2[] = {
+ "C=UK,CN=qemu",
+ NULL,
+ };
+ const char *const wildcards3[] = {
+ "C=UK,CN=dogfood",
+ "C=UK,CN=qemu",
+ NULL,
+ };
+ const char *const wildcards4[] = {
+ "C=UK,CN=qemustuff",
+ NULL,
+ };
+ const char *const wildcards5[] = {
+ "C=UK,CN=qemu*",
+ NULL,
+ };
+ const char *const wildcards6[] = {
+ "C=UK,CN=*emu*",
+ NULL,
+ };
+
+ TEST_SESS_REG(wildcard1, cacertreq.filename,
+ servercertreq.filename, clientcertreq.filename,
+ true, false, "qemu.org", wildcards1);
+ TEST_SESS_REG(wildcard2, cacertreq.filename,
+ servercertreq.filename, clientcertreq.filename,
+ false, false, "qemu.org", wildcards2);
+ TEST_SESS_REG(wildcard3, cacertreq.filename,
+ servercertreq.filename, clientcertreq.filename,
+ false, false, "qemu.org", wildcards3);
+ TEST_SESS_REG(wildcard4, cacertreq.filename,
+ servercertreq.filename, clientcertreq.filename,
+ true, false, "qemu.org", wildcards4);
+ TEST_SESS_REG(wildcard5, cacertreq.filename,
+ servercertreq.filename, clientcertreq.filename,
+ false, false, "qemu.org", wildcards5);
+ TEST_SESS_REG(wildcard6, cacertreq.filename,
+ servercertreq.filename, clientcertreq.filename,
+ false, false, "qemu.org", wildcards6);
+
+ TLS_ROOT_REQ(cacertrootreq,
+ "UK", "qemu root", NULL, NULL, NULL, NULL,
+ true, true, true,
+ true, true, GNUTLS_KEY_KEY_CERT_SIGN,
+ false, false, NULL, NULL,
+ 0, 0);
+ TLS_CERT_REQ(cacertlevel1areq, cacertrootreq,
+ "UK", "qemu level 1a", NULL, NULL, NULL, NULL,
+ true, true, true,
+ true, true, GNUTLS_KEY_KEY_CERT_SIGN,
+ false, false, NULL, NULL,
+ 0, 0);
+ TLS_CERT_REQ(cacertlevel1breq, cacertrootreq,
+ "UK", "qemu level 1b", NULL, NULL, NULL, NULL,
+ true, true, true,
+ true, true, GNUTLS_KEY_KEY_CERT_SIGN,
+ false, false, NULL, NULL,
+ 0, 0);
+ TLS_CERT_REQ(cacertlevel2areq, cacertlevel1areq,
+ "UK", "qemu level 2a", NULL, NULL, NULL, NULL,
+ true, true, true,
+ true, true, GNUTLS_KEY_KEY_CERT_SIGN,
+ false, false, NULL, NULL,
+ 0, 0);
+ TLS_CERT_REQ(servercertlevel3areq, cacertlevel2areq,
+ "UK", "qemu.org", NULL, NULL, NULL, NULL,
+ true, true, false,
+ true, true,
+ GNUTLS_KEY_DIGITAL_SIGNATURE | GNUTLS_KEY_KEY_ENCIPHERMENT,
+ true, true, GNUTLS_KP_TLS_WWW_SERVER, NULL,
+ 0, 0);
+ TLS_CERT_REQ(clientcertlevel2breq, cacertlevel1breq,
+ "UK", "qemu client level 2b", NULL, NULL, NULL, NULL,
+ true, true, false,
+ true, true,
+ GNUTLS_KEY_DIGITAL_SIGNATURE | GNUTLS_KEY_KEY_ENCIPHERMENT,
+ true, true, GNUTLS_KP_TLS_WWW_CLIENT, NULL,
+ 0, 0);
+
+ gnutls_x509_crt_t certchain[] = {
+ cacertrootreq.crt,
+ cacertlevel1areq.crt,
+ cacertlevel1breq.crt,
+ cacertlevel2areq.crt,
+ };
+
+ test_tls_write_cert_chain(WORKDIR "cacertchain-sess.pem",
+ certchain,
+ G_N_ELEMENTS(certchain));
+
+ TEST_SESS_REG(cachain, WORKDIR "cacertchain-sess.pem",
+ servercertlevel3areq.filename, clientcertlevel2breq.filename,
+ false, false, "qemu.org", NULL);
+
+ ret = g_test_run();
+
+ test_tls_discard_cert(&clientcertreq);
+ test_tls_discard_cert(&clientcertaltreq);
+
+ test_tls_discard_cert(&servercertreq);
+ test_tls_discard_cert(&servercertalt1req);
+ test_tls_discard_cert(&servercertalt2req);
+
+ test_tls_discard_cert(&cacertreq);
+ test_tls_discard_cert(&altcacertreq);
+
+ test_tls_discard_cert(&cacertrootreq);
+ test_tls_discard_cert(&cacertlevel1areq);
+ test_tls_discard_cert(&cacertlevel1breq);
+ test_tls_discard_cert(&cacertlevel2areq);
+ test_tls_discard_cert(&servercertlevel3areq);
+ test_tls_discard_cert(&clientcertlevel2breq);
+ unlink(WORKDIR "cacertchain-sess.pem");
+
+ test_tls_cleanup(KEYFILE);
+ rmdir(WORKDIR);
+
+ return ret == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
+}
+
+#else /* ! QCRYPTO_HAVE_TLS_TEST_SUPPORT */
+
+int
+main(void)
+{
+ return EXIT_SUCCESS;
+}
+
+#endif /* ! QCRYPTO_HAVE_TLS_TEST_SUPPORT */
diff --git a/tests/test-cutils.c b/tests/test-cutils.c
index 2a4556d3a..a3de6ab87 100644
--- a/tests/test-cutils.c
+++ b/tests/test-cutils.c
@@ -226,6 +226,1212 @@ static void test_parse_uint_full_correct(void)
g_assert_cmpint(i, ==, 123);
}
+static void test_qemu_strtol_correct(void)
+{
+ const char *str = "12345 foo";
+ char f = 'X';
+ const char *endptr = &f;
+ long res = 999;
+ int err;
+
+ err = qemu_strtol(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, 12345);
+ g_assert(endptr == str + 5);
+}
+
+static void test_qemu_strtol_null(void)
+{
+ char f = 'X';
+ const char *endptr = &f;
+ long res = 999;
+ int err;
+
+ err = qemu_strtol(NULL, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, -EINVAL);
+ g_assert(endptr == NULL);
+}
+
+static void test_qemu_strtol_empty(void)
+{
+ const char *str = "";
+ char f = 'X';
+ const char *endptr = &f;
+ long res = 999;
+ int err;
+
+ err = qemu_strtol(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, -EINVAL);
+}
+
+static void test_qemu_strtol_whitespace(void)
+{
+ const char *str = " \t ";
+ char f = 'X';
+ const char *endptr = &f;
+ long res = 999;
+ int err;
+
+ err = qemu_strtol(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, -EINVAL);
+}
+
+static void test_qemu_strtol_invalid(void)
+{
+ const char *str = " xxxx \t abc";
+ char f = 'X';
+ const char *endptr = &f;
+ long res = 999;
+ int err;
+
+ err = qemu_strtol(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, -EINVAL);
+}
+
+static void test_qemu_strtol_trailing(void)
+{
+ const char *str = "123xxx";
+ char f = 'X';
+ const char *endptr = &f;
+ long res = 999;
+ int err;
+
+ err = qemu_strtol(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, 123);
+ g_assert(endptr == str + 3);
+}
+
+static void test_qemu_strtol_octal(void)
+{
+ const char *str = "0123";
+ char f = 'X';
+ const char *endptr = &f;
+ long res = 999;
+ int err;
+
+ err = qemu_strtol(str, &endptr, 8, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, 0123);
+ g_assert(endptr == str + strlen(str));
+
+ res = 999;
+ endptr = &f;
+ err = qemu_strtol(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, 0123);
+ g_assert(endptr == str + strlen(str));
+}
+
+static void test_qemu_strtol_decimal(void)
+{
+ const char *str = "0123";
+ char f = 'X';
+ const char *endptr = &f;
+ long res = 999;
+ int err;
+
+ err = qemu_strtol(str, &endptr, 10, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, 123);
+ g_assert(endptr == str + strlen(str));
+
+ str = "123";
+ res = 999;
+ endptr = &f;
+ err = qemu_strtol(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, 123);
+ g_assert(endptr == str + strlen(str));
+}
+
+static void test_qemu_strtol_hex(void)
+{
+ const char *str = "0123";
+ char f = 'X';
+ const char *endptr = &f;
+ long res = 999;
+ int err;
+
+ err = qemu_strtol(str, &endptr, 16, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, 0x123);
+ g_assert(endptr == str + strlen(str));
+
+ str = "0x123";
+ res = 999;
+ endptr = &f;
+ err = qemu_strtol(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, 0x123);
+ g_assert(endptr == str + strlen(str));
+}
+
+static void test_qemu_strtol_max(void)
+{
+ const char *str = g_strdup_printf("%ld", LONG_MAX);
+ char f = 'X';
+ const char *endptr = &f;
+ long res = 999;
+ int err;
+
+ err = qemu_strtol(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, LONG_MAX);
+ g_assert(endptr == str + strlen(str));
+}
+
+static void test_qemu_strtol_overflow(void)
+{
+ const char *str = "99999999999999999999999999999999999999999999";
+ char f = 'X';
+ const char *endptr = &f;
+ long res = 999;
+ int err;
+
+ err = qemu_strtol(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, -ERANGE);
+ g_assert_cmpint(res, ==, LONG_MAX);
+ g_assert(endptr == str + strlen(str));
+}
+
+static void test_qemu_strtol_underflow(void)
+{
+ const char *str = "-99999999999999999999999999999999999999999999";
+ char f = 'X';
+ const char *endptr = &f;
+ long res = 999;
+ int err;
+
+ err = qemu_strtol(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, -ERANGE);
+ g_assert_cmpint(res, ==, LONG_MIN);
+ g_assert(endptr == str + strlen(str));
+}
+
+static void test_qemu_strtol_negative(void)
+{
+ const char *str = " \t -321";
+ char f = 'X';
+ const char *endptr = &f;
+ long res = 999;
+ int err;
+
+ err = qemu_strtol(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, -321);
+ g_assert(endptr == str + strlen(str));
+}
+
+static void test_qemu_strtol_full_correct(void)
+{
+ const char *str = "123";
+ long res = 999;
+ int err;
+
+ err = qemu_strtol(str, NULL, 0, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, 123);
+}
+
+static void test_qemu_strtol_full_null(void)
+{
+ char f = 'X';
+ const char *endptr = &f;
+ long res = 999;
+ int err;
+
+ err = qemu_strtol(NULL, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, -EINVAL);
+ g_assert(endptr == NULL);
+}
+
+static void test_qemu_strtol_full_empty(void)
+{
+ const char *str = "";
+ long res = 999L;
+ int err;
+
+ err = qemu_strtol(str, NULL, 0, &res);
+
+ g_assert_cmpint(err, ==, -EINVAL);
+}
+
+static void test_qemu_strtol_full_negative(void)
+{
+ const char *str = " \t -321";
+ long res = 999;
+ int err;
+
+ err = qemu_strtol(str, NULL, 0, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, -321);
+}
+
+static void test_qemu_strtol_full_trailing(void)
+{
+ const char *str = "123xxx";
+ long res;
+ int err;
+
+ err = qemu_strtol(str, NULL, 0, &res);
+
+ g_assert_cmpint(err, ==, -EINVAL);
+}
+
+static void test_qemu_strtol_full_max(void)
+{
+ const char *str = g_strdup_printf("%ld", LONG_MAX);
+ long res;
+ int err;
+
+ err = qemu_strtol(str, NULL, 0, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, LONG_MAX);
+}
+
+static void test_qemu_strtoul_correct(void)
+{
+ const char *str = "12345 foo";
+ char f = 'X';
+ const char *endptr = &f;
+ unsigned long res = 999;
+ int err;
+
+ err = qemu_strtoul(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, 12345);
+ g_assert(endptr == str + 5);
+}
+
+static void test_qemu_strtoul_null(void)
+{
+ char f = 'X';
+ const char *endptr = &f;
+ unsigned long res = 999;
+ int err;
+
+ err = qemu_strtoul(NULL, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, -EINVAL);
+ g_assert(endptr == NULL);
+}
+
+static void test_qemu_strtoul_empty(void)
+{
+ const char *str = "";
+ char f = 'X';
+ const char *endptr = &f;
+ unsigned long res = 999;
+ int err;
+
+ err = qemu_strtoul(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, -EINVAL);
+}
+
+static void test_qemu_strtoul_whitespace(void)
+{
+ const char *str = " \t ";
+ char f = 'X';
+ const char *endptr = &f;
+ unsigned long res = 999;
+ int err;
+
+ err = qemu_strtoul(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, -EINVAL);
+}
+
+static void test_qemu_strtoul_invalid(void)
+{
+ const char *str = " xxxx \t abc";
+ char f = 'X';
+ const char *endptr = &f;
+ unsigned long res = 999;
+ int err;
+
+ err = qemu_strtoul(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, -EINVAL);
+}
+
+static void test_qemu_strtoul_trailing(void)
+{
+ const char *str = "123xxx";
+ char f = 'X';
+ const char *endptr = &f;
+ unsigned long res = 999;
+ int err;
+
+ err = qemu_strtoul(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, 123);
+ g_assert(endptr == str + 3);
+}
+
+static void test_qemu_strtoul_octal(void)
+{
+ const char *str = "0123";
+ char f = 'X';
+ const char *endptr = &f;
+ unsigned long res = 999;
+ int err;
+
+ err = qemu_strtoul(str, &endptr, 8, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, 0123);
+ g_assert(endptr == str + strlen(str));
+
+ res = 999;
+ endptr = &f;
+ err = qemu_strtoul(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, 0123);
+ g_assert(endptr == str + strlen(str));
+}
+
+static void test_qemu_strtoul_decimal(void)
+{
+ const char *str = "0123";
+ char f = 'X';
+ const char *endptr = &f;
+ unsigned long res = 999;
+ int err;
+
+ err = qemu_strtoul(str, &endptr, 10, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, 123);
+ g_assert(endptr == str + strlen(str));
+
+ str = "123";
+ res = 999;
+ endptr = &f;
+ err = qemu_strtoul(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, 123);
+ g_assert(endptr == str + strlen(str));
+}
+
+static void test_qemu_strtoul_hex(void)
+{
+ const char *str = "0123";
+ char f = 'X';
+ const char *endptr = &f;
+ unsigned long res = 999;
+ int err;
+
+ err = qemu_strtoul(str, &endptr, 16, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, 0x123);
+ g_assert(endptr == str + strlen(str));
+
+ str = "0x123";
+ res = 999;
+ endptr = &f;
+ err = qemu_strtoul(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, 0x123);
+ g_assert(endptr == str + strlen(str));
+}
+
+static void test_qemu_strtoul_max(void)
+{
+ const char *str = g_strdup_printf("%lu", ULONG_MAX);
+ char f = 'X';
+ const char *endptr = &f;
+ unsigned long res = 999;
+ int err;
+
+ err = qemu_strtoul(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, ULONG_MAX);
+ g_assert(endptr == str + strlen(str));
+}
+
+static void test_qemu_strtoul_overflow(void)
+{
+ const char *str = "99999999999999999999999999999999999999999999";
+ char f = 'X';
+ const char *endptr = &f;
+ unsigned long res = 999;
+ int err;
+
+ err = qemu_strtoul(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, -ERANGE);
+ g_assert_cmpint(res, ==, ULONG_MAX);
+ g_assert(endptr == str + strlen(str));
+}
+
+static void test_qemu_strtoul_underflow(void)
+{
+ const char *str = "-99999999999999999999999999999999999999999999";
+ char f = 'X';
+ const char *endptr = &f;
+ unsigned long res = 999;
+ int err;
+
+ err = qemu_strtoul(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, -ERANGE);
+ g_assert_cmpint(res, ==, -1ul);
+ g_assert(endptr == str + strlen(str));
+}
+
+static void test_qemu_strtoul_negative(void)
+{
+ const char *str = " \t -321";
+ char f = 'X';
+ const char *endptr = &f;
+ unsigned long res = 999;
+ int err;
+
+ err = qemu_strtoul(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, -321ul);
+ g_assert(endptr == str + strlen(str));
+}
+
+static void test_qemu_strtoul_full_correct(void)
+{
+ const char *str = "123";
+ unsigned long res = 999;
+ int err;
+
+ err = qemu_strtoul(str, NULL, 0, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, 123);
+}
+
+static void test_qemu_strtoul_full_null(void)
+{
+ unsigned long res = 999;
+ int err;
+
+ err = qemu_strtoul(NULL, NULL, 0, &res);
+
+ g_assert_cmpint(err, ==, -EINVAL);
+}
+
+static void test_qemu_strtoul_full_empty(void)
+{
+ const char *str = "";
+ unsigned long res = 999;
+ int err;
+
+ err = qemu_strtoul(str, NULL, 0, &res);
+
+ g_assert_cmpint(err, ==, -EINVAL);
+}
+static void test_qemu_strtoul_full_negative(void)
+{
+ const char *str = " \t -321";
+ unsigned long res = 999;
+ int err;
+
+ err = qemu_strtoul(str, NULL, 0, &res);
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, -321ul);
+}
+
+static void test_qemu_strtoul_full_trailing(void)
+{
+ const char *str = "123xxx";
+ unsigned long res;
+ int err;
+
+ err = qemu_strtoul(str, NULL, 0, &res);
+
+ g_assert_cmpint(err, ==, -EINVAL);
+}
+
+static void test_qemu_strtoul_full_max(void)
+{
+ const char *str = g_strdup_printf("%lu", ULONG_MAX);
+ unsigned long res = 999;
+ int err;
+
+ err = qemu_strtoul(str, NULL, 0, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, ULONG_MAX);
+}
+
+static void test_qemu_strtoll_correct(void)
+{
+ const char *str = "12345 foo";
+ char f = 'X';
+ const char *endptr = &f;
+ int64_t res = 999;
+ int err;
+
+ err = qemu_strtoll(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, 12345);
+ g_assert(endptr == str + 5);
+}
+
+static void test_qemu_strtoll_null(void)
+{
+ char f = 'X';
+ const char *endptr = &f;
+ int64_t res = 999;
+ int err;
+
+ err = qemu_strtoll(NULL, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, -EINVAL);
+ g_assert(endptr == NULL);
+}
+
+static void test_qemu_strtoll_empty(void)
+{
+ const char *str = "";
+ char f = 'X';
+ const char *endptr = &f;
+ int64_t res = 999;
+ int err;
+
+ err = qemu_strtoll(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, -EINVAL);
+}
+
+static void test_qemu_strtoll_whitespace(void)
+{
+ const char *str = " \t ";
+ char f = 'X';
+ const char *endptr = &f;
+ int64_t res = 999;
+ int err;
+
+ err = qemu_strtoll(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, -EINVAL);
+}
+
+static void test_qemu_strtoll_invalid(void)
+{
+ const char *str = " xxxx \t abc";
+ char f = 'X';
+ const char *endptr = &f;
+ int64_t res = 999;
+ int err;
+
+ err = qemu_strtoll(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, -EINVAL);
+}
+
+static void test_qemu_strtoll_trailing(void)
+{
+ const char *str = "123xxx";
+ char f = 'X';
+ const char *endptr = &f;
+ int64_t res = 999;
+ int err;
+
+ err = qemu_strtoll(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, 123);
+ g_assert(endptr == str + 3);
+}
+
+static void test_qemu_strtoll_octal(void)
+{
+ const char *str = "0123";
+ char f = 'X';
+ const char *endptr = &f;
+ int64_t res = 999;
+ int err;
+
+ err = qemu_strtoll(str, &endptr, 8, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, 0123);
+ g_assert(endptr == str + strlen(str));
+
+ endptr = &f;
+ res = 999;
+ err = qemu_strtoll(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, 0123);
+ g_assert(endptr == str + strlen(str));
+}
+
+static void test_qemu_strtoll_decimal(void)
+{
+ const char *str = "0123";
+ char f = 'X';
+ const char *endptr = &f;
+ int64_t res = 999;
+ int err;
+
+ err = qemu_strtoll(str, &endptr, 10, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, 123);
+ g_assert(endptr == str + strlen(str));
+
+ str = "123";
+ endptr = &f;
+ res = 999;
+ err = qemu_strtoll(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, 123);
+ g_assert(endptr == str + strlen(str));
+}
+
+static void test_qemu_strtoll_hex(void)
+{
+ const char *str = "0123";
+ char f = 'X';
+ const char *endptr = &f;
+ int64_t res = 999;
+ int err;
+
+ err = qemu_strtoll(str, &endptr, 16, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, 0x123);
+ g_assert(endptr == str + strlen(str));
+
+ str = "0x123";
+ endptr = &f;
+ res = 999;
+ err = qemu_strtoll(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, 0x123);
+ g_assert(endptr == str + strlen(str));
+}
+
+static void test_qemu_strtoll_max(void)
+{
+ const char *str = g_strdup_printf("%lld", LLONG_MAX);
+ char f = 'X';
+ const char *endptr = &f;
+ int64_t res = 999;
+ int err;
+
+ err = qemu_strtoll(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, LLONG_MAX);
+ g_assert(endptr == str + strlen(str));
+}
+
+static void test_qemu_strtoll_overflow(void)
+{
+ const char *str = "99999999999999999999999999999999999999999999";
+ char f = 'X';
+ const char *endptr = &f;
+ int64_t res = 999;
+ int err;
+
+ err = qemu_strtoll(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, -ERANGE);
+ g_assert_cmpint(res, ==, LLONG_MAX);
+ g_assert(endptr == str + strlen(str));
+}
+
+static void test_qemu_strtoll_underflow(void)
+{
+ const char *str = "-99999999999999999999999999999999999999999999";
+ char f = 'X';
+ const char *endptr = &f;
+ int64_t res = 999;
+ int err;
+
+ err = qemu_strtoll(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, -ERANGE);
+ g_assert_cmpint(res, ==, LLONG_MIN);
+ g_assert(endptr == str + strlen(str));
+}
+
+static void test_qemu_strtoll_negative(void)
+{
+ const char *str = " \t -321";
+ char f = 'X';
+ const char *endptr = &f;
+ int64_t res = 999;
+ int err;
+
+ err = qemu_strtoll(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, -321);
+ g_assert(endptr == str + strlen(str));
+}
+
+static void test_qemu_strtoll_full_correct(void)
+{
+ const char *str = "123";
+ int64_t res = 999;
+ int err;
+
+ err = qemu_strtoll(str, NULL, 0, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, 123);
+}
+
+static void test_qemu_strtoll_full_null(void)
+{
+ int64_t res = 999;
+ int err;
+
+ err = qemu_strtoll(NULL, NULL, 0, &res);
+
+ g_assert_cmpint(err, ==, -EINVAL);
+}
+
+static void test_qemu_strtoll_full_empty(void)
+{
+ const char *str = "";
+ int64_t res = 999;
+ int err;
+
+ err = qemu_strtoll(str, NULL, 0, &res);
+
+ g_assert_cmpint(err, ==, -EINVAL);
+}
+
+static void test_qemu_strtoll_full_negative(void)
+{
+ const char *str = " \t -321";
+ int64_t res = 999;
+ int err;
+
+ err = qemu_strtoll(str, NULL, 0, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, -321);
+}
+
+static void test_qemu_strtoll_full_trailing(void)
+{
+ const char *str = "123xxx";
+ int64_t res = 999;
+ int err;
+
+ err = qemu_strtoll(str, NULL, 0, &res);
+
+ g_assert_cmpint(err, ==, -EINVAL);
+}
+
+static void test_qemu_strtoll_full_max(void)
+{
+
+ const char *str = g_strdup_printf("%lld", LLONG_MAX);
+ int64_t res;
+ int err;
+
+ err = qemu_strtoll(str, NULL, 0, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, LLONG_MAX);
+}
+
+static void test_qemu_strtoull_correct(void)
+{
+ const char *str = "12345 foo";
+ char f = 'X';
+ const char *endptr = &f;
+ uint64_t res = 999;
+ int err;
+
+ err = qemu_strtoull(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, 12345);
+ g_assert(endptr == str + 5);
+}
+
+static void test_qemu_strtoull_null(void)
+{
+ char f = 'X';
+ const char *endptr = &f;
+ uint64_t res = 999;
+ int err;
+
+ err = qemu_strtoull(NULL, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, -EINVAL);
+ g_assert(endptr == NULL);
+}
+
+static void test_qemu_strtoull_empty(void)
+{
+ const char *str = "";
+ char f = 'X';
+ const char *endptr = &f;
+ uint64_t res = 999;
+ int err;
+
+ err = qemu_strtoull(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, -EINVAL);
+}
+
+static void test_qemu_strtoull_whitespace(void)
+{
+ const char *str = " \t ";
+ char f = 'X';
+ const char *endptr = &f;
+ uint64_t res = 999;
+ int err;
+
+ err = qemu_strtoull(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, -EINVAL);
+}
+
+static void test_qemu_strtoull_invalid(void)
+{
+ const char *str = " xxxx \t abc";
+ char f = 'X';
+ const char *endptr = &f;
+ uint64_t res = 999;
+ int err;
+
+ err = qemu_strtoull(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, -EINVAL);
+}
+
+static void test_qemu_strtoull_trailing(void)
+{
+ const char *str = "123xxx";
+ char f = 'X';
+ const char *endptr = &f;
+ uint64_t res = 999;
+ int err;
+
+ err = qemu_strtoull(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, 123);
+ g_assert(endptr == str + 3);
+}
+
+static void test_qemu_strtoull_octal(void)
+{
+ const char *str = "0123";
+ char f = 'X';
+ const char *endptr = &f;
+ uint64_t res = 999;
+ int err;
+
+ err = qemu_strtoull(str, &endptr, 8, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, 0123);
+ g_assert(endptr == str + strlen(str));
+
+ endptr = &f;
+ res = 999;
+ err = qemu_strtoull(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, 0123);
+ g_assert(endptr == str + strlen(str));
+}
+
+static void test_qemu_strtoull_decimal(void)
+{
+ const char *str = "0123";
+ char f = 'X';
+ const char *endptr = &f;
+ uint64_t res = 999;
+ int err;
+
+ err = qemu_strtoull(str, &endptr, 10, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, 123);
+ g_assert(endptr == str + strlen(str));
+
+ str = "123";
+ endptr = &f;
+ res = 999;
+ err = qemu_strtoull(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, 123);
+ g_assert(endptr == str + strlen(str));
+}
+
+static void test_qemu_strtoull_hex(void)
+{
+ const char *str = "0123";
+ char f = 'X';
+ const char *endptr = &f;
+ uint64_t res = 999;
+ int err;
+
+ err = qemu_strtoull(str, &endptr, 16, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, 0x123);
+ g_assert(endptr == str + strlen(str));
+
+ str = "0x123";
+ endptr = &f;
+ res = 999;
+ err = qemu_strtoull(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, 0x123);
+ g_assert(endptr == str + strlen(str));
+}
+
+static void test_qemu_strtoull_max(void)
+{
+ const char *str = g_strdup_printf("%llu", ULLONG_MAX);
+ char f = 'X';
+ const char *endptr = &f;
+ uint64_t res = 999;
+ int err;
+
+ err = qemu_strtoull(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, ULLONG_MAX);
+ g_assert(endptr == str + strlen(str));
+}
+
+static void test_qemu_strtoull_overflow(void)
+{
+ const char *str = "99999999999999999999999999999999999999999999";
+ char f = 'X';
+ const char *endptr = &f;
+ uint64_t res = 999;
+ int err;
+
+ err = qemu_strtoull(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, -ERANGE);
+ g_assert_cmpint(res, ==, ULLONG_MAX);
+ g_assert(endptr == str + strlen(str));
+}
+
+static void test_qemu_strtoull_underflow(void)
+{
+ const char *str = "-99999999999999999999999999999999999999999999";
+ char f = 'X';
+ const char *endptr = &f;
+ uint64_t res = 999;
+ int err;
+
+ err = qemu_strtoull(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, -ERANGE);
+ g_assert_cmpint(res, ==, -1);
+ g_assert(endptr == str + strlen(str));
+}
+
+static void test_qemu_strtoull_negative(void)
+{
+ const char *str = " \t -321";
+ char f = 'X';
+ const char *endptr = &f;
+ uint64_t res = 999;
+ int err;
+
+ err = qemu_strtoull(str, &endptr, 0, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, -321);
+ g_assert(endptr == str + strlen(str));
+}
+
+static void test_qemu_strtoull_full_correct(void)
+{
+ const char *str = "18446744073709551614";
+ uint64_t res = 999;
+ int err;
+
+ err = qemu_strtoull(str, NULL, 0, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, 18446744073709551614LLU);
+}
+
+static void test_qemu_strtoull_full_null(void)
+{
+ uint64_t res = 999;
+ int err;
+
+ err = qemu_strtoull(NULL, NULL, 0, &res);
+
+ g_assert_cmpint(err, ==, -EINVAL);
+}
+
+static void test_qemu_strtoull_full_empty(void)
+{
+ const char *str = "";
+ uint64_t res = 999;
+ int err;
+
+ err = qemu_strtoull(str, NULL, 0, &res);
+
+ g_assert_cmpint(err, ==, -EINVAL);
+}
+
+static void test_qemu_strtoull_full_negative(void)
+{
+ const char *str = " \t -321";
+ uint64_t res = 999;
+ int err;
+
+ err = qemu_strtoull(str, NULL, 0, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, 18446744073709551295LLU);
+}
+
+static void test_qemu_strtoull_full_trailing(void)
+{
+ const char *str = "18446744073709551614xxxxxx";
+ uint64_t res = 999;
+ int err;
+
+ err = qemu_strtoull(str, NULL, 0, &res);
+
+ g_assert_cmpint(err, ==, -EINVAL);
+}
+
+static void test_qemu_strtoull_full_max(void)
+{
+ const char *str = g_strdup_printf("%lld", ULLONG_MAX);
+ uint64_t res = 999;
+ int err;
+
+ err = qemu_strtoull(str, NULL, 0, &res);
+
+ g_assert_cmpint(err, ==, 0);
+ g_assert_cmpint(res, ==, ULLONG_MAX);
+}
+
+static void test_qemu_strtosz_simple(void)
+{
+ const char *str = "12345M";
+ char *endptr = NULL;
+ int64_t res;
+
+ res = qemu_strtosz(str, &endptr);
+ g_assert_cmpint(res, ==, 12345 * M_BYTE);
+ g_assert(endptr == str + 6);
+
+ res = qemu_strtosz(str, NULL);
+ g_assert_cmpint(res, ==, 12345 * M_BYTE);
+}
+
+static void test_qemu_strtosz_units(void)
+{
+ const char *none = "1";
+ const char *b = "1B";
+ const char *k = "1K";
+ const char *m = "1M";
+ const char *g = "1G";
+ const char *t = "1T";
+ const char *p = "1P";
+ const char *e = "1E";
+ int64_t res;
+
+ /* default is M */
+ res = qemu_strtosz(none, NULL);
+ g_assert_cmpint(res, ==, M_BYTE);
+
+ res = qemu_strtosz(b, NULL);
+ g_assert_cmpint(res, ==, 1);
+
+ res = qemu_strtosz(k, NULL);
+ g_assert_cmpint(res, ==, K_BYTE);
+
+ res = qemu_strtosz(m, NULL);
+ g_assert_cmpint(res, ==, M_BYTE);
+
+ res = qemu_strtosz(g, NULL);
+ g_assert_cmpint(res, ==, G_BYTE);
+
+ res = qemu_strtosz(t, NULL);
+ g_assert_cmpint(res, ==, T_BYTE);
+
+ res = qemu_strtosz(p, NULL);
+ g_assert_cmpint(res, ==, P_BYTE);
+
+ res = qemu_strtosz(e, NULL);
+ g_assert_cmpint(res, ==, E_BYTE);
+}
+
+static void test_qemu_strtosz_float(void)
+{
+ const char *str = "12.345M";
+ int64_t res;
+
+ res = qemu_strtosz(str, NULL);
+ g_assert_cmpint(res, ==, 12.345 * M_BYTE);
+}
+
+static void test_qemu_strtosz_erange(void)
+{
+ const char *str = "10E";
+ int64_t res;
+
+ res = qemu_strtosz(str, NULL);
+ g_assert_cmpint(res, ==, -ERANGE);
+}
+
+static void test_qemu_strtosz_suffix_unit(void)
+{
+ const char *str = "12345";
+ int64_t res;
+
+ res = qemu_strtosz_suffix_unit(str, NULL,
+ QEMU_STRTOSZ_DEFSUFFIX_KB, 1000);
+ g_assert_cmpint(res, ==, 12345000);
+}
+
int main(int argc, char **argv)
{
g_test_init(&argc, &argv, NULL);
@@ -247,5 +1453,145 @@ int main(int argc, char **argv)
g_test_add_func("/cutils/parse_uint_full/correct",
test_parse_uint_full_correct);
+ /* qemu_strtol() tests */
+ g_test_add_func("/cutils/qemu_strtol/correct", test_qemu_strtol_correct);
+ g_test_add_func("/cutils/qemu_strtol/null", test_qemu_strtol_null);
+ g_test_add_func("/cutils/qemu_strtol/empty", test_qemu_strtol_empty);
+ g_test_add_func("/cutils/qemu_strtol/whitespace",
+ test_qemu_strtol_whitespace);
+ g_test_add_func("/cutils/qemu_strtol/invalid", test_qemu_strtol_invalid);
+ g_test_add_func("/cutils/qemu_strtol/trailing", test_qemu_strtol_trailing);
+ g_test_add_func("/cutils/qemu_strtol/octal", test_qemu_strtol_octal);
+ g_test_add_func("/cutils/qemu_strtol/decimal", test_qemu_strtol_decimal);
+ g_test_add_func("/cutils/qemu_strtol/hex", test_qemu_strtol_hex);
+ g_test_add_func("/cutils/qemu_strtol/max", test_qemu_strtol_max);
+ g_test_add_func("/cutils/qemu_strtol/overflow", test_qemu_strtol_overflow);
+ g_test_add_func("/cutils/qemu_strtol/underflow",
+ test_qemu_strtol_underflow);
+ g_test_add_func("/cutils/qemu_strtol/negative", test_qemu_strtol_negative);
+ g_test_add_func("/cutils/qemu_strtol_full/correct",
+ test_qemu_strtol_full_correct);
+ g_test_add_func("/cutils/qemu_strtol_full/null",
+ test_qemu_strtol_full_null);
+ g_test_add_func("/cutils/qemu_strtol_full/empty",
+ test_qemu_strtol_full_empty);
+ g_test_add_func("/cutils/qemu_strtol_full/negative",
+ test_qemu_strtol_full_negative);
+ g_test_add_func("/cutils/qemu_strtol_full/trailing",
+ test_qemu_strtol_full_trailing);
+ g_test_add_func("/cutils/qemu_strtol_full/max",
+ test_qemu_strtol_full_max);
+
+ /* qemu_strtoul() tests */
+ g_test_add_func("/cutils/qemu_strtoul/correct", test_qemu_strtoul_correct);
+ g_test_add_func("/cutils/qemu_strtoul/null", test_qemu_strtoul_null);
+ g_test_add_func("/cutils/qemu_strtoul/empty", test_qemu_strtoul_empty);
+ g_test_add_func("/cutils/qemu_strtoul/whitespace",
+ test_qemu_strtoul_whitespace);
+ g_test_add_func("/cutils/qemu_strtoul/invalid", test_qemu_strtoul_invalid);
+ g_test_add_func("/cutils/qemu_strtoul/trailing",
+ test_qemu_strtoul_trailing);
+ g_test_add_func("/cutils/qemu_strtoul/octal", test_qemu_strtoul_octal);
+ g_test_add_func("/cutils/qemu_strtoul/decimal", test_qemu_strtoul_decimal);
+ g_test_add_func("/cutils/qemu_strtoul/hex", test_qemu_strtoul_hex);
+ g_test_add_func("/cutils/qemu_strtoul/max", test_qemu_strtoul_max);
+ g_test_add_func("/cutils/qemu_strtoul/overflow",
+ test_qemu_strtoul_overflow);
+ g_test_add_func("/cutils/qemu_strtoul/underflow",
+ test_qemu_strtoul_underflow);
+ g_test_add_func("/cutils/qemu_strtoul/negative",
+ test_qemu_strtoul_negative);
+ g_test_add_func("/cutils/qemu_strtoul_full/correct",
+ test_qemu_strtoul_full_correct);
+ g_test_add_func("/cutils/qemu_strtoul_full/null",
+ test_qemu_strtoul_full_null);
+ g_test_add_func("/cutils/qemu_strtoul_full/empty",
+ test_qemu_strtoul_full_empty);
+ g_test_add_func("/cutils/qemu_strtoul_full/negative",
+ test_qemu_strtoul_full_negative);
+ g_test_add_func("/cutils/qemu_strtoul_full/trailing",
+ test_qemu_strtoul_full_trailing);
+ g_test_add_func("/cutils/qemu_strtoul_full/max",
+ test_qemu_strtoul_full_max);
+
+ /* qemu_strtoll() tests */
+ g_test_add_func("/cutils/qemu_strtoll/correct", test_qemu_strtoll_correct);
+ g_test_add_func("/cutils/qemu_strtoll/null", test_qemu_strtoll_null);
+ g_test_add_func("/cutils/qemu_strtoll/empty", test_qemu_strtoll_empty);
+ g_test_add_func("/cutils/qemu_strtoll/whitespace",
+ test_qemu_strtoll_whitespace);
+ g_test_add_func("/cutils/qemu_strtoll/invalid", test_qemu_strtoll_invalid);
+ g_test_add_func("/cutils/qemu_strtoll/trailing",
+ test_qemu_strtoll_trailing);
+ g_test_add_func("/cutils/qemu_strtoll/octal", test_qemu_strtoll_octal);
+ g_test_add_func("/cutils/qemu_strtoll/decimal", test_qemu_strtoll_decimal);
+ g_test_add_func("/cutils/qemu_strtoll/hex", test_qemu_strtoll_hex);
+ g_test_add_func("/cutils/qemu_strtoll/max", test_qemu_strtoll_max);
+ g_test_add_func("/cutils/qemu_strtoll/overflow",
+ test_qemu_strtoll_overflow);
+ g_test_add_func("/cutils/qemu_strtoll/underflow",
+ test_qemu_strtoll_underflow);
+ g_test_add_func("/cutils/qemu_strtoll/negative",
+ test_qemu_strtoll_negative);
+ g_test_add_func("/cutils/qemu_strtoll_full/correct",
+ test_qemu_strtoll_full_correct);
+ g_test_add_func("/cutils/qemu_strtoll_full/null",
+ test_qemu_strtoll_full_null);
+ g_test_add_func("/cutils/qemu_strtoll_full/empty",
+ test_qemu_strtoll_full_empty);
+ g_test_add_func("/cutils/qemu_strtoll_full/negative",
+ test_qemu_strtoll_full_negative);
+ g_test_add_func("/cutils/qemu_strtoll_full/trailing",
+ test_qemu_strtoll_full_trailing);
+ g_test_add_func("/cutils/qemu_strtoll_full/max",
+ test_qemu_strtoll_full_max);
+
+ /* qemu_strtoull() tests */
+ g_test_add_func("/cutils/qemu_strtoull/correct",
+ test_qemu_strtoull_correct);
+ g_test_add_func("/cutils/qemu_strtoull/null",
+ test_qemu_strtoull_null);
+ g_test_add_func("/cutils/qemu_strtoull/empty", test_qemu_strtoull_empty);
+ g_test_add_func("/cutils/qemu_strtoull/whitespace",
+ test_qemu_strtoull_whitespace);
+ g_test_add_func("/cutils/qemu_strtoull/invalid",
+ test_qemu_strtoull_invalid);
+ g_test_add_func("/cutils/qemu_strtoull/trailing",
+ test_qemu_strtoull_trailing);
+ g_test_add_func("/cutils/qemu_strtoull/octal", test_qemu_strtoull_octal);
+ g_test_add_func("/cutils/qemu_strtoull/decimal",
+ test_qemu_strtoull_decimal);
+ g_test_add_func("/cutils/qemu_strtoull/hex", test_qemu_strtoull_hex);
+ g_test_add_func("/cutils/qemu_strtoull/max", test_qemu_strtoull_max);
+ g_test_add_func("/cutils/qemu_strtoull/overflow",
+ test_qemu_strtoull_overflow);
+ g_test_add_func("/cutils/qemu_strtoull/underflow",
+ test_qemu_strtoull_underflow);
+ g_test_add_func("/cutils/qemu_strtoull/negative",
+ test_qemu_strtoull_negative);
+ g_test_add_func("/cutils/qemu_strtoull_full/correct",
+ test_qemu_strtoull_full_correct);
+ g_test_add_func("/cutils/qemu_strtoull_full/null",
+ test_qemu_strtoull_full_null);
+ g_test_add_func("/cutils/qemu_strtoull_full/empty",
+ test_qemu_strtoull_full_empty);
+ g_test_add_func("/cutils/qemu_strtoull_full/negative",
+ test_qemu_strtoull_full_negative);
+ g_test_add_func("/cutils/qemu_strtoull_full/trailing",
+ test_qemu_strtoull_full_trailing);
+ g_test_add_func("/cutils/qemu_strtoull_full/max",
+ test_qemu_strtoull_full_max);
+
+ g_test_add_func("/cutils/strtosz/simple",
+ test_qemu_strtosz_simple);
+ g_test_add_func("/cutils/strtosz/units",
+ test_qemu_strtosz_units);
+ g_test_add_func("/cutils/strtosz/float",
+ test_qemu_strtosz_float);
+ g_test_add_func("/cutils/strtosz/erange",
+ test_qemu_strtosz_erange);
+ g_test_add_func("/cutils/strtosz/suffix-unit",
+ test_qemu_strtosz_suffix_unit);
+
return g_test_run();
}
diff --git a/tests/test-hbitmap.c b/tests/test-hbitmap.c
index 161eeb496..abcea0cda 100644
--- a/tests/test-hbitmap.c
+++ b/tests/test-hbitmap.c
@@ -139,10 +139,8 @@ static void hbitmap_test_teardown(TestHBitmapData *data,
hbitmap_free(data->hb);
data->hb = NULL;
}
- if (data->bits) {
- g_free(data->bits);
- data->bits = NULL;
- }
+ g_free(data->bits);
+ data->bits = NULL;
}
/* Set a range in the HBitmap and in the shadow "simple" bitmap.
diff --git a/tests/test-netfilter.c b/tests/test-netfilter.c
new file mode 100644
index 000000000..303deb7e0
--- /dev/null
+++ b/tests/test-netfilter.c
@@ -0,0 +1,200 @@
+/*
+ * QTest testcase for netfilter
+ *
+ * Copyright (c) 2015 FUJITSU LIMITED
+ * Author: Yang Hongyang <yanghy@cn.fujitsu.com>
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or
+ * later. See the COPYING file in the top-level directory.
+ */
+
+#include <glib.h>
+#include "libqtest.h"
+
+/* add a netfilter to a netdev and then remove it */
+static void add_one_netfilter(void)
+{
+ QDict *response;
+
+ response = qmp("{'execute': 'object-add',"
+ " 'arguments': {"
+ " 'qom-type': 'filter-buffer',"
+ " 'id': 'qtest-f0',"
+ " 'props': {"
+ " 'netdev': 'qtest-bn0',"
+ " 'queue': 'rx',"
+ " 'interval': 1000"
+ "}}}");
+
+ g_assert(response);
+ g_assert(!qdict_haskey(response, "error"));
+ QDECREF(response);
+
+ response = qmp("{'execute': 'object-del',"
+ " 'arguments': {"
+ " 'id': 'qtest-f0'"
+ "}}");
+ g_assert(response);
+ g_assert(!qdict_haskey(response, "error"));
+ QDECREF(response);
+}
+
+/* add a netfilter to a netdev and then remove the netdev */
+static void remove_netdev_with_one_netfilter(void)
+{
+ QDict *response;
+
+ response = qmp("{'execute': 'object-add',"
+ " 'arguments': {"
+ " 'qom-type': 'filter-buffer',"
+ " 'id': 'qtest-f0',"
+ " 'props': {"
+ " 'netdev': 'qtest-bn0',"
+ " 'queue': 'rx',"
+ " 'interval': 1000"
+ "}}}");
+
+ g_assert(response);
+ g_assert(!qdict_haskey(response, "error"));
+ QDECREF(response);
+
+ response = qmp("{'execute': 'netdev_del',"
+ " 'arguments': {"
+ " 'id': 'qtest-bn0'"
+ "}}");
+ g_assert(response);
+ g_assert(!qdict_haskey(response, "error"));
+ QDECREF(response);
+
+ /* add back the netdev */
+ response = qmp("{'execute': 'netdev_add',"
+ " 'arguments': {"
+ " 'type': 'user',"
+ " 'id': 'qtest-bn0'"
+ "}}");
+ g_assert(response);
+ g_assert(!qdict_haskey(response, "error"));
+ QDECREF(response);
+}
+
+/* add multi(2) netfilters to a netdev and then remove them */
+static void add_multi_netfilter(void)
+{
+ QDict *response;
+
+ response = qmp("{'execute': 'object-add',"
+ " 'arguments': {"
+ " 'qom-type': 'filter-buffer',"
+ " 'id': 'qtest-f0',"
+ " 'props': {"
+ " 'netdev': 'qtest-bn0',"
+ " 'queue': 'rx',"
+ " 'interval': 1000"
+ "}}}");
+
+ g_assert(response);
+ g_assert(!qdict_haskey(response, "error"));
+ QDECREF(response);
+
+ response = qmp("{'execute': 'object-add',"
+ " 'arguments': {"
+ " 'qom-type': 'filter-buffer',"
+ " 'id': 'qtest-f1',"
+ " 'props': {"
+ " 'netdev': 'qtest-bn0',"
+ " 'queue': 'rx',"
+ " 'interval': 1000"
+ "}}}");
+
+ g_assert(response);
+ g_assert(!qdict_haskey(response, "error"));
+ QDECREF(response);
+
+ response = qmp("{'execute': 'object-del',"
+ " 'arguments': {"
+ " 'id': 'qtest-f0'"
+ "}}");
+ g_assert(response);
+ g_assert(!qdict_haskey(response, "error"));
+ QDECREF(response);
+
+ response = qmp("{'execute': 'object-del',"
+ " 'arguments': {"
+ " 'id': 'qtest-f1'"
+ "}}");
+ g_assert(response);
+ g_assert(!qdict_haskey(response, "error"));
+ QDECREF(response);
+}
+
+/* add multi(2) netfilters to a netdev and then remove the netdev */
+static void remove_netdev_with_multi_netfilter(void)
+{
+ QDict *response;
+
+ response = qmp("{'execute': 'object-add',"
+ " 'arguments': {"
+ " 'qom-type': 'filter-buffer',"
+ " 'id': 'qtest-f0',"
+ " 'props': {"
+ " 'netdev': 'qtest-bn0',"
+ " 'queue': 'rx',"
+ " 'interval': 1000"
+ "}}}");
+
+ g_assert(response);
+ g_assert(!qdict_haskey(response, "error"));
+ QDECREF(response);
+
+ response = qmp("{'execute': 'object-add',"
+ " 'arguments': {"
+ " 'qom-type': 'filter-buffer',"
+ " 'id': 'qtest-f1',"
+ " 'props': {"
+ " 'netdev': 'qtest-bn0',"
+ " 'queue': 'rx',"
+ " 'interval': 1000"
+ "}}}");
+
+ g_assert(response);
+ g_assert(!qdict_haskey(response, "error"));
+ QDECREF(response);
+
+ response = qmp("{'execute': 'netdev_del',"
+ " 'arguments': {"
+ " 'id': 'qtest-bn0'"
+ "}}");
+ g_assert(response);
+ g_assert(!qdict_haskey(response, "error"));
+ QDECREF(response);
+
+ /* add back the netdev */
+ response = qmp("{'execute': 'netdev_add',"
+ " 'arguments': {"
+ " 'type': 'user',"
+ " 'id': 'qtest-bn0'"
+ "}}");
+ g_assert(response);
+ g_assert(!qdict_haskey(response, "error"));
+ QDECREF(response);
+}
+
+int main(int argc, char **argv)
+{
+ int ret;
+
+ g_test_init(&argc, &argv, NULL);
+ qtest_add_func("/netfilter/addremove_one", add_one_netfilter);
+ qtest_add_func("/netfilter/remove_netdev_one",
+ remove_netdev_with_one_netfilter);
+ qtest_add_func("/netfilter/addremove_multi", add_multi_netfilter);
+ qtest_add_func("/netfilter/remove_netdev_multi",
+ remove_netdev_with_multi_netfilter);
+
+ qtest_start("-netdev user,id=qtest-bn0 -device e1000,netdev=qtest-bn0");
+ ret = g_test_run();
+
+ qtest_end();
+
+ return ret;
+}
diff --git a/tests/test-qga.c b/tests/test-qga.c
new file mode 100644
index 000000000..e6a84d17f
--- /dev/null
+++ b/tests/test-qga.c
@@ -0,0 +1,877 @@
+#include <locale.h>
+#include <glib.h>
+#include <glib/gstdio.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <string.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <unistd.h>
+#include <inttypes.h>
+
+#include "libqtest.h"
+#include "config-host.h"
+#include "qga/guest-agent-core.h"
+
+typedef struct {
+ char *test_dir;
+ GMainLoop *loop;
+ int fd;
+ GPid pid;
+} TestFixture;
+
+static int connect_qga(char *path)
+{
+ int s, ret, len, i = 0;
+ struct sockaddr_un remote;
+
+ s = socket(AF_UNIX, SOCK_STREAM, 0);
+ g_assert(s != -1);
+
+ remote.sun_family = AF_UNIX;
+ do {
+ strcpy(remote.sun_path, path);
+ len = strlen(remote.sun_path) + sizeof(remote.sun_family);
+ ret = connect(s, (struct sockaddr *)&remote, len);
+ if (ret == -1) {
+ g_usleep(G_USEC_PER_SEC);
+ }
+ if (i++ == 10) {
+ return -1;
+ }
+ } while (ret == -1);
+
+ return s;
+}
+
+static void qga_watch(GPid pid, gint status, gpointer user_data)
+{
+ TestFixture *fixture = user_data;
+
+ g_assert_cmpint(status, ==, 0);
+ g_main_loop_quit(fixture->loop);
+}
+
+static void
+fixture_setup(TestFixture *fixture, gconstpointer data)
+{
+ const gchar *extra_arg = data;
+ GError *error = NULL;
+ gchar *cwd, *path, *cmd, **argv = NULL;
+
+ fixture->loop = g_main_loop_new(NULL, FALSE);
+
+ fixture->test_dir = g_strdup("/tmp/qgatest.XXXXXX");
+ g_assert_nonnull(mkdtemp(fixture->test_dir));
+
+ path = g_build_filename(fixture->test_dir, "sock", NULL);
+ cwd = g_get_current_dir();
+ cmd = g_strdup_printf("%s%cqemu-ga -m unix-listen -t %s -p %s %s %s",
+ cwd, G_DIR_SEPARATOR,
+ fixture->test_dir, path,
+ getenv("QTEST_LOG") ? "-v" : "",
+ extra_arg ?: "");
+ g_shell_parse_argv(cmd, NULL, &argv, &error);
+ g_assert_no_error(error);
+
+ g_spawn_async(fixture->test_dir, argv, NULL,
+ G_SPAWN_SEARCH_PATH|G_SPAWN_DO_NOT_REAP_CHILD,
+ NULL, NULL, &fixture->pid, &error);
+ g_assert_no_error(error);
+
+ g_child_watch_add(fixture->pid, qga_watch, fixture);
+
+ fixture->fd = connect_qga(path);
+ g_assert_cmpint(fixture->fd, !=, -1);
+
+ g_strfreev(argv);
+ g_free(cmd);
+ g_free(cwd);
+ g_free(path);
+}
+
+static void
+fixture_tear_down(TestFixture *fixture, gconstpointer data)
+{
+ gchar *tmp;
+
+ kill(fixture->pid, SIGTERM);
+
+ g_main_loop_run(fixture->loop);
+ g_main_loop_unref(fixture->loop);
+
+ g_spawn_close_pid(fixture->pid);
+
+ tmp = g_build_filename(fixture->test_dir, "foo", NULL);
+ g_unlink(tmp);
+ g_free(tmp);
+
+ tmp = g_build_filename(fixture->test_dir, "qga.state", NULL);
+ g_unlink(tmp);
+ g_free(tmp);
+
+ tmp = g_build_filename(fixture->test_dir, "sock", NULL);
+ g_unlink(tmp);
+ g_free(tmp);
+
+ g_rmdir(fixture->test_dir);
+ g_free(fixture->test_dir);
+}
+
+static void qmp_assertion_message_error(const char *domain,
+ const char *file,
+ int line,
+ const char *func,
+ const char *expr,
+ QDict *dict)
+{
+ const char *class, *desc;
+ char *s;
+ QDict *error;
+
+ error = qdict_get_qdict(dict, "error");
+ class = qdict_get_try_str(error, "class");
+ desc = qdict_get_try_str(error, "desc");
+
+ s = g_strdup_printf("assertion failed %s: %s %s", expr, class, desc);
+ g_assertion_message(domain, file, line, func, s);
+ g_free(s);
+}
+
+#define qmp_assert_no_error(err) do { \
+ if (qdict_haskey(err, "error")) { \
+ qmp_assertion_message_error(G_LOG_DOMAIN, __FILE__, __LINE__, \
+ G_STRFUNC, #err, err); \
+ } \
+} while (0)
+
+static void test_qga_sync_delimited(gconstpointer fix)
+{
+ const TestFixture *fixture = fix;
+ guint32 v, r = g_random_int();
+ unsigned char c;
+ QDict *ret;
+ gchar *cmd;
+
+ cmd = g_strdup_printf("%c{'execute': 'guest-sync-delimited',"
+ " 'arguments': {'id': %u } }", 0xff, r);
+ qmp_fd_send(fixture->fd, cmd);
+ g_free(cmd);
+
+ v = read(fixture->fd, &c, 1);
+ g_assert_cmpint(v, ==, 1);
+ g_assert_cmpint(c, ==, 0xff);
+
+ ret = qmp_fd_receive(fixture->fd);
+ g_assert_nonnull(ret);
+ qmp_assert_no_error(ret);
+
+ v = qdict_get_int(ret, "return");
+ g_assert_cmpint(r, ==, v);
+
+ QDECREF(ret);
+}
+
+static void test_qga_sync(gconstpointer fix)
+{
+ const TestFixture *fixture = fix;
+ guint32 v, r = g_random_int();
+ QDict *ret;
+ gchar *cmd;
+
+ cmd = g_strdup_printf("%c{'execute': 'guest-sync',"
+ " 'arguments': {'id': %u } }", 0xff, r);
+ ret = qmp_fd(fixture->fd, cmd);
+ g_free(cmd);
+
+ g_assert_nonnull(ret);
+ qmp_assert_no_error(ret);
+
+ v = qdict_get_int(ret, "return");
+ g_assert_cmpint(r, ==, v);
+
+ QDECREF(ret);
+}
+
+static void test_qga_ping(gconstpointer fix)
+{
+ const TestFixture *fixture = fix;
+ QDict *ret;
+
+ ret = qmp_fd(fixture->fd, "{'execute': 'guest-ping'}");
+ g_assert_nonnull(ret);
+ qmp_assert_no_error(ret);
+
+ QDECREF(ret);
+}
+
+static void test_qga_invalid_cmd(gconstpointer fix)
+{
+ const TestFixture *fixture = fix;
+ QDict *ret, *error;
+ const gchar *class, *desc;
+
+ ret = qmp_fd(fixture->fd, "{'execute': 'guest-invalid-cmd'}");
+ g_assert_nonnull(ret);
+
+ error = qdict_get_qdict(ret, "error");
+ class = qdict_get_try_str(error, "class");
+ desc = qdict_get_try_str(error, "desc");
+
+ g_assert_cmpstr(class, ==, "CommandNotFound");
+ g_assert_cmpint(strlen(desc), >, 0);
+
+ QDECREF(ret);
+}
+
+static void test_qga_info(gconstpointer fix)
+{
+ const TestFixture *fixture = fix;
+ QDict *ret, *val;
+ const gchar *version;
+
+ ret = qmp_fd(fixture->fd, "{'execute': 'guest-info'}");
+ g_assert_nonnull(ret);
+ qmp_assert_no_error(ret);
+
+ val = qdict_get_qdict(ret, "return");
+ version = qdict_get_try_str(val, "version");
+ g_assert_cmpstr(version, ==, QEMU_VERSION);
+
+ QDECREF(ret);
+}
+
+static void test_qga_get_vcpus(gconstpointer fix)
+{
+ const TestFixture *fixture = fix;
+ QDict *ret;
+ QList *list;
+ const QListEntry *entry;
+
+ ret = qmp_fd(fixture->fd, "{'execute': 'guest-get-vcpus'}");
+ g_assert_nonnull(ret);
+ qmp_assert_no_error(ret);
+
+ /* check there is at least a cpu */
+ list = qdict_get_qlist(ret, "return");
+ entry = qlist_first(list);
+ g_assert(qdict_haskey(qobject_to_qdict(entry->value), "online"));
+ g_assert(qdict_haskey(qobject_to_qdict(entry->value), "logical-id"));
+
+ QDECREF(ret);
+}
+
+static void test_qga_get_fsinfo(gconstpointer fix)
+{
+ const TestFixture *fixture = fix;
+ QDict *ret;
+ QList *list;
+ const QListEntry *entry;
+
+ ret = qmp_fd(fixture->fd, "{'execute': 'guest-get-fsinfo'}");
+ g_assert_nonnull(ret);
+ qmp_assert_no_error(ret);
+
+ /* sanity-check the response if there are any filesystems */
+ list = qdict_get_qlist(ret, "return");
+ entry = qlist_first(list);
+ if (entry) {
+ g_assert(qdict_haskey(qobject_to_qdict(entry->value), "name"));
+ g_assert(qdict_haskey(qobject_to_qdict(entry->value), "mountpoint"));
+ g_assert(qdict_haskey(qobject_to_qdict(entry->value), "type"));
+ g_assert(qdict_haskey(qobject_to_qdict(entry->value), "disk"));
+ }
+
+ QDECREF(ret);
+}
+
+static void test_qga_get_memory_block_info(gconstpointer fix)
+{
+ const TestFixture *fixture = fix;
+ QDict *ret, *val;
+ int64_t size;
+
+ ret = qmp_fd(fixture->fd, "{'execute': 'guest-get-memory-block-info'}");
+ g_assert_nonnull(ret);
+
+ /* some systems might not expose memory block info in sysfs */
+ if (!qdict_haskey(ret, "error")) {
+ /* check there is at least some memory */
+ val = qdict_get_qdict(ret, "return");
+ size = qdict_get_int(val, "size");
+ g_assert_cmpint(size, >, 0);
+ }
+
+ QDECREF(ret);
+}
+
+static void test_qga_get_memory_blocks(gconstpointer fix)
+{
+ const TestFixture *fixture = fix;
+ QDict *ret;
+ QList *list;
+ const QListEntry *entry;
+
+ ret = qmp_fd(fixture->fd, "{'execute': 'guest-get-memory-blocks'}");
+ g_assert_nonnull(ret);
+
+ /* some systems might not expose memory block info in sysfs */
+ if (!qdict_haskey(ret, "error")) {
+ list = qdict_get_qlist(ret, "return");
+ entry = qlist_first(list);
+ /* newer versions of qga may return empty list without error */
+ if (entry) {
+ g_assert(qdict_haskey(qobject_to_qdict(entry->value), "phys-index"));
+ g_assert(qdict_haskey(qobject_to_qdict(entry->value), "online"));
+ }
+ }
+
+ QDECREF(ret);
+}
+
+static void test_qga_network_get_interfaces(gconstpointer fix)
+{
+ const TestFixture *fixture = fix;
+ QDict *ret;
+ QList *list;
+ const QListEntry *entry;
+
+ ret = qmp_fd(fixture->fd, "{'execute': 'guest-network-get-interfaces'}");
+ g_assert_nonnull(ret);
+ qmp_assert_no_error(ret);
+
+ /* check there is at least an interface */
+ list = qdict_get_qlist(ret, "return");
+ entry = qlist_first(list);
+ g_assert(qdict_haskey(qobject_to_qdict(entry->value), "name"));
+
+ QDECREF(ret);
+}
+
+static void test_qga_file_ops(gconstpointer fix)
+{
+ const TestFixture *fixture = fix;
+ const unsigned char helloworld[] = "Hello World!\n";
+ const char *b64;
+ gchar *cmd, *path, *enc;
+ unsigned char *dec;
+ QDict *ret, *val;
+ int64_t id, eof;
+ gsize count;
+ FILE *f;
+ char tmp[100];
+
+ /* open */
+ ret = qmp_fd(fixture->fd, "{'execute': 'guest-file-open',"
+ " 'arguments': { 'path': 'foo', 'mode': 'w+' } }");
+ g_assert_nonnull(ret);
+ qmp_assert_no_error(ret);
+ id = qdict_get_int(ret, "return");
+ QDECREF(ret);
+
+ enc = g_base64_encode(helloworld, sizeof(helloworld));
+ /* write */
+ cmd = g_strdup_printf("{'execute': 'guest-file-write',"
+ " 'arguments': { 'handle': %" PRId64 ","
+ " 'buf-b64': '%s' } }", id, enc);
+ ret = qmp_fd(fixture->fd, cmd);
+ g_assert_nonnull(ret);
+ qmp_assert_no_error(ret);
+
+ val = qdict_get_qdict(ret, "return");
+ count = qdict_get_int(val, "count");
+ eof = qdict_get_bool(val, "eof");
+ g_assert_cmpint(count, ==, sizeof(helloworld));
+ g_assert_cmpint(eof, ==, 0);
+ QDECREF(ret);
+ g_free(cmd);
+
+ /* flush */
+ cmd = g_strdup_printf("{'execute': 'guest-file-flush',"
+ " 'arguments': {'handle': %" PRId64 "} }",
+ id);
+ ret = qmp_fd(fixture->fd, cmd);
+ QDECREF(ret);
+ g_free(cmd);
+
+ /* close */
+ cmd = g_strdup_printf("{'execute': 'guest-file-close',"
+ " 'arguments': {'handle': %" PRId64 "} }",
+ id);
+ ret = qmp_fd(fixture->fd, cmd);
+ QDECREF(ret);
+ g_free(cmd);
+
+ /* check content */
+ path = g_build_filename(fixture->test_dir, "foo", NULL);
+ f = fopen(path, "r");
+ g_assert_nonnull(f);
+ count = fread(tmp, 1, sizeof(tmp), f);
+ g_assert_cmpint(count, ==, sizeof(helloworld));
+ tmp[count] = 0;
+ g_assert_cmpstr(tmp, ==, (char *)helloworld);
+ fclose(f);
+
+ /* open */
+ ret = qmp_fd(fixture->fd, "{'execute': 'guest-file-open',"
+ " 'arguments': { 'path': 'foo', 'mode': 'r' } }");
+ g_assert_nonnull(ret);
+ qmp_assert_no_error(ret);
+ id = qdict_get_int(ret, "return");
+ QDECREF(ret);
+
+ /* read */
+ cmd = g_strdup_printf("{'execute': 'guest-file-read',"
+ " 'arguments': { 'handle': %" PRId64 "} }",
+ id);
+ ret = qmp_fd(fixture->fd, cmd);
+ val = qdict_get_qdict(ret, "return");
+ count = qdict_get_int(val, "count");
+ eof = qdict_get_bool(val, "eof");
+ b64 = qdict_get_str(val, "buf-b64");
+ g_assert_cmpint(count, ==, sizeof(helloworld));
+ g_assert(eof);
+ g_assert_cmpstr(b64, ==, enc);
+
+ QDECREF(ret);
+ g_free(cmd);
+ g_free(enc);
+
+ /* read eof */
+ cmd = g_strdup_printf("{'execute': 'guest-file-read',"
+ " 'arguments': { 'handle': %" PRId64 "} }",
+ id);
+ ret = qmp_fd(fixture->fd, cmd);
+ val = qdict_get_qdict(ret, "return");
+ count = qdict_get_int(val, "count");
+ eof = qdict_get_bool(val, "eof");
+ b64 = qdict_get_str(val, "buf-b64");
+ g_assert_cmpint(count, ==, 0);
+ g_assert(eof);
+ g_assert_cmpstr(b64, ==, "");
+ QDECREF(ret);
+ g_free(cmd);
+
+ /* seek */
+ cmd = g_strdup_printf("{'execute': 'guest-file-seek',"
+ " 'arguments': { 'handle': %" PRId64 ", "
+ " 'offset': %d, 'whence': %d } }",
+ id, 6, QGA_SEEK_SET);
+ ret = qmp_fd(fixture->fd, cmd);
+ qmp_assert_no_error(ret);
+ val = qdict_get_qdict(ret, "return");
+ count = qdict_get_int(val, "position");
+ eof = qdict_get_bool(val, "eof");
+ g_assert_cmpint(count, ==, 6);
+ g_assert(!eof);
+ QDECREF(ret);
+ g_free(cmd);
+
+ /* partial read */
+ cmd = g_strdup_printf("{'execute': 'guest-file-read',"
+ " 'arguments': { 'handle': %" PRId64 "} }",
+ id);
+ ret = qmp_fd(fixture->fd, cmd);
+ val = qdict_get_qdict(ret, "return");
+ count = qdict_get_int(val, "count");
+ eof = qdict_get_bool(val, "eof");
+ b64 = qdict_get_str(val, "buf-b64");
+ g_assert_cmpint(count, ==, sizeof(helloworld) - 6);
+ g_assert(eof);
+ dec = g_base64_decode(b64, &count);
+ g_assert_cmpint(count, ==, sizeof(helloworld) - 6);
+ g_assert_cmpmem(dec, count, helloworld + 6, sizeof(helloworld) - 6);
+ g_free(dec);
+
+ QDECREF(ret);
+ g_free(cmd);
+
+ /* close */
+ cmd = g_strdup_printf("{'execute': 'guest-file-close',"
+ " 'arguments': {'handle': %" PRId64 "} }",
+ id);
+ ret = qmp_fd(fixture->fd, cmd);
+ QDECREF(ret);
+ g_free(cmd);
+}
+
+static void test_qga_file_write_read(gconstpointer fix)
+{
+ const TestFixture *fixture = fix;
+ const unsigned char helloworld[] = "Hello World!\n";
+ const char *b64;
+ gchar *cmd, *enc;
+ QDict *ret, *val;
+ int64_t id, eof;
+ gsize count;
+
+ /* open */
+ ret = qmp_fd(fixture->fd, "{'execute': 'guest-file-open',"
+ " 'arguments': { 'path': 'foo', 'mode': 'w+' } }");
+ g_assert_nonnull(ret);
+ qmp_assert_no_error(ret);
+ id = qdict_get_int(ret, "return");
+ QDECREF(ret);
+
+ enc = g_base64_encode(helloworld, sizeof(helloworld));
+ /* write */
+ cmd = g_strdup_printf("{'execute': 'guest-file-write',"
+ " 'arguments': { 'handle': %" PRId64 ","
+ " 'buf-b64': '%s' } }", id, enc);
+ ret = qmp_fd(fixture->fd, cmd);
+ g_assert_nonnull(ret);
+ qmp_assert_no_error(ret);
+
+ val = qdict_get_qdict(ret, "return");
+ count = qdict_get_int(val, "count");
+ eof = qdict_get_bool(val, "eof");
+ g_assert_cmpint(count, ==, sizeof(helloworld));
+ g_assert_cmpint(eof, ==, 0);
+ QDECREF(ret);
+ g_free(cmd);
+
+ /* read (check implicit flush) */
+ cmd = g_strdup_printf("{'execute': 'guest-file-read',"
+ " 'arguments': { 'handle': %" PRId64 "} }",
+ id);
+ ret = qmp_fd(fixture->fd, cmd);
+ val = qdict_get_qdict(ret, "return");
+ count = qdict_get_int(val, "count");
+ eof = qdict_get_bool(val, "eof");
+ b64 = qdict_get_str(val, "buf-b64");
+ g_assert_cmpint(count, ==, 0);
+ g_assert(eof);
+ g_assert_cmpstr(b64, ==, "");
+ QDECREF(ret);
+ g_free(cmd);
+
+ /* seek to 0 */
+ cmd = g_strdup_printf("{'execute': 'guest-file-seek',"
+ " 'arguments': { 'handle': %" PRId64 ", "
+ " 'offset': %d, 'whence': %d } }",
+ id, 0, QGA_SEEK_SET);
+ ret = qmp_fd(fixture->fd, cmd);
+ qmp_assert_no_error(ret);
+ val = qdict_get_qdict(ret, "return");
+ count = qdict_get_int(val, "position");
+ eof = qdict_get_bool(val, "eof");
+ g_assert_cmpint(count, ==, 0);
+ g_assert(!eof);
+ QDECREF(ret);
+ g_free(cmd);
+
+ /* read */
+ cmd = g_strdup_printf("{'execute': 'guest-file-read',"
+ " 'arguments': { 'handle': %" PRId64 "} }",
+ id);
+ ret = qmp_fd(fixture->fd, cmd);
+ val = qdict_get_qdict(ret, "return");
+ count = qdict_get_int(val, "count");
+ eof = qdict_get_bool(val, "eof");
+ b64 = qdict_get_str(val, "buf-b64");
+ g_assert_cmpint(count, ==, sizeof(helloworld));
+ g_assert(eof);
+ g_assert_cmpstr(b64, ==, enc);
+ QDECREF(ret);
+ g_free(cmd);
+ g_free(enc);
+
+ /* close */
+ cmd = g_strdup_printf("{'execute': 'guest-file-close',"
+ " 'arguments': {'handle': %" PRId64 "} }",
+ id);
+ ret = qmp_fd(fixture->fd, cmd);
+ QDECREF(ret);
+ g_free(cmd);
+}
+
+static void test_qga_get_time(gconstpointer fix)
+{
+ const TestFixture *fixture = fix;
+ QDict *ret;
+ int64_t time;
+
+ ret = qmp_fd(fixture->fd, "{'execute': 'guest-get-time'}");
+ g_assert_nonnull(ret);
+ qmp_assert_no_error(ret);
+
+ time = qdict_get_int(ret, "return");
+ g_assert_cmpint(time, >, 0);
+
+ QDECREF(ret);
+}
+
+static void test_qga_set_time(gconstpointer fix)
+{
+ const TestFixture *fixture = fix;
+ QDict *ret;
+ int64_t current, time;
+ gchar *cmd;
+
+ /* get current time */
+ ret = qmp_fd(fixture->fd, "{'execute': 'guest-get-time'}");
+ g_assert_nonnull(ret);
+ qmp_assert_no_error(ret);
+ current = qdict_get_int(ret, "return");
+ g_assert_cmpint(current, >, 0);
+ QDECREF(ret);
+
+ /* set some old time */
+ ret = qmp_fd(fixture->fd, "{'execute': 'guest-set-time',"
+ " 'arguments': { 'time': 1000 } }");
+ g_assert_nonnull(ret);
+ qmp_assert_no_error(ret);
+ QDECREF(ret);
+
+ /* check old time */
+ ret = qmp_fd(fixture->fd, "{'execute': 'guest-get-time'}");
+ g_assert_nonnull(ret);
+ qmp_assert_no_error(ret);
+ time = qdict_get_int(ret, "return");
+ g_assert_cmpint(time / 1000, <, G_USEC_PER_SEC * 10);
+ QDECREF(ret);
+
+ /* set back current time */
+ cmd = g_strdup_printf("{'execute': 'guest-set-time',"
+ " 'arguments': { 'time': %" PRId64 " } }",
+ current + time * 1000);
+ ret = qmp_fd(fixture->fd, cmd);
+ g_free(cmd);
+ g_assert_nonnull(ret);
+ qmp_assert_no_error(ret);
+ QDECREF(ret);
+}
+
+static void test_qga_fstrim(gconstpointer fix)
+{
+ const TestFixture *fixture = fix;
+ QDict *ret;
+ QList *list;
+ const QListEntry *entry;
+
+ ret = qmp_fd(fixture->fd, "{'execute': 'guest-fstrim',"
+ " arguments: { minimum: 4194304 } }");
+ g_assert_nonnull(ret);
+ qmp_assert_no_error(ret);
+ list = qdict_get_qlist(ret, "return");
+ entry = qlist_first(list);
+ g_assert(qdict_haskey(qobject_to_qdict(entry->value), "paths"));
+
+ QDECREF(ret);
+}
+
+static void test_qga_blacklist(gconstpointer data)
+{
+ TestFixture fix;
+ QDict *ret, *error;
+ const gchar *class, *desc;
+
+ fixture_setup(&fix, "-b guest-ping,guest-get-time");
+
+ /* check blacklist */
+ ret = qmp_fd(fix.fd, "{'execute': 'guest-ping'}");
+ g_assert_nonnull(ret);
+ error = qdict_get_qdict(ret, "error");
+ class = qdict_get_try_str(error, "class");
+ desc = qdict_get_try_str(error, "desc");
+ g_assert_cmpstr(class, ==, "GenericError");
+ g_assert_nonnull(g_strstr_len(desc, -1, "has been disabled"));
+ QDECREF(ret);
+
+ ret = qmp_fd(fix.fd, "{'execute': 'guest-get-time'}");
+ g_assert_nonnull(ret);
+ error = qdict_get_qdict(ret, "error");
+ class = qdict_get_try_str(error, "class");
+ desc = qdict_get_try_str(error, "desc");
+ g_assert_cmpstr(class, ==, "GenericError");
+ g_assert_nonnull(g_strstr_len(desc, -1, "has been disabled"));
+ QDECREF(ret);
+
+ /* check something work */
+ ret = qmp_fd(fix.fd, "{'execute': 'guest-get-fsinfo'}");
+ qmp_assert_no_error(ret);
+ QDECREF(ret);
+
+ fixture_tear_down(&fix, NULL);
+}
+
+static void test_qga_config(gconstpointer data)
+{
+ GError *error = NULL;
+ char *cwd, *cmd, *out, *err, *str, **strv, *conf, **argv = NULL;
+ char *env[2];
+ int status, tmp;
+ gsize n;
+ GKeyFile *kf;
+ const char *qga_config =
+ "[general]\n"
+ "daemon=false\n"
+ "method=virtio-serial\n"
+ "path=/path/to/org.qemu.guest_agent.0\n"
+ "pidfile=/var/foo/qemu-ga.pid\n"
+ "statedir=/var/state\n"
+ "verbose=true\n"
+ "blacklist=guest-ping;guest-get-time\n";
+
+ tmp = g_file_open_tmp(NULL, &conf, &error);
+ g_assert_no_error(error);
+ g_assert_cmpint(tmp, >=, 0);
+ g_assert_cmpstr(conf, !=, "");
+
+ g_file_set_contents(conf, qga_config, -1, &error);
+ g_assert_no_error(error);
+
+ cwd = g_get_current_dir();
+ cmd = g_strdup_printf("%s%cqemu-ga -D",
+ cwd, G_DIR_SEPARATOR);
+ g_shell_parse_argv(cmd, NULL, &argv, &error);
+ g_assert_no_error(error);
+
+ env[0] = g_strdup_printf("QGA_CONF=%s", conf);
+ env[1] = NULL;
+ g_spawn_sync(NULL, argv, env, 0,
+ NULL, NULL, &out, &err, &status, &error);
+ g_assert_no_error(error);
+ g_assert_cmpstr(err, ==, "");
+ g_assert_cmpint(status, ==, 0);
+
+ kf = g_key_file_new();
+ g_key_file_load_from_data(kf, out, -1, G_KEY_FILE_NONE, &error);
+ g_assert_no_error(error);
+
+ str = g_key_file_get_start_group(kf);
+ g_assert_cmpstr(str, ==, "general");
+ g_free(str);
+
+ g_assert_false(g_key_file_get_boolean(kf, "general", "daemon", &error));
+ g_assert_no_error(error);
+
+ str = g_key_file_get_string(kf, "general", "method", &error);
+ g_assert_no_error(error);
+ g_assert_cmpstr(str, ==, "virtio-serial");
+ g_free(str);
+
+ str = g_key_file_get_string(kf, "general", "path", &error);
+ g_assert_no_error(error);
+ g_assert_cmpstr(str, ==, "/path/to/org.qemu.guest_agent.0");
+ g_free(str);
+
+ str = g_key_file_get_string(kf, "general", "pidfile", &error);
+ g_assert_no_error(error);
+ g_assert_cmpstr(str, ==, "/var/foo/qemu-ga.pid");
+ g_free(str);
+
+ str = g_key_file_get_string(kf, "general", "statedir", &error);
+ g_assert_no_error(error);
+ g_assert_cmpstr(str, ==, "/var/state");
+ g_free(str);
+
+ g_assert_true(g_key_file_get_boolean(kf, "general", "verbose", &error));
+ g_assert_no_error(error);
+
+ strv = g_key_file_get_string_list(kf, "general", "blacklist", &n, &error);
+ g_assert_cmpint(n, ==, 2);
+#if GLIB_CHECK_VERSION(2, 44, 0)
+ g_assert_true(g_strv_contains((const char * const *)strv,
+ "guest-ping"));
+ g_assert_true(g_strv_contains((const char * const *)strv,
+ "guest-get-time"));
+#endif
+ g_assert_no_error(error);
+ g_strfreev(strv);
+
+ g_free(out);
+ g_free(err);
+ g_free(conf);
+ g_free(env[0]);
+ g_key_file_free(kf);
+
+ close(tmp);
+}
+
+static void test_qga_fsfreeze_status(gconstpointer fix)
+{
+ const TestFixture *fixture = fix;
+ QDict *ret;
+ const gchar *status;
+
+ ret = qmp_fd(fixture->fd, "{'execute': 'guest-fsfreeze-status'}");
+ g_assert_nonnull(ret);
+ qmp_assert_no_error(ret);
+
+ status = qdict_get_try_str(ret, "return");
+ g_assert_cmpstr(status, ==, "thawed");
+
+ QDECREF(ret);
+}
+
+static void test_qga_fsfreeze_and_thaw(gconstpointer fix)
+{
+ const TestFixture *fixture = fix;
+ QDict *ret;
+ const gchar *status;
+
+ ret = qmp_fd(fixture->fd, "{'execute': 'guest-fsfreeze-freeze'}");
+ g_assert_nonnull(ret);
+ qmp_assert_no_error(ret);
+ QDECREF(ret);
+
+ ret = qmp_fd(fixture->fd, "{'execute': 'guest-fsfreeze-status'}");
+ g_assert_nonnull(ret);
+ qmp_assert_no_error(ret);
+ status = qdict_get_try_str(ret, "return");
+ g_assert_cmpstr(status, ==, "frozen");
+ QDECREF(ret);
+
+ ret = qmp_fd(fixture->fd, "{'execute': 'guest-fsfreeze-thaw'}");
+ g_assert_nonnull(ret);
+ qmp_assert_no_error(ret);
+ QDECREF(ret);
+}
+
+int main(int argc, char **argv)
+{
+ TestFixture fix;
+ int ret;
+
+ setlocale (LC_ALL, "");
+ g_test_init(&argc, &argv, NULL);
+ fixture_setup(&fix, NULL);
+
+ g_test_add_data_func("/qga/sync-delimited", &fix, test_qga_sync_delimited);
+ g_test_add_data_func("/qga/sync", &fix, test_qga_sync);
+ g_test_add_data_func("/qga/ping", &fix, test_qga_ping);
+ g_test_add_data_func("/qga/info", &fix, test_qga_info);
+ g_test_add_data_func("/qga/network-get-interfaces", &fix,
+ test_qga_network_get_interfaces);
+ g_test_add_data_func("/qga/get-vcpus", &fix, test_qga_get_vcpus);
+ g_test_add_data_func("/qga/get-fsinfo", &fix, test_qga_get_fsinfo);
+ g_test_add_data_func("/qga/get-memory-block-info", &fix,
+ test_qga_get_memory_block_info);
+ g_test_add_data_func("/qga/get-memory-blocks", &fix,
+ test_qga_get_memory_blocks);
+ g_test_add_data_func("/qga/file-ops", &fix, test_qga_file_ops);
+ g_test_add_data_func("/qga/file-write-read", &fix, test_qga_file_write_read);
+ g_test_add_data_func("/qga/get-time", &fix, test_qga_get_time);
+ g_test_add_data_func("/qga/invalid-cmd", &fix, test_qga_invalid_cmd);
+ g_test_add_data_func("/qga/fsfreeze-status", &fix,
+ test_qga_fsfreeze_status);
+
+ g_test_add_data_func("/qga/blacklist", NULL, test_qga_blacklist);
+ g_test_add_data_func("/qga/config", NULL, test_qga_config);
+
+ if (g_getenv("QGA_TEST_SIDE_EFFECTING")) {
+ g_test_add_data_func("/qga/fsfreeze-and-thaw", &fix,
+ test_qga_fsfreeze_and_thaw);
+ g_test_add_data_func("/qga/set-time", &fix, test_qga_set_time);
+ g_test_add_data_func("/qga/fstrim", &fix, test_qga_fstrim);
+ }
+
+ ret = g_test_run();
+
+ fixture_tear_down(&fix, NULL);
+
+ return ret;
+}
diff --git a/tests/test-qmp-commands.c b/tests/test-qmp-commands.c
index 9918f2306..888fb5ffe 100644
--- a/tests/test-qmp-commands.c
+++ b/tests/test-qmp-commands.c
@@ -25,11 +25,9 @@ UserDefTwo *qmp_user_def_cmd2(UserDefOne *ud1a,
UserDefOne *ud1d = g_malloc0(sizeof(UserDefOne));
ud1c->string = strdup(ud1a->string);
- ud1c->base = g_new0(UserDefZero, 1);
- ud1c->base->integer = ud1a->base->integer;
+ ud1c->integer = ud1a->integer;
ud1d->string = strdup(has_udb1 ? ud1b->string : "blah0");
- ud1d->base = g_new0(UserDefZero, 1);
- ud1d->base->integer = has_udb1 ? ud1b->base->integer : 0;
+ ud1d->integer = has_udb1 ? ud1b->integer : 0;
ret = g_new0(UserDefTwo, 1);
ret->string0 = strdup("blah1");
@@ -46,11 +44,16 @@ UserDefTwo *qmp_user_def_cmd2(UserDefOne *ud1a,
return ret;
}
-int64_t qmp_user_def_cmd3(int64_t a, bool has_b, int64_t b, Error **errp)
+int64_t qmp_guest_get_time(int64_t a, bool has_b, int64_t b, Error **errp)
{
return a + (has_b ? b : 0);
}
+QObject *qmp_guest_sync(QObject *arg, Error **errp)
+{
+ return arg;
+}
+
__org_qemu_x_Union1 *qmp___org_qemu_x_command(__org_qemu_x_EnumList *a,
__org_qemu_x_StructList *b,
__org_qemu_x_Union2 *c,
@@ -59,8 +62,8 @@ __org_qemu_x_Union1 *qmp___org_qemu_x_command(__org_qemu_x_EnumList *a,
{
__org_qemu_x_Union1 *ret = g_new0(__org_qemu_x_Union1, 1);
- ret->kind = ORG_QEMU_X_UNION1_KIND___ORG_QEMU_X_BRANCH;
- ret->__org_qemu_x_branch = strdup("blah1");
+ ret->type = ORG_QEMU_X_UNION1_KIND___ORG_QEMU_X_BRANCH;
+ ret->u.__org_qemu_x_branch = strdup("blah1");
return ret;
}
@@ -155,7 +158,7 @@ static void test_dispatch_cmd_io(void)
qdict_put(args3, "a", qint_from_int(66));
qdict_put(req, "arguments", args3);
- qdict_put(req, "execute", qstring_from_str("user_def_cmd3"));
+ qdict_put(req, "execute", qstring_from_str("guest-get-time"));
ret3 = qobject_to_qint(test_qmp_dispatch(req));
assert(qint_get_int(ret3) == 66);
@@ -171,20 +174,17 @@ static void test_dealloc_types(void)
UserDefOneList *ud1list;
ud1test = g_malloc0(sizeof(UserDefOne));
- ud1test->base = g_new0(UserDefZero, 1);
- ud1test->base->integer = 42;
+ ud1test->integer = 42;
ud1test->string = g_strdup("hi there 42");
qapi_free_UserDefOne(ud1test);
ud1a = g_malloc0(sizeof(UserDefOne));
- ud1a->base = g_new0(UserDefZero, 1);
- ud1a->base->integer = 43;
+ ud1a->integer = 43;
ud1a->string = g_strdup("hi there 43");
ud1b = g_malloc0(sizeof(UserDefOne));
- ud1b->base = g_new0(UserDefZero, 1);
- ud1b->base->integer = 44;
+ ud1b->integer = 44;
ud1b->string = g_strdup("hi there 44");
ud1list = g_malloc0(sizeof(UserDefOneList));
@@ -225,8 +225,7 @@ static void test_dealloc_partial(void)
assert(ud2->dict1 == NULL);
/* confirm & release construction error */
- assert(err != NULL);
- error_free(err);
+ error_free_or_abort(&err);
/* tear down partial object */
qapi_free_UserDefTwo(ud2);
diff --git a/tests/test-qmp-event.c b/tests/test-qmp-event.c
index 1ee40e148..035c65cfd 100644
--- a/tests/test-qmp-event.c
+++ b/tests/test-qmp-event.c
@@ -94,7 +94,7 @@ static bool qdict_cmp_simple(QDict *a, QDict *b)
/* This function is hooked as final emit function, which can verify the
correctness. */
-static void event_test_emit(TEST_QAPIEvent event, QDict *d, Error **errp)
+static void event_test_emit(test_QAPIEvent event, QDict *d, Error **errp)
{
QObject *obj;
QDict *t;
@@ -179,9 +179,7 @@ static void test_event_c(TestEventData *data,
QDict *d, *d_data, *d_b;
UserDefOne b;
- UserDefZero z;
- z.integer = 2;
- b.base = &z;
+ b.integer = 2;
b.string = g_strdup("test1");
b.has_enum1 = false;
@@ -209,11 +207,9 @@ static void test_event_d(TestEventData *data,
{
UserDefOne struct1;
EventStructOne a;
- UserDefZero z;
QDict *d, *d_data, *d_a, *d_struct1;
- z.integer = 2;
- struct1.base = &z;
+ struct1.integer = 2;
struct1.string = g_strdup("test1");
struct1.has_enum1 = true;
struct1.enum1 = ENUM_ONE_VALUE1;
diff --git a/tests/test-qmp-input-strict.c b/tests/test-qmp-input-strict.c
index 68f855bdf..f1c2e3ba6 100644
--- a/tests/test-qmp-input-strict.c
+++ b/tests/test-qmp-input-strict.c
@@ -19,6 +19,9 @@
#include "test-qapi-types.h"
#include "test-qapi-visit.h"
#include "qapi/qmp/types.h"
+#include "test-qmp-introspect.h"
+#include "qmp-introspect.h"
+#include "qapi-visit.h"
typedef struct TestInputVisitorData {
QObject *obj;
@@ -37,78 +40,65 @@ static void validate_teardown(TestInputVisitorData *data,
}
}
-/* This is provided instead of a test setup function so that the JSON
- string used by the tests are kept in the test functions (and not
- int main()) */
-static GCC_FMT_ATTR(2, 3)
-Visitor *validate_test_init(TestInputVisitorData *data,
- const char *json_string, ...)
+/* The various test_init functions are provided instead of a test setup
+ function so that the JSON string used by the tests are kept in the test
+ functions (and not in main()). */
+static Visitor *validate_test_init_internal(TestInputVisitorData *data,
+ const char *json_string,
+ va_list *ap)
{
Visitor *v;
- va_list ap;
- va_start(ap, json_string);
- data->obj = qobject_from_jsonv(json_string, &ap);
- va_end(ap);
+ validate_teardown(data, NULL);
- g_assert(data->obj != NULL);
+ data->obj = qobject_from_jsonv(json_string, ap);
+ g_assert(data->obj);
data->qiv = qmp_input_visitor_new_strict(data->obj);
- g_assert(data->qiv != NULL);
+ g_assert(data->qiv);
v = qmp_input_get_visitor(data->qiv);
- g_assert(v != NULL);
+ g_assert(v);
return v;
}
-typedef struct TestStruct
-{
- int64_t integer;
- bool boolean;
- char *string;
-} TestStruct;
-
-static void visit_type_TestStruct(Visitor *v, TestStruct **obj,
- const char *name, Error **errp)
+static GCC_FMT_ATTR(2, 3)
+Visitor *validate_test_init(TestInputVisitorData *data,
+ const char *json_string, ...)
{
- Error *err = NULL;
+ Visitor *v;
+ va_list ap;
- visit_start_struct(v, (void **)obj, "TestStruct", name, sizeof(TestStruct),
- &err);
- if (err) {
- goto out;
- }
+ va_start(ap, json_string);
+ v = validate_test_init_internal(data, json_string, &ap);
+ va_end(ap);
+ return v;
+}
- visit_type_int(v, &(*obj)->integer, "integer", &err);
- if (err) {
- goto out_end;
- }
- visit_type_bool(v, &(*obj)->boolean, "boolean", &err);
- if (err) {
- goto out_end;
- }
- visit_type_str(v, &(*obj)->string, "string", &err);
-
-out_end:
- error_propagate(errp, err);
- err = NULL;
- visit_end_struct(v, &err);
-out:
- error_propagate(errp, err);
+/* similar to validate_test_init(), but does not expect a string
+ * literal/format json_string argument and so can be used for
+ * programatically generated strings (and we can't pass in programatically
+ * generated strings via %s format parameters since qobject_from_jsonv()
+ * will wrap those in double-quotes and treat the entire object as a
+ * string)
+ */
+static Visitor *validate_test_init_raw(TestInputVisitorData *data,
+ const char *json_string)
+{
+ return validate_test_init_internal(data, json_string, NULL);
}
+
static void test_validate_struct(TestInputVisitorData *data,
const void *unused)
{
TestStruct *p = NULL;
- Error *err = NULL;
Visitor *v;
v = validate_test_init(data, "{ 'integer': -42, 'boolean': true, 'string': 'foo' }");
- visit_type_TestStruct(v, &p, NULL, &err);
- g_assert(!err);
+ visit_type_TestStruct(v, &p, NULL, &error_abort);
g_free(p->string);
g_free(p);
}
@@ -117,7 +107,6 @@ static void test_validate_struct_nested(TestInputVisitorData *data,
const void *unused)
{
UserDefTwo *udp = NULL;
- Error *err = NULL;
Visitor *v;
v = validate_test_init(data, "{ 'string0': 'string0', "
@@ -125,8 +114,7 @@ static void test_validate_struct_nested(TestInputVisitorData *data,
"'dict2': { 'userdef': { 'integer': 42, "
"'string': 'string' }, 'string': 'string2'}}}");
- visit_type_UserDefTwo(v, &udp, NULL, &err);
- g_assert(!err);
+ visit_type_UserDefTwo(v, &udp, NULL, &error_abort);
qapi_free_UserDefTwo(udp);
}
@@ -134,13 +122,11 @@ static void test_validate_list(TestInputVisitorData *data,
const void *unused)
{
UserDefOneList *head = NULL;
- Error *err = NULL;
Visitor *v;
v = validate_test_init(data, "[ { 'string': 'string0', 'integer': 42 }, { 'string': 'string1', 'integer': 43 }, { 'string': 'string2', 'integer': 44 } ]");
- visit_type_UserDefOneList(v, &head, NULL, &err);
- g_assert(!err);
+ visit_type_UserDefOneList(v, &head, NULL, &error_abort);
qapi_free_UserDefOneList(head);
}
@@ -149,12 +135,10 @@ static void test_validate_union_native_list(TestInputVisitorData *data,
{
UserDefNativeListUnion *tmp = NULL;
Visitor *v;
- Error *err = NULL;
v = validate_test_init(data, "{ 'type': 'integer', 'data' : [ 1, 2 ] }");
- visit_type_UserDefNativeListUnion(v, &tmp, NULL, &err);
- g_assert(!err);
+ visit_type_UserDefNativeListUnion(v, &tmp, NULL, &error_abort);
qapi_free_UserDefNativeListUnion(tmp);
}
@@ -163,16 +147,14 @@ static void test_validate_union_flat(TestInputVisitorData *data,
{
UserDefFlatUnion *tmp = NULL;
Visitor *v;
- Error *err = NULL;
v = validate_test_init(data,
"{ 'enum1': 'value1', "
+ "'integer': 41, "
"'string': 'str', "
"'boolean': true }");
- /* TODO when generator bug is fixed, add 'integer': 41 */
- visit_type_UserDefFlatUnion(v, &tmp, NULL, &err);
- g_assert(!err);
+ visit_type_UserDefFlatUnion(v, &tmp, NULL, &error_abort);
qapi_free_UserDefFlatUnion(tmp);
}
@@ -181,12 +163,10 @@ static void test_validate_alternate(TestInputVisitorData *data,
{
UserDefAlternate *tmp = NULL;
Visitor *v;
- Error *err = NULL;
v = validate_test_init(data, "42");
- visit_type_UserDefAlternate(v, &tmp, NULL, &err);
- g_assert(!err);
+ visit_type_UserDefAlternate(v, &tmp, NULL, &error_abort);
qapi_free_UserDefAlternate(tmp);
}
@@ -200,7 +180,7 @@ static void test_validate_fail_struct(TestInputVisitorData *data,
v = validate_test_init(data, "{ 'integer': -42, 'boolean': true, 'string': 'foo', 'extra': 42 }");
visit_type_TestStruct(v, &p, NULL, &err);
- g_assert(err);
+ error_free_or_abort(&err);
if (p) {
g_free(p->string);
}
@@ -217,7 +197,7 @@ static void test_validate_fail_struct_nested(TestInputVisitorData *data,
v = validate_test_init(data, "{ 'string0': 'string0', 'dict1': { 'string1': 'string1', 'dict2': { 'userdef1': { 'integer': 42, 'string': 'string', 'extra': [42, 23, {'foo':'bar'}] }, 'string2': 'string2'}}}");
visit_type_UserDefTwo(v, &udp, NULL, &err);
- g_assert(err);
+ error_free_or_abort(&err);
qapi_free_UserDefTwo(udp);
}
@@ -231,7 +211,7 @@ static void test_validate_fail_list(TestInputVisitorData *data,
v = validate_test_init(data, "[ { 'string': 'string0', 'integer': 42 }, { 'string': 'string1', 'integer': 43 }, { 'string': 'string2', 'integer': 44, 'extra': 'ggg' } ]");
visit_type_UserDefOneList(v, &head, NULL, &err);
- g_assert(err);
+ error_free_or_abort(&err);
qapi_free_UserDefOneList(head);
}
@@ -246,7 +226,7 @@ static void test_validate_fail_union_native_list(TestInputVisitorData *data,
"{ 'type': 'integer', 'data' : [ 'string' ] }");
visit_type_UserDefNativeListUnion(v, &tmp, NULL, &err);
- g_assert(err);
+ error_free_or_abort(&err);
qapi_free_UserDefNativeListUnion(tmp);
}
@@ -260,7 +240,7 @@ static void test_validate_fail_union_flat(TestInputVisitorData *data,
v = validate_test_init(data, "{ 'string': 'c', 'integer': 41, 'boolean': true }");
visit_type_UserDefFlatUnion(v, &tmp, NULL, &err);
- g_assert(err);
+ error_free_or_abort(&err);
qapi_free_UserDefFlatUnion(tmp);
}
@@ -272,10 +252,10 @@ static void test_validate_fail_union_flat_no_discrim(TestInputVisitorData *data,
Visitor *v;
/* test situation where discriminator field ('enum1' here) is missing */
- v = validate_test_init(data, "{ 'string': 'c', 'string1': 'd', 'string2': 'e' }");
+ v = validate_test_init(data, "{ 'integer': 42, 'string': 'c', 'string1': 'd', 'string2': 'e' }");
visit_type_UserDefFlatUnion2(v, &tmp, NULL, &err);
- g_assert(err);
+ error_free_or_abort(&err);
qapi_free_UserDefFlatUnion2(tmp);
}
@@ -289,10 +269,31 @@ static void test_validate_fail_alternate(TestInputVisitorData *data,
v = validate_test_init(data, "3.14");
visit_type_UserDefAlternate(v, &tmp, NULL, &err);
- g_assert(err);
+ error_free_or_abort(&err);
qapi_free_UserDefAlternate(tmp);
}
+static void do_test_validate_qmp_introspect(TestInputVisitorData *data,
+ const char *schema_json)
+{
+ SchemaInfoList *schema = NULL;
+ Visitor *v;
+
+ v = validate_test_init_raw(data, schema_json);
+
+ visit_type_SchemaInfoList(v, &schema, NULL, &error_abort);
+ g_assert(schema);
+
+ qapi_free_SchemaInfoList(schema);
+}
+
+static void test_validate_qmp_introspect(TestInputVisitorData *data,
+ const void *unused)
+{
+ do_test_validate_qmp_introspect(data, test_qmp_schema_json);
+ do_test_validate_qmp_introspect(data, qmp_schema_json);
+}
+
static void validate_test_add(const char *testpath,
TestInputVisitorData *data,
void (*test_func)(TestInputVisitorData *data, const void *user_data))
@@ -333,6 +334,8 @@ int main(int argc, char **argv)
&testdata, test_validate_fail_alternate);
validate_test_add("/visitor/input-strict/fail/union-native-list",
&testdata, test_validate_fail_union_native_list);
+ validate_test_add("/visitor/input-strict/pass/qmp-introspect",
+ &testdata, test_validate_qmp_introspect);
g_test_run();
diff --git a/tests/test-qmp-input-visitor.c b/tests/test-qmp-input-visitor.c
index b96195309..d48ebdd62 100644
--- a/tests/test-qmp-input-visitor.c
+++ b/tests/test-qmp-input-visitor.c
@@ -36,28 +36,39 @@ static void visitor_input_teardown(TestInputVisitorData *data,
}
}
-/* This is provided instead of a test setup function so that the JSON
- string used by the tests are kept in the test functions (and not
- int main()) */
-static GCC_FMT_ATTR(2, 3)
-Visitor *visitor_input_test_init(TestInputVisitorData *data,
- const char *json_string, ...)
+/* The various test_init functions are provided instead of a test setup
+ function so that the JSON string used by the tests are kept in the test
+ functions (and not in main()). */
+static Visitor *visitor_input_test_init_internal(TestInputVisitorData *data,
+ const char *json_string,
+ va_list *ap)
{
Visitor *v;
- va_list ap;
- va_start(ap, json_string);
- data->obj = qobject_from_jsonv(json_string, &ap);
- va_end(ap);
+ visitor_input_teardown(data, NULL);
- g_assert(data->obj != NULL);
+ data->obj = qobject_from_jsonv(json_string, ap);
+ g_assert(data->obj);
data->qiv = qmp_input_visitor_new(data->obj);
- g_assert(data->qiv != NULL);
+ g_assert(data->qiv);
v = qmp_input_get_visitor(data->qiv);
- g_assert(v != NULL);
+ g_assert(v);
+
+ return v;
+}
+
+static GCC_FMT_ATTR(2, 3)
+Visitor *visitor_input_test_init(TestInputVisitorData *data,
+ const char *json_string, ...)
+{
+ Visitor *v;
+ va_list ap;
+ va_start(ap, json_string);
+ v = visitor_input_test_init_internal(data, json_string, &ap);
+ va_end(ap);
return v;
}
@@ -71,32 +82,18 @@ Visitor *visitor_input_test_init(TestInputVisitorData *data,
static Visitor *visitor_input_test_init_raw(TestInputVisitorData *data,
const char *json_string)
{
- Visitor *v;
-
- data->obj = qobject_from_json(json_string);
-
- g_assert(data->obj != NULL);
-
- data->qiv = qmp_input_visitor_new(data->obj);
- g_assert(data->qiv != NULL);
-
- v = qmp_input_get_visitor(data->qiv);
- g_assert(v != NULL);
-
- return v;
+ return visitor_input_test_init_internal(data, json_string, NULL);
}
static void test_visitor_in_int(TestInputVisitorData *data,
const void *unused)
{
int64_t res = 0, value = -42;
- Error *err = NULL;
Visitor *v;
v = visitor_input_test_init(data, "%" PRId64, value);
- visit_type_int(v, &res, NULL, &err);
- g_assert(!err);
+ visit_type_int(v, &res, NULL, &error_abort);
g_assert_cmpint(res, ==, value);
}
@@ -114,21 +111,18 @@ static void test_visitor_in_int_overflow(TestInputVisitorData *data,
v = visitor_input_test_init(data, "%f", DBL_MAX);
visit_type_int(v, &res, NULL, &err);
- g_assert(err);
- error_free(err);
+ error_free_or_abort(&err);
}
static void test_visitor_in_bool(TestInputVisitorData *data,
const void *unused)
{
- Error *err = NULL;
bool res = false;
Visitor *v;
v = visitor_input_test_init(data, "true");
- visit_type_bool(v, &res, NULL, &err);
- g_assert(!err);
+ visit_type_bool(v, &res, NULL, &error_abort);
g_assert_cmpint(res, ==, true);
}
@@ -136,13 +130,11 @@ static void test_visitor_in_number(TestInputVisitorData *data,
const void *unused)
{
double res = 0, value = 3.14;
- Error *err = NULL;
Visitor *v;
v = visitor_input_test_init(data, "%f", value);
- visit_type_number(v, &res, NULL, &err);
- g_assert(!err);
+ visit_type_number(v, &res, NULL, &error_abort);
g_assert_cmpfloat(res, ==, value);
}
@@ -150,13 +142,11 @@ static void test_visitor_in_string(TestInputVisitorData *data,
const void *unused)
{
char *res = NULL, *value = (char *) "Q E M U";
- Error *err = NULL;
Visitor *v;
v = visitor_input_test_init(data, "%s", value);
- visit_type_str(v, &res, NULL, &err);
- g_assert(!err);
+ visit_type_str(v, &res, NULL, &error_abort);
g_assert_cmpstr(res, ==, value);
g_free(res);
@@ -165,7 +155,6 @@ static void test_visitor_in_string(TestInputVisitorData *data,
static void test_visitor_in_enum(TestInputVisitorData *data,
const void *unused)
{
- Error *err = NULL;
Visitor *v;
EnumOne i;
@@ -174,63 +163,21 @@ static void test_visitor_in_enum(TestInputVisitorData *data,
v = visitor_input_test_init(data, "%s", EnumOne_lookup[i]);
- visit_type_EnumOne(v, &res, NULL, &err);
- g_assert(!err);
+ visit_type_EnumOne(v, &res, NULL, &error_abort);
g_assert_cmpint(i, ==, res);
-
- visitor_input_teardown(data, NULL);
}
-
- data->obj = NULL;
- data->qiv = NULL;
}
-typedef struct TestStruct
-{
- int64_t integer;
- bool boolean;
- char *string;
-} TestStruct;
-
-static void visit_type_TestStruct(Visitor *v, TestStruct **obj,
- const char *name, Error **errp)
-{
- Error *err = NULL;
-
- visit_start_struct(v, (void **)obj, "TestStruct", name, sizeof(TestStruct),
- &err);
- if (err) {
- goto out;
- }
- visit_type_int(v, &(*obj)->integer, "integer", &err);
- if (err) {
- goto out_end;
- }
- visit_type_bool(v, &(*obj)->boolean, "boolean", &err);
- if (err) {
- goto out_end;
- }
- visit_type_str(v, &(*obj)->string, "string", &err);
-
-out_end:
- error_propagate(errp, err);
- err = NULL;
- visit_end_struct(v, &err);
-out:
- error_propagate(errp, err);
-}
static void test_visitor_in_struct(TestInputVisitorData *data,
const void *unused)
{
TestStruct *p = NULL;
- Error *err = NULL;
Visitor *v;
v = visitor_input_test_init(data, "{ 'integer': -42, 'boolean': true, 'string': 'foo' }");
- visit_type_TestStruct(v, &p, NULL, &err);
- g_assert(!err);
+ visit_type_TestStruct(v, &p, NULL, &error_abort);
g_assert_cmpint(p->integer, ==, -42);
g_assert(p->boolean == true);
g_assert_cmpstr(p->string, ==, "foo");
@@ -239,17 +186,10 @@ static void test_visitor_in_struct(TestInputVisitorData *data,
g_free(p);
}
-static void check_and_free_str(char *str, const char *cmp)
-{
- g_assert_cmpstr(str, ==, cmp);
- g_free(str);
-}
-
static void test_visitor_in_struct_nested(TestInputVisitorData *data,
const void *unused)
{
UserDefTwo *udp = NULL;
- Error *err = NULL;
Visitor *v;
v = visitor_input_test_init(data, "{ 'string0': 'string0', "
@@ -257,34 +197,28 @@ static void test_visitor_in_struct_nested(TestInputVisitorData *data,
"'dict2': { 'userdef': { 'integer': 42, "
"'string': 'string' }, 'string': 'string2'}}}");
- visit_type_UserDefTwo(v, &udp, NULL, &err);
- g_assert(!err);
+ visit_type_UserDefTwo(v, &udp, NULL, &error_abort);
- check_and_free_str(udp->string0, "string0");
- check_and_free_str(udp->dict1->string1, "string1");
- g_assert_cmpint(udp->dict1->dict2->userdef->base->integer, ==, 42);
- check_and_free_str(udp->dict1->dict2->userdef->string, "string");
- check_and_free_str(udp->dict1->dict2->string, "string2");
+ g_assert_cmpstr(udp->string0, ==, "string0");
+ g_assert_cmpstr(udp->dict1->string1, ==, "string1");
+ g_assert_cmpint(udp->dict1->dict2->userdef->integer, ==, 42);
+ g_assert_cmpstr(udp->dict1->dict2->userdef->string, ==, "string");
+ g_assert_cmpstr(udp->dict1->dict2->string, ==, "string2");
g_assert(udp->dict1->has_dict3 == false);
- g_free(udp->dict1->dict2->userdef);
- g_free(udp->dict1->dict2);
- g_free(udp->dict1);
- g_free(udp);
+ qapi_free_UserDefTwo(udp);
}
static void test_visitor_in_list(TestInputVisitorData *data,
const void *unused)
{
UserDefOneList *item, *head = NULL;
- Error *err = NULL;
Visitor *v;
int i;
v = visitor_input_test_init(data, "[ { 'string': 'string0', 'integer': 42 }, { 'string': 'string1', 'integer': 43 }, { 'string': 'string2', 'integer': 44 } ]");
- visit_type_UserDefOneList(v, &head, NULL, &err);
- g_assert(!err);
+ visit_type_UserDefOneList(v, &head, NULL, &error_abort);
g_assert(head != NULL);
for (i = 0, item = head; item; item = item->next, i++) {
@@ -292,31 +226,80 @@ static void test_visitor_in_list(TestInputVisitorData *data,
snprintf(string, sizeof(string), "string%d", i);
g_assert_cmpstr(item->value->string, ==, string);
- g_assert_cmpint(item->value->base->integer, ==, 42 + i);
+ g_assert_cmpint(item->value->integer, ==, 42 + i);
}
qapi_free_UserDefOneList(head);
+ head = NULL;
+
+ /* An empty list is valid */
+ v = visitor_input_test_init(data, "[]");
+ visit_type_UserDefOneList(v, &head, NULL, &error_abort);
+ g_assert(!head);
+}
+
+static void test_visitor_in_any(TestInputVisitorData *data,
+ const void *unused)
+{
+ QObject *res = NULL;
+ Visitor *v;
+ QInt *qint;
+ QBool *qbool;
+ QString *qstring;
+ QDict *qdict;
+ QObject *qobj;
+
+ v = visitor_input_test_init(data, "-42");
+ visit_type_any(v, &res, NULL, &error_abort);
+ qint = qobject_to_qint(res);
+ g_assert(qint);
+ g_assert_cmpint(qint_get_int(qint), ==, -42);
+ qobject_decref(res);
+
+ v = visitor_input_test_init(data, "{ 'integer': -42, 'boolean': true, 'string': 'foo' }");
+ visit_type_any(v, &res, NULL, &error_abort);
+ qdict = qobject_to_qdict(res);
+ g_assert(qdict && qdict_size(qdict) == 3);
+ qobj = qdict_get(qdict, "integer");
+ g_assert(qobj);
+ qint = qobject_to_qint(qobj);
+ g_assert(qint);
+ g_assert_cmpint(qint_get_int(qint), ==, -42);
+ qobj = qdict_get(qdict, "boolean");
+ g_assert(qobj);
+ qbool = qobject_to_qbool(qobj);
+ g_assert(qbool);
+ g_assert(qbool_get_bool(qbool) == true);
+ qobj = qdict_get(qdict, "string");
+ g_assert(qobj);
+ qstring = qobject_to_qstring(qobj);
+ g_assert(qstring);
+ g_assert_cmpstr(qstring_get_str(qstring), ==, "foo");
+ qobject_decref(res);
}
static void test_visitor_in_union_flat(TestInputVisitorData *data,
const void *unused)
{
Visitor *v;
- Error *err = NULL;
UserDefFlatUnion *tmp;
+ UserDefUnionBase *base;
v = visitor_input_test_init(data,
"{ 'enum1': 'value1', "
+ "'integer': 41, "
"'string': 'str', "
"'boolean': true }");
- /* TODO when generator bug is fixed, add 'integer': 41 */
- visit_type_UserDefFlatUnion(v, &tmp, NULL, &err);
- g_assert(err == NULL);
- g_assert_cmpint(tmp->kind, ==, ENUM_ONE_VALUE1);
+ visit_type_UserDefFlatUnion(v, &tmp, NULL, &error_abort);
+ g_assert_cmpint(tmp->enum1, ==, ENUM_ONE_VALUE1);
g_assert_cmpstr(tmp->string, ==, "str");
- /* TODO g_assert_cmpint(tmp->integer, ==, 41); */
- g_assert_cmpint(tmp->value1->boolean, ==, true);
+ g_assert_cmpint(tmp->integer, ==, 41);
+ g_assert_cmpint(tmp->u.value1->boolean, ==, true);
+
+ base = qapi_UserDefFlatUnion_base(tmp);
+ g_assert(&base->enum1 == &tmp->enum1);
+
qapi_free_UserDefFlatUnion(tmp);
}
@@ -328,20 +311,117 @@ static void test_visitor_in_alternate(TestInputVisitorData *data,
UserDefAlternate *tmp;
v = visitor_input_test_init(data, "42");
+ visit_type_UserDefAlternate(v, &tmp, NULL, &error_abort);
+ g_assert_cmpint(tmp->type, ==, USER_DEF_ALTERNATE_KIND_I);
+ g_assert_cmpint(tmp->u.i, ==, 42);
+ qapi_free_UserDefAlternate(tmp);
+ v = visitor_input_test_init(data, "'string'");
+ visit_type_UserDefAlternate(v, &tmp, NULL, &error_abort);
+ g_assert_cmpint(tmp->type, ==, USER_DEF_ALTERNATE_KIND_S);
+ g_assert_cmpstr(tmp->u.s, ==, "string");
+ qapi_free_UserDefAlternate(tmp);
+
+ v = visitor_input_test_init(data, "false");
visit_type_UserDefAlternate(v, &tmp, NULL, &err);
- g_assert(err == NULL);
- g_assert_cmpint(tmp->kind, ==, USER_DEF_ALTERNATE_KIND_I);
- g_assert_cmpint(tmp->i, ==, 42);
+ error_free_or_abort(&err);
qapi_free_UserDefAlternate(tmp);
}
+static void test_visitor_in_alternate_number(TestInputVisitorData *data,
+ const void *unused)
+{
+ Visitor *v;
+ Error *err = NULL;
+ AltStrBool *asb;
+ AltStrNum *asn;
+ AltNumStr *ans;
+ AltStrInt *asi;
+ AltIntNum *ain;
+ AltNumInt *ani;
+
+ /* Parsing an int */
+
+ v = visitor_input_test_init(data, "42");
+ visit_type_AltStrBool(v, &asb, NULL, &err);
+ error_free_or_abort(&err);
+ qapi_free_AltStrBool(asb);
+
+ /* FIXME: Order of alternate should not affect semantics; asn should
+ * parse the same as ans */
+ v = visitor_input_test_init(data, "42");
+ visit_type_AltStrNum(v, &asn, NULL, &err);
+ /* FIXME g_assert_cmpint(asn->type, == ALT_STR_NUM_KIND_N); */
+ /* FIXME g_assert_cmpfloat(asn->u.n, ==, 42); */
+ error_free_or_abort(&err);
+ qapi_free_AltStrNum(asn);
+
+ v = visitor_input_test_init(data, "42");
+ visit_type_AltNumStr(v, &ans, NULL, &error_abort);
+ g_assert_cmpint(ans->type, ==, ALT_NUM_STR_KIND_N);
+ g_assert_cmpfloat(ans->u.n, ==, 42);
+ qapi_free_AltNumStr(ans);
+
+ v = visitor_input_test_init(data, "42");
+ visit_type_AltStrInt(v, &asi, NULL, &error_abort);
+ g_assert_cmpint(asi->type, ==, ALT_STR_INT_KIND_I);
+ g_assert_cmpint(asi->u.i, ==, 42);
+ qapi_free_AltStrInt(asi);
+
+ v = visitor_input_test_init(data, "42");
+ visit_type_AltIntNum(v, &ain, NULL, &error_abort);
+ g_assert_cmpint(ain->type, ==, ALT_INT_NUM_KIND_I);
+ g_assert_cmpint(ain->u.i, ==, 42);
+ qapi_free_AltIntNum(ain);
+
+ v = visitor_input_test_init(data, "42");
+ visit_type_AltNumInt(v, &ani, NULL, &error_abort);
+ g_assert_cmpint(ani->type, ==, ALT_NUM_INT_KIND_I);
+ g_assert_cmpint(ani->u.i, ==, 42);
+ qapi_free_AltNumInt(ani);
+
+ /* Parsing a double */
+
+ v = visitor_input_test_init(data, "42.5");
+ visit_type_AltStrBool(v, &asb, NULL, &err);
+ error_free_or_abort(&err);
+ qapi_free_AltStrBool(asb);
+
+ v = visitor_input_test_init(data, "42.5");
+ visit_type_AltStrNum(v, &asn, NULL, &error_abort);
+ g_assert_cmpint(asn->type, ==, ALT_STR_NUM_KIND_N);
+ g_assert_cmpfloat(asn->u.n, ==, 42.5);
+ qapi_free_AltStrNum(asn);
+
+ v = visitor_input_test_init(data, "42.5");
+ visit_type_AltNumStr(v, &ans, NULL, &error_abort);
+ g_assert_cmpint(ans->type, ==, ALT_NUM_STR_KIND_N);
+ g_assert_cmpfloat(ans->u.n, ==, 42.5);
+ qapi_free_AltNumStr(ans);
+
+ v = visitor_input_test_init(data, "42.5");
+ visit_type_AltStrInt(v, &asi, NULL, &err);
+ error_free_or_abort(&err);
+ qapi_free_AltStrInt(asi);
+
+ v = visitor_input_test_init(data, "42.5");
+ visit_type_AltIntNum(v, &ain, NULL, &error_abort);
+ g_assert_cmpint(ain->type, ==, ALT_INT_NUM_KIND_N);
+ g_assert_cmpfloat(ain->u.n, ==, 42.5);
+ qapi_free_AltIntNum(ain);
+
+ v = visitor_input_test_init(data, "42.5");
+ visit_type_AltNumInt(v, &ani, NULL, &error_abort);
+ g_assert_cmpint(ani->type, ==, ALT_NUM_INT_KIND_N);
+ g_assert_cmpfloat(ani->u.n, ==, 42.5);
+ qapi_free_AltNumInt(ani);
+}
+
static void test_native_list_integer_helper(TestInputVisitorData *data,
const void *unused,
UserDefNativeListUnionKind kind)
{
UserDefNativeListUnion *cvalue = NULL;
- Error *err = NULL;
Visitor *v;
GString *gstr_list = g_string_new("");
GString *gstr_union = g_string_new("");
@@ -358,71 +438,70 @@ static void test_native_list_integer_helper(TestInputVisitorData *data,
gstr_list->str);
v = visitor_input_test_init_raw(data, gstr_union->str);
- visit_type_UserDefNativeListUnion(v, &cvalue, NULL, &err);
- g_assert(err == NULL);
+ visit_type_UserDefNativeListUnion(v, &cvalue, NULL, &error_abort);
g_assert(cvalue != NULL);
- g_assert_cmpint(cvalue->kind, ==, kind);
+ g_assert_cmpint(cvalue->type, ==, kind);
switch (kind) {
case USER_DEF_NATIVE_LIST_UNION_KIND_INTEGER: {
intList *elem = NULL;
- for (i = 0, elem = cvalue->integer; elem; elem = elem->next, i++) {
+ for (i = 0, elem = cvalue->u.integer; elem; elem = elem->next, i++) {
g_assert_cmpint(elem->value, ==, i);
}
break;
}
case USER_DEF_NATIVE_LIST_UNION_KIND_S8: {
int8List *elem = NULL;
- for (i = 0, elem = cvalue->s8; elem; elem = elem->next, i++) {
+ for (i = 0, elem = cvalue->u.s8; elem; elem = elem->next, i++) {
g_assert_cmpint(elem->value, ==, i);
}
break;
}
case USER_DEF_NATIVE_LIST_UNION_KIND_S16: {
int16List *elem = NULL;
- for (i = 0, elem = cvalue->s16; elem; elem = elem->next, i++) {
+ for (i = 0, elem = cvalue->u.s16; elem; elem = elem->next, i++) {
g_assert_cmpint(elem->value, ==, i);
}
break;
}
case USER_DEF_NATIVE_LIST_UNION_KIND_S32: {
int32List *elem = NULL;
- for (i = 0, elem = cvalue->s32; elem; elem = elem->next, i++) {
+ for (i = 0, elem = cvalue->u.s32; elem; elem = elem->next, i++) {
g_assert_cmpint(elem->value, ==, i);
}
break;
}
case USER_DEF_NATIVE_LIST_UNION_KIND_S64: {
int64List *elem = NULL;
- for (i = 0, elem = cvalue->s64; elem; elem = elem->next, i++) {
+ for (i = 0, elem = cvalue->u.s64; elem; elem = elem->next, i++) {
g_assert_cmpint(elem->value, ==, i);
}
break;
}
case USER_DEF_NATIVE_LIST_UNION_KIND_U8: {
uint8List *elem = NULL;
- for (i = 0, elem = cvalue->u8; elem; elem = elem->next, i++) {
+ for (i = 0, elem = cvalue->u.u8; elem; elem = elem->next, i++) {
g_assert_cmpint(elem->value, ==, i);
}
break;
}
case USER_DEF_NATIVE_LIST_UNION_KIND_U16: {
uint16List *elem = NULL;
- for (i = 0, elem = cvalue->u16; elem; elem = elem->next, i++) {
+ for (i = 0, elem = cvalue->u.u16; elem; elem = elem->next, i++) {
g_assert_cmpint(elem->value, ==, i);
}
break;
}
case USER_DEF_NATIVE_LIST_UNION_KIND_U32: {
uint32List *elem = NULL;
- for (i = 0, elem = cvalue->u32; elem; elem = elem->next, i++) {
+ for (i = 0, elem = cvalue->u.u32; elem; elem = elem->next, i++) {
g_assert_cmpint(elem->value, ==, i);
}
break;
}
case USER_DEF_NATIVE_LIST_UNION_KIND_U64: {
uint64List *elem = NULL;
- for (i = 0, elem = cvalue->u64; elem; elem = elem->next, i++) {
+ for (i = 0, elem = cvalue->u.u64; elem; elem = elem->next, i++) {
g_assert_cmpint(elem->value, ==, i);
}
break;
@@ -504,7 +583,6 @@ static void test_visitor_in_native_list_bool(TestInputVisitorData *data,
{
UserDefNativeListUnion *cvalue = NULL;
boolList *elem = NULL;
- Error *err = NULL;
Visitor *v;
GString *gstr_list = g_string_new("");
GString *gstr_union = g_string_new("");
@@ -521,12 +599,11 @@ static void test_visitor_in_native_list_bool(TestInputVisitorData *data,
gstr_list->str);
v = visitor_input_test_init_raw(data, gstr_union->str);
- visit_type_UserDefNativeListUnion(v, &cvalue, NULL, &err);
- g_assert(err == NULL);
+ visit_type_UserDefNativeListUnion(v, &cvalue, NULL, &error_abort);
g_assert(cvalue != NULL);
- g_assert_cmpint(cvalue->kind, ==, USER_DEF_NATIVE_LIST_UNION_KIND_BOOLEAN);
+ g_assert_cmpint(cvalue->type, ==, USER_DEF_NATIVE_LIST_UNION_KIND_BOOLEAN);
- for (i = 0, elem = cvalue->boolean; elem; elem = elem->next, i++) {
+ for (i = 0, elem = cvalue->u.boolean; elem; elem = elem->next, i++) {
g_assert_cmpint(elem->value, ==, (i % 3 == 0) ? 1 : 0);
}
@@ -540,7 +617,6 @@ static void test_visitor_in_native_list_string(TestInputVisitorData *data,
{
UserDefNativeListUnion *cvalue = NULL;
strList *elem = NULL;
- Error *err = NULL;
Visitor *v;
GString *gstr_list = g_string_new("");
GString *gstr_union = g_string_new("");
@@ -556,12 +632,11 @@ static void test_visitor_in_native_list_string(TestInputVisitorData *data,
gstr_list->str);
v = visitor_input_test_init_raw(data, gstr_union->str);
- visit_type_UserDefNativeListUnion(v, &cvalue, NULL, &err);
- g_assert(err == NULL);
+ visit_type_UserDefNativeListUnion(v, &cvalue, NULL, &error_abort);
g_assert(cvalue != NULL);
- g_assert_cmpint(cvalue->kind, ==, USER_DEF_NATIVE_LIST_UNION_KIND_STRING);
+ g_assert_cmpint(cvalue->type, ==, USER_DEF_NATIVE_LIST_UNION_KIND_STRING);
- for (i = 0, elem = cvalue->string; elem; elem = elem->next, i++) {
+ for (i = 0, elem = cvalue->u.string; elem; elem = elem->next, i++) {
gchar str[8];
sprintf(str, "%d", i);
g_assert_cmpstr(elem->value, ==, str);
@@ -579,7 +654,6 @@ static void test_visitor_in_native_list_number(TestInputVisitorData *data,
{
UserDefNativeListUnion *cvalue = NULL;
numberList *elem = NULL;
- Error *err = NULL;
Visitor *v;
GString *gstr_list = g_string_new("");
GString *gstr_union = g_string_new("");
@@ -595,12 +669,11 @@ static void test_visitor_in_native_list_number(TestInputVisitorData *data,
gstr_list->str);
v = visitor_input_test_init_raw(data, gstr_union->str);
- visit_type_UserDefNativeListUnion(v, &cvalue, NULL, &err);
- g_assert(err == NULL);
+ visit_type_UserDefNativeListUnion(v, &cvalue, NULL, &error_abort);
g_assert(cvalue != NULL);
- g_assert_cmpint(cvalue->kind, ==, USER_DEF_NATIVE_LIST_UNION_KIND_NUMBER);
+ g_assert_cmpint(cvalue->type, ==, USER_DEF_NATIVE_LIST_UNION_KIND_NUMBER);
- for (i = 0, elem = cvalue->number; elem; elem = elem->next, i++) {
+ for (i = 0, elem = cvalue->u.number; elem; elem = elem->next, i++) {
GString *double_expected = g_string_new("");
GString *double_actual = g_string_new("");
@@ -631,16 +704,69 @@ static void test_visitor_in_errors(TestInputVisitorData *data,
TestStruct *p = NULL;
Error *err = NULL;
Visitor *v;
+ strList *q = NULL;
- v = visitor_input_test_init(data, "{ 'integer': false, 'boolean': 'foo', 'string': -42 }");
+ v = visitor_input_test_init(data, "{ 'integer': false, 'boolean': 'foo', "
+ "'string': -42 }");
visit_type_TestStruct(v, &p, NULL, &err);
- g_assert(err);
+ error_free_or_abort(&err);
+ /* FIXME - a failed parse should not leave a partially-allocated p
+ * for us to clean up; this could cause callers to leak memory. */
g_assert(p->string == NULL);
- error_free(err);
g_free(p->string);
g_free(p);
+
+ v = visitor_input_test_init(data, "[ '1', '2', false, '3' ]");
+ visit_type_strList(v, &q, NULL, &err);
+ error_free_or_abort(&err);
+ assert(q);
+ qapi_free_strList(q);
+}
+
+static void test_visitor_in_wrong_type(TestInputVisitorData *data,
+ const void *unused)
+{
+ TestStruct *p = NULL;
+ Visitor *v;
+ strList *q = NULL;
+ int64_t i;
+ Error *err = NULL;
+
+ /* Make sure arrays and structs cannot be confused */
+
+ v = visitor_input_test_init(data, "[]");
+ visit_type_TestStruct(v, &p, NULL, &err);
+ error_free_or_abort(&err);
+ g_assert(!p);
+
+ v = visitor_input_test_init(data, "{}");
+ visit_type_strList(v, &q, NULL, &err);
+ error_free_or_abort(&err);
+ assert(!q);
+
+ /* Make sure primitives and struct cannot be confused */
+
+ v = visitor_input_test_init(data, "1");
+ visit_type_TestStruct(v, &p, NULL, &err);
+ error_free_or_abort(&err);
+ g_assert(!p);
+
+ v = visitor_input_test_init(data, "{}");
+ visit_type_int(v, &i, NULL, &err);
+ error_free_or_abort(&err);
+
+ /* Make sure primitives and arrays cannot be confused */
+
+ v = visitor_input_test_init(data, "1");
+ visit_type_strList(v, &q, NULL, &err);
+ error_free_or_abort(&err);
+ assert(!q);
+
+ v = visitor_input_test_init(data, "[]");
+ visit_type_int(v, &i, NULL, &err);
+ error_free_or_abort(&err);
}
int main(int argc, char **argv)
@@ -667,12 +793,18 @@ int main(int argc, char **argv)
&in_visitor_data, test_visitor_in_struct_nested);
input_visitor_test_add("/visitor/input/list",
&in_visitor_data, test_visitor_in_list);
+ input_visitor_test_add("/visitor/input/any",
+ &in_visitor_data, test_visitor_in_any);
input_visitor_test_add("/visitor/input/union-flat",
&in_visitor_data, test_visitor_in_union_flat);
input_visitor_test_add("/visitor/input/alternate",
&in_visitor_data, test_visitor_in_alternate);
input_visitor_test_add("/visitor/input/errors",
&in_visitor_data, test_visitor_in_errors);
+ input_visitor_test_add("/visitor/input/wrong-type",
+ &in_visitor_data, test_visitor_in_wrong_type);
+ input_visitor_test_add("/visitor/input/alternate-number",
+ &in_visitor_data, test_visitor_in_alternate_number);
input_visitor_test_add("/visitor/input/native_list/int",
&in_visitor_data,
test_visitor_in_native_list_int);
diff --git a/tests/test-qmp-output-visitor.c b/tests/test-qmp-output-visitor.c
index 87ba350b4..5609bb8df 100644
--- a/tests/test-qmp-output-visitor.c
+++ b/tests/test-qmp-output-visitor.c
@@ -45,11 +45,9 @@ static void test_visitor_out_int(TestOutputVisitorData *data,
const void *unused)
{
int64_t value = -42;
- Error *err = NULL;
QObject *obj;
- visit_type_int(data->ov, &value, NULL, &err);
- g_assert(!err);
+ visit_type_int(data->ov, &value, NULL, &error_abort);
obj = qmp_output_get_qobject(data->qov);
g_assert(obj != NULL);
@@ -62,12 +60,10 @@ static void test_visitor_out_int(TestOutputVisitorData *data,
static void test_visitor_out_bool(TestOutputVisitorData *data,
const void *unused)
{
- Error *err = NULL;
bool value = true;
QObject *obj;
- visit_type_bool(data->ov, &value, NULL, &err);
- g_assert(!err);
+ visit_type_bool(data->ov, &value, NULL, &error_abort);
obj = qmp_output_get_qobject(data->qov);
g_assert(obj != NULL);
@@ -81,11 +77,9 @@ static void test_visitor_out_number(TestOutputVisitorData *data,
const void *unused)
{
double value = 3.14;
- Error *err = NULL;
QObject *obj;
- visit_type_number(data->ov, &value, NULL, &err);
- g_assert(!err);
+ visit_type_number(data->ov, &value, NULL, &error_abort);
obj = qmp_output_get_qobject(data->qov);
g_assert(obj != NULL);
@@ -99,11 +93,9 @@ static void test_visitor_out_string(TestOutputVisitorData *data,
const void *unused)
{
char *string = (char *) "Q E M U";
- Error *err = NULL;
QObject *obj;
- visit_type_str(data->ov, &string, NULL, &err);
- g_assert(!err);
+ visit_type_str(data->ov, &string, NULL, &error_abort);
obj = qmp_output_get_qobject(data->qov);
g_assert(obj != NULL);
@@ -117,12 +109,10 @@ static void test_visitor_out_no_string(TestOutputVisitorData *data,
const void *unused)
{
char *string = NULL;
- Error *err = NULL;
QObject *obj;
/* A null string should return "" */
- visit_type_str(data->ov, &string, NULL, &err);
- g_assert(!err);
+ visit_type_str(data->ov, &string, NULL, &error_abort);
obj = qmp_output_get_qobject(data->qov);
g_assert(obj != NULL);
@@ -135,13 +125,11 @@ static void test_visitor_out_no_string(TestOutputVisitorData *data,
static void test_visitor_out_enum(TestOutputVisitorData *data,
const void *unused)
{
- Error *err = NULL;
QObject *obj;
EnumOne i;
for (i = 0; i < ENUM_ONE_MAX; i++) {
- visit_type_EnumOne(data->ov, &i, "unused", &err);
- g_assert(!err);
+ visit_type_EnumOne(data->ov, &i, "unused", &error_abort);
obj = qmp_output_get_qobject(data->qov);
g_assert(obj != NULL);
@@ -166,41 +154,6 @@ static void test_visitor_out_enum_errors(TestOutputVisitorData *data,
}
}
-typedef struct TestStruct
-{
- int64_t integer;
- bool boolean;
- char *string;
-} TestStruct;
-
-static void visit_type_TestStruct(Visitor *v, TestStruct **obj,
- const char *name, Error **errp)
-{
- Error *err = NULL;
-
- visit_start_struct(v, (void **)obj, "TestStruct", name, sizeof(TestStruct),
- &err);
- if (err) {
- goto out;
- }
-
- visit_type_int(v, &(*obj)->integer, "integer", &err);
- if (err) {
- goto out_end;
- }
- visit_type_bool(v, &(*obj)->boolean, "boolean", &err);
- if (err) {
- goto out_end;
- }
- visit_type_str(v, &(*obj)->string, "string", &err);
-
-out_end:
- error_propagate(errp, err);
- err = NULL;
- visit_end_struct(v, &err);
-out:
- error_propagate(errp, err);
-}
static void test_visitor_out_struct(TestOutputVisitorData *data,
const void *unused)
@@ -209,12 +162,10 @@ static void test_visitor_out_struct(TestOutputVisitorData *data,
.boolean = false,
.string = (char *) "foo"};
TestStruct *p = &test_struct;
- Error *err = NULL;
QObject *obj;
QDict *qdict;
- visit_type_TestStruct(data->ov, &p, NULL, &err);
- g_assert(!err);
+ visit_type_TestStruct(data->ov, &p, NULL, &error_abort);
obj = qmp_output_get_qobject(data->qov);
g_assert(obj != NULL);
@@ -233,7 +184,6 @@ static void test_visitor_out_struct_nested(TestOutputVisitorData *data,
const void *unused)
{
int64_t value = 42;
- Error *err = NULL;
UserDefTwo *ud2;
QObject *obj;
QDict *qdict, *dict1, *dict2, *dict3, *userdef;
@@ -250,20 +200,17 @@ static void test_visitor_out_struct_nested(TestOutputVisitorData *data,
ud2->dict1->dict2 = g_malloc0(sizeof(*ud2->dict1->dict2));
ud2->dict1->dict2->userdef = g_new0(UserDefOne, 1);
ud2->dict1->dict2->userdef->string = g_strdup(string);
- ud2->dict1->dict2->userdef->base = g_new0(UserDefZero, 1);
- ud2->dict1->dict2->userdef->base->integer = value;
+ ud2->dict1->dict2->userdef->integer = value;
ud2->dict1->dict2->string = g_strdup(strings[2]);
ud2->dict1->dict3 = g_malloc0(sizeof(*ud2->dict1->dict3));
ud2->dict1->has_dict3 = true;
ud2->dict1->dict3->userdef = g_new0(UserDefOne, 1);
ud2->dict1->dict3->userdef->string = g_strdup(string);
- ud2->dict1->dict3->userdef->base = g_new0(UserDefZero, 1);
- ud2->dict1->dict3->userdef->base->integer = value;
+ ud2->dict1->dict3->userdef->integer = value;
ud2->dict1->dict3->string = g_strdup(strings[3]);
- visit_type_UserDefTwo(data->ov, &ud2, "unused", &err);
- g_assert(!err);
+ visit_type_UserDefTwo(data->ov, &ud2, "unused", &error_abort);
obj = qmp_output_get_qobject(data->qov);
g_assert(obj != NULL);
@@ -301,8 +248,8 @@ static void test_visitor_out_struct_errors(TestOutputVisitorData *data,
const void *unused)
{
EnumOne bad_values[] = { ENUM_ONE_MAX, -1 };
- UserDefZero b;
- UserDefOne u = { .base = &b }, *pu = &u;
+ UserDefOne u = {0};
+ UserDefOne *pu = &u;
Error *err;
int i;
@@ -316,57 +263,33 @@ static void test_visitor_out_struct_errors(TestOutputVisitorData *data,
}
}
-typedef struct TestStructList
-{
- union {
- TestStruct *value;
- uint64_t padding;
- };
- struct TestStructList *next;
-} TestStructList;
-
-static void visit_type_TestStructList(Visitor *v, TestStructList **obj,
- const char *name, Error **errp)
-{
- GenericList *i, **head = (GenericList **)obj;
-
- visit_start_list(v, name, errp);
-
- for (*head = i = visit_next_list(v, head, errp); i; i = visit_next_list(v, &i, errp)) {
- TestStructList *native_i = (TestStructList *)i;
- visit_type_TestStruct(v, &native_i->value, NULL, errp);
- }
-
- visit_end_list(v, errp);
-}
static void test_visitor_out_list(TestOutputVisitorData *data,
const void *unused)
{
- char *value_str = (char *) "list value";
+ const char *value_str = "list value";
TestStructList *p, *head = NULL;
const int max_items = 10;
bool value_bool = true;
int value_int = 10;
- Error *err = NULL;
QListEntry *entry;
QObject *obj;
QList *qlist;
int i;
+ /* Build the list in reverse order... */
for (i = 0; i < max_items; i++) {
p = g_malloc0(sizeof(*p));
p->value = g_malloc0(sizeof(*p->value));
- p->value->integer = value_int;
+ p->value->integer = value_int + (max_items - i - 1);
p->value->boolean = value_bool;
- p->value->string = value_str;
+ p->value->string = g_strdup(value_str);
p->next = head;
head = p;
}
- visit_type_TestStructList(data->ov, &head, NULL, &err);
- g_assert(!err);
+ visit_type_TestStructList(data->ov, &head, NULL, &error_abort);
obj = qmp_output_get_qobject(data->qov);
g_assert(obj != NULL);
@@ -375,6 +298,7 @@ static void test_visitor_out_list(TestOutputVisitorData *data,
qlist = qobject_to_qlist(obj);
g_assert(!qlist_empty(qlist));
+ /* ...and ensure that the visitor sees it in order */
i = 0;
QLIST_FOREACH_ENTRY(qlist, entry) {
QDict *qdict;
@@ -382,7 +306,7 @@ static void test_visitor_out_list(TestOutputVisitorData *data,
g_assert(qobject_type(entry->value) == QTYPE_QDICT);
qdict = qobject_to_qdict(entry->value);
g_assert_cmpint(qdict_size(qdict), ==, 3);
- g_assert_cmpint(qdict_get_int(qdict, "integer"), ==, value_int);
+ g_assert_cmpint(qdict_get_int(qdict, "integer"), ==, value_int + i);
g_assert_cmpint(qdict_get_bool(qdict, "boolean"), ==, value_bool);
g_assert_cmpstr(qdict_get_str(qdict, "string"), ==, value_str);
i++;
@@ -390,13 +314,7 @@ static void test_visitor_out_list(TestOutputVisitorData *data,
g_assert_cmpint(i, ==, max_items);
QDECREF(qlist);
-
- for (p = head; p;) {
- TestStructList *tmp = p->next;
- g_free(p->value);
- g_free(p);
- p = tmp;
- }
+ qapi_free_TestStructList(head);
}
static void test_visitor_out_list_qapi_free(TestOutputVisitorData *data,
@@ -416,8 +334,7 @@ static void test_visitor_out_list_qapi_free(TestOutputVisitorData *data,
p->value->dict1->dict2 = g_new0(UserDefTwoDictDict, 1);
p->value->dict1->dict2->userdef = g_new0(UserDefOne, 1);
p->value->dict1->dict2->userdef->string = g_strdup(string);
- p->value->dict1->dict2->userdef->base = g_new0(UserDefZero, 1);
- p->value->dict1->dict2->userdef->base->integer = 42;
+ p->value->dict1->dict2->userdef->integer = 42;
p->value->dict1->dict2->string = g_strdup(string);
p->value->dict1->has_dict3 = false;
@@ -428,23 +345,68 @@ static void test_visitor_out_list_qapi_free(TestOutputVisitorData *data,
qapi_free_UserDefTwoList(head);
}
+static void test_visitor_out_any(TestOutputVisitorData *data,
+ const void *unused)
+{
+ QObject *qobj;
+ QInt *qint;
+ QBool *qbool;
+ QString *qstring;
+ QDict *qdict;
+ QObject *obj;
+
+ qobj = QOBJECT(qint_from_int(-42));
+ visit_type_any(data->ov, &qobj, NULL, &error_abort);
+ obj = qmp_output_get_qobject(data->qov);
+ g_assert(obj != NULL);
+ g_assert(qobject_type(obj) == QTYPE_QINT);
+ g_assert_cmpint(qint_get_int(qobject_to_qint(obj)), ==, -42);
+ qobject_decref(obj);
+ qobject_decref(qobj);
+
+ qdict = qdict_new();
+ qdict_put(qdict, "integer", qint_from_int(-42));
+ qdict_put(qdict, "boolean", qbool_from_bool(true));
+ qdict_put(qdict, "string", qstring_from_str("foo"));
+ qobj = QOBJECT(qdict);
+ visit_type_any(data->ov, &qobj, NULL, &error_abort);
+ qobject_decref(qobj);
+ obj = qmp_output_get_qobject(data->qov);
+ g_assert(obj != NULL);
+ qdict = qobject_to_qdict(obj);
+ g_assert(qdict);
+ qobj = qdict_get(qdict, "integer");
+ g_assert(qobj);
+ qint = qobject_to_qint(qobj);
+ g_assert(qint);
+ g_assert_cmpint(qint_get_int(qint), ==, -42);
+ qobj = qdict_get(qdict, "boolean");
+ g_assert(qobj);
+ qbool = qobject_to_qbool(qobj);
+ g_assert(qbool);
+ g_assert(qbool_get_bool(qbool) == true);
+ qobj = qdict_get(qdict, "string");
+ g_assert(qobj);
+ qstring = qobject_to_qstring(qobj);
+ g_assert(qstring);
+ g_assert_cmpstr(qstring_get_str(qstring), ==, "foo");
+ qobject_decref(obj);
+}
+
static void test_visitor_out_union_flat(TestOutputVisitorData *data,
const void *unused)
{
QObject *arg;
QDict *qdict;
- Error *err = NULL;
-
UserDefFlatUnion *tmp = g_malloc0(sizeof(UserDefFlatUnion));
- tmp->kind = ENUM_ONE_VALUE1;
+ tmp->enum1 = ENUM_ONE_VALUE1;
tmp->string = g_strdup("str");
- tmp->value1 = g_malloc0(sizeof(UserDefA));
- /* TODO when generator bug is fixed: tmp->integer = 41; */
- tmp->value1->boolean = true;
+ tmp->u.value1 = g_malloc0(sizeof(UserDefA));
+ tmp->integer = 41;
+ tmp->u.value1->boolean = true;
- visit_type_UserDefFlatUnion(data->ov, &tmp, NULL, &err);
- g_assert(err == NULL);
+ visit_type_UserDefFlatUnion(data->ov, &tmp, NULL, &error_abort);
arg = qmp_output_get_qobject(data->qov);
g_assert(qobject_type(arg) == QTYPE_QDICT);
@@ -452,7 +414,7 @@ static void test_visitor_out_union_flat(TestOutputVisitorData *data,
g_assert_cmpstr(qdict_get_str(qdict, "enum1"), ==, "value1");
g_assert_cmpstr(qdict_get_str(qdict, "string"), ==, "str");
- /* TODO g_assert_cmpint(qdict_get_int(qdict, "integer"), ==, 41); */
+ g_assert_cmpint(qdict_get_int(qdict, "integer"), ==, 41);
g_assert_cmpint(qdict_get_bool(qdict, "boolean"), ==, true);
qapi_free_UserDefFlatUnion(tmp);
@@ -463,20 +425,33 @@ static void test_visitor_out_alternate(TestOutputVisitorData *data,
const void *unused)
{
QObject *arg;
- Error *err = NULL;
+ UserDefAlternate *tmp;
- UserDefAlternate *tmp = g_malloc0(sizeof(UserDefAlternate));
- tmp->kind = USER_DEF_ALTERNATE_KIND_I;
- tmp->i = 42;
+ tmp = g_new0(UserDefAlternate, 1);
+ tmp->type = USER_DEF_ALTERNATE_KIND_I;
+ tmp->u.i = 42;
- visit_type_UserDefAlternate(data->ov, &tmp, NULL, &err);
- g_assert(err == NULL);
+ visit_type_UserDefAlternate(data->ov, &tmp, NULL, &error_abort);
arg = qmp_output_get_qobject(data->qov);
g_assert(qobject_type(arg) == QTYPE_QINT);
g_assert_cmpint(qint_get_int(qobject_to_qint(arg)), ==, 42);
qapi_free_UserDefAlternate(tmp);
+ qobject_decref(arg);
+
+ tmp = g_new0(UserDefAlternate, 1);
+ tmp->type = USER_DEF_ALTERNATE_KIND_S;
+ tmp->u.s = g_strdup("hello");
+
+ visit_type_UserDefAlternate(data->ov, &tmp, NULL, &error_abort);
+ arg = qmp_output_get_qobject(data->qov);
+
+ g_assert(qobject_type(arg) == QTYPE_QSTRING);
+ g_assert_cmpstr(qstring_get_str(qobject_to_qstring(arg)), ==, "hello");
+
+ qapi_free_UserDefAlternate(tmp);
+ qobject_decref(arg);
}
static void test_visitor_out_empty(TestOutputVisitorData *data,
@@ -485,15 +460,18 @@ static void test_visitor_out_empty(TestOutputVisitorData *data,
QObject *arg;
arg = qmp_output_get_qobject(data->qov);
- g_assert(!arg);
+ g_assert(qobject_type(arg) == QTYPE_QNULL);
+ /* Check that qnull reference counting is sane */
+ g_assert(arg->refcnt == 2);
+ qobject_decref(arg);
}
static void init_native_list(UserDefNativeListUnion *cvalue)
{
int i;
- switch (cvalue->kind) {
+ switch (cvalue->type) {
case USER_DEF_NATIVE_LIST_UNION_KIND_INTEGER: {
- intList **list = &cvalue->integer;
+ intList **list = &cvalue->u.integer;
for (i = 0; i < 32; i++) {
*list = g_new0(intList, 1);
(*list)->value = i;
@@ -503,7 +481,7 @@ static void init_native_list(UserDefNativeListUnion *cvalue)
break;
}
case USER_DEF_NATIVE_LIST_UNION_KIND_S8: {
- int8List **list = &cvalue->s8;
+ int8List **list = &cvalue->u.s8;
for (i = 0; i < 32; i++) {
*list = g_new0(int8List, 1);
(*list)->value = i;
@@ -513,7 +491,7 @@ static void init_native_list(UserDefNativeListUnion *cvalue)
break;
}
case USER_DEF_NATIVE_LIST_UNION_KIND_S16: {
- int16List **list = &cvalue->s16;
+ int16List **list = &cvalue->u.s16;
for (i = 0; i < 32; i++) {
*list = g_new0(int16List, 1);
(*list)->value = i;
@@ -523,7 +501,7 @@ static void init_native_list(UserDefNativeListUnion *cvalue)
break;
}
case USER_DEF_NATIVE_LIST_UNION_KIND_S32: {
- int32List **list = &cvalue->s32;
+ int32List **list = &cvalue->u.s32;
for (i = 0; i < 32; i++) {
*list = g_new0(int32List, 1);
(*list)->value = i;
@@ -533,7 +511,7 @@ static void init_native_list(UserDefNativeListUnion *cvalue)
break;
}
case USER_DEF_NATIVE_LIST_UNION_KIND_S64: {
- int64List **list = &cvalue->s64;
+ int64List **list = &cvalue->u.s64;
for (i = 0; i < 32; i++) {
*list = g_new0(int64List, 1);
(*list)->value = i;
@@ -543,7 +521,7 @@ static void init_native_list(UserDefNativeListUnion *cvalue)
break;
}
case USER_DEF_NATIVE_LIST_UNION_KIND_U8: {
- uint8List **list = &cvalue->u8;
+ uint8List **list = &cvalue->u.u8;
for (i = 0; i < 32; i++) {
*list = g_new0(uint8List, 1);
(*list)->value = i;
@@ -553,7 +531,7 @@ static void init_native_list(UserDefNativeListUnion *cvalue)
break;
}
case USER_DEF_NATIVE_LIST_UNION_KIND_U16: {
- uint16List **list = &cvalue->u16;
+ uint16List **list = &cvalue->u.u16;
for (i = 0; i < 32; i++) {
*list = g_new0(uint16List, 1);
(*list)->value = i;
@@ -563,7 +541,7 @@ static void init_native_list(UserDefNativeListUnion *cvalue)
break;
}
case USER_DEF_NATIVE_LIST_UNION_KIND_U32: {
- uint32List **list = &cvalue->u32;
+ uint32List **list = &cvalue->u.u32;
for (i = 0; i < 32; i++) {
*list = g_new0(uint32List, 1);
(*list)->value = i;
@@ -573,7 +551,7 @@ static void init_native_list(UserDefNativeListUnion *cvalue)
break;
}
case USER_DEF_NATIVE_LIST_UNION_KIND_U64: {
- uint64List **list = &cvalue->u64;
+ uint64List **list = &cvalue->u.u64;
for (i = 0; i < 32; i++) {
*list = g_new0(uint64List, 1);
(*list)->value = i;
@@ -583,7 +561,7 @@ static void init_native_list(UserDefNativeListUnion *cvalue)
break;
}
case USER_DEF_NATIVE_LIST_UNION_KIND_BOOLEAN: {
- boolList **list = &cvalue->boolean;
+ boolList **list = &cvalue->u.boolean;
for (i = 0; i < 32; i++) {
*list = g_new0(boolList, 1);
(*list)->value = (i % 3 == 0);
@@ -593,7 +571,7 @@ static void init_native_list(UserDefNativeListUnion *cvalue)
break;
}
case USER_DEF_NATIVE_LIST_UNION_KIND_STRING: {
- strList **list = &cvalue->string;
+ strList **list = &cvalue->u.string;
for (i = 0; i < 32; i++) {
*list = g_new0(strList, 1);
(*list)->value = g_strdup_printf("%d", i);
@@ -603,7 +581,7 @@ static void init_native_list(UserDefNativeListUnion *cvalue)
break;
}
case USER_DEF_NATIVE_LIST_UNION_KIND_NUMBER: {
- numberList **list = &cvalue->number;
+ numberList **list = &cvalue->u.number;
for (i = 0; i < 32; i++) {
*list = g_new0(numberList, 1);
(*list)->value = (double)i / 3;
@@ -709,17 +687,15 @@ static void test_native_list(TestOutputVisitorData *data,
UserDefNativeListUnionKind kind)
{
UserDefNativeListUnion *cvalue = g_new0(UserDefNativeListUnion, 1);
- Error *err = NULL;
QObject *obj;
- cvalue->kind = kind;
+ cvalue->type = kind;
init_native_list(cvalue);
- visit_type_UserDefNativeListUnion(data->ov, &cvalue, NULL, &err);
- g_assert(err == NULL);
+ visit_type_UserDefNativeListUnion(data->ov, &cvalue, NULL, &error_abort);
obj = qmp_output_get_qobject(data->qov);
- check_native_list(obj, cvalue->kind);
+ check_native_list(obj, cvalue->type);
qapi_free_UserDefNativeListUnion(cvalue);
qobject_decref(obj);
}
@@ -832,6 +808,8 @@ int main(int argc, char **argv)
&out_visitor_data, test_visitor_out_struct_errors);
output_visitor_test_add("/visitor/output/list",
&out_visitor_data, test_visitor_out_list);
+ output_visitor_test_add("/visitor/output/any",
+ &out_visitor_data, test_visitor_out_any);
output_visitor_test_add("/visitor/output/list-qapi-free",
&out_visitor_data, test_visitor_out_list_qapi_free);
output_visitor_test_add("/visitor/output/union-flat",
diff --git a/tests/test-string-output-visitor.c b/tests/test-string-output-visitor.c
index 101fb27dd..fd5e67be6 100644
--- a/tests/test-string-output-visitor.c
+++ b/tests/test-string-output-visitor.c
@@ -248,39 +248,39 @@ int main(int argc, char **argv)
output_visitor_test_add("/string-visitor/output/int",
&out_visitor_data, test_visitor_out_int, false);
- output_visitor_test_add("/string-visitor/output/int",
+ output_visitor_test_add("/string-visitor/output/int-human",
&out_visitor_data, test_visitor_out_int, true);
output_visitor_test_add("/string-visitor/output/bool",
&out_visitor_data, test_visitor_out_bool, false);
- output_visitor_test_add("/string-visitor/output/bool",
+ output_visitor_test_add("/string-visitor/output/bool-human",
&out_visitor_data, test_visitor_out_bool, true);
output_visitor_test_add("/string-visitor/output/number",
&out_visitor_data, test_visitor_out_number, false);
- output_visitor_test_add("/string-visitor/output/number",
+ output_visitor_test_add("/string-visitor/output/number-human",
&out_visitor_data, test_visitor_out_number, true);
output_visitor_test_add("/string-visitor/output/string",
&out_visitor_data, test_visitor_out_string, false);
- output_visitor_test_add("/string-visitor/output/string",
+ output_visitor_test_add("/string-visitor/output/string-human",
&out_visitor_data, test_visitor_out_string, true);
output_visitor_test_add("/string-visitor/output/no-string",
&out_visitor_data, test_visitor_out_no_string,
false);
- output_visitor_test_add("/string-visitor/output/no-string",
+ output_visitor_test_add("/string-visitor/output/no-string-human",
&out_visitor_data, test_visitor_out_no_string,
true);
output_visitor_test_add("/string-visitor/output/enum",
&out_visitor_data, test_visitor_out_enum, false);
- output_visitor_test_add("/string-visitor/output/enum",
+ output_visitor_test_add("/string-visitor/output/enum-human",
&out_visitor_data, test_visitor_out_enum, true);
output_visitor_test_add("/string-visitor/output/enum-errors",
&out_visitor_data, test_visitor_out_enum_errors,
false);
- output_visitor_test_add("/string-visitor/output/enum-errors",
+ output_visitor_test_add("/string-visitor/output/enum-errors-human",
&out_visitor_data, test_visitor_out_enum_errors,
true);
output_visitor_test_add("/string-visitor/output/intList",
&out_visitor_data, test_visitor_out_intList, false);
- output_visitor_test_add("/string-visitor/output/intList",
+ output_visitor_test_add("/string-visitor/output/intList-human",
&out_visitor_data, test_visitor_out_intList, true);
g_test_run();
diff --git a/tests/test-throttle.c b/tests/test-throttle.c
index 016844546..85c9b6cee 100644
--- a/tests/test-throttle.c
+++ b/tests/test-throttle.c
@@ -329,6 +329,26 @@ static void test_is_valid(void)
test_is_valid_for_value(1, true);
}
+static void test_max_is_missing_limit(void)
+{
+ int i;
+
+ for (i = 0; i < BUCKETS_COUNT; i++) {
+ memset(&cfg, 0, sizeof(cfg));
+ cfg.buckets[i].max = 100;
+ cfg.buckets[i].avg = 0;
+ g_assert(throttle_max_is_missing_limit(&cfg));
+
+ cfg.buckets[i].max = 0;
+ cfg.buckets[i].avg = 0;
+ g_assert(!throttle_max_is_missing_limit(&cfg));
+
+ cfg.buckets[i].max = 0;
+ cfg.buckets[i].avg = 100;
+ g_assert(!throttle_max_is_missing_limit(&cfg));
+ }
+}
+
static void test_have_timer(void)
{
/* zero structures */
@@ -591,6 +611,7 @@ int main(int argc, char **argv)
g_test_add_func("/throttle/config/enabled", test_enabled);
g_test_add_func("/throttle/config/conflicting", test_conflicting_config);
g_test_add_func("/throttle/config/is_valid", test_is_valid);
+ g_test_add_func("/throttle/config/max", test_max_is_missing_limit);
g_test_add_func("/throttle/config_functions", test_config_functions);
g_test_add_func("/throttle/accounting", test_accounting);
g_test_add_func("/throttle/groups", test_groups);
diff --git a/tests/test-timed-average.c b/tests/test-timed-average.c
new file mode 100644
index 000000000..a049799b8
--- /dev/null
+++ b/tests/test-timed-average.c
@@ -0,0 +1,90 @@
+/*
+ * Timed average computation tests
+ *
+ * Copyright Nodalink, EURL. 2014
+ *
+ * Authors:
+ * Benoît Canet <benoit.canet@nodalink.com>
+ *
+ * This work is licensed under the terms of the GNU LGPL, version 2 or later.
+ * See the COPYING.LIB file in the top-level directory.
+ */
+
+#include <glib.h>
+#include <unistd.h>
+
+#include "qemu/timed-average.h"
+
+/* This is the clock for QEMU_CLOCK_VIRTUAL */
+static int64_t my_clock_value;
+
+int64_t cpu_get_clock(void)
+{
+ return my_clock_value;
+}
+
+static void account(TimedAverage *ta)
+{
+ timed_average_account(ta, 1);
+ timed_average_account(ta, 5);
+ timed_average_account(ta, 2);
+ timed_average_account(ta, 4);
+ timed_average_account(ta, 3);
+}
+
+static void test_average(void)
+{
+ TimedAverage ta;
+ uint64_t result;
+ int i;
+
+ /* we will compute some average on a period of 1 second */
+ timed_average_init(&ta, QEMU_CLOCK_VIRTUAL, NANOSECONDS_PER_SECOND);
+
+ result = timed_average_min(&ta);
+ g_assert(result == 0);
+ result = timed_average_avg(&ta);
+ g_assert(result == 0);
+ result = timed_average_max(&ta);
+ g_assert(result == 0);
+
+ for (i = 0; i < 100; i++) {
+ account(&ta);
+ result = timed_average_min(&ta);
+ g_assert(result == 1);
+ result = timed_average_avg(&ta);
+ g_assert(result == 3);
+ result = timed_average_max(&ta);
+ g_assert(result == 5);
+ my_clock_value += NANOSECONDS_PER_SECOND / 10;
+ }
+
+ my_clock_value += NANOSECONDS_PER_SECOND * 100;
+
+ result = timed_average_min(&ta);
+ g_assert(result == 0);
+ result = timed_average_avg(&ta);
+ g_assert(result == 0);
+ result = timed_average_max(&ta);
+ g_assert(result == 0);
+
+ for (i = 0; i < 100; i++) {
+ account(&ta);
+ result = timed_average_min(&ta);
+ g_assert(result == 1);
+ result = timed_average_avg(&ta);
+ g_assert(result == 3);
+ result = timed_average_max(&ta);
+ g_assert(result == 5);
+ my_clock_value += NANOSECONDS_PER_SECOND / 10;
+ }
+}
+
+int main(int argc, char **argv)
+{
+ /* tests in the same order as the header function declarations */
+ g_test_init(&argc, &argv, NULL);
+ g_test_add_func("/timed-average/average", test_average);
+ return g_test_run();
+}
+
diff --git a/tests/test-visitor-serialization.c b/tests/test-visitor-serialization.c
index fa86cae88..9f67f9e00 100644
--- a/tests/test-visitor-serialization.c
+++ b/tests/test-visitor-serialization.c
@@ -186,40 +186,6 @@ static void visit_primitive_list(Visitor *v, void **native, Error **errp)
}
}
-typedef struct TestStruct
-{
- int64_t integer;
- bool boolean;
- char *string;
-} TestStruct;
-
-static void visit_type_TestStruct(Visitor *v, TestStruct **obj,
- const char *name, Error **errp)
-{
- Error *err = NULL;
-
- visit_start_struct(v, (void **)obj, NULL, name, sizeof(TestStruct), &err);
- if (err) {
- goto out;
- }
-
- visit_type_int(v, &(*obj)->integer, "integer", &err);
- if (err) {
- goto out_end;
- }
- visit_type_bool(v, &(*obj)->boolean, "boolean", &err);
- if (err) {
- goto out_end;
- }
- visit_type_str(v, &(*obj)->string, "string", &err);
-
-out_end:
- error_propagate(errp, err);
- err = NULL;
- visit_end_struct(v, &err);
-out:
- error_propagate(errp, err);
-}
static TestStruct *struct_create(void)
{
@@ -258,15 +224,13 @@ static UserDefTwo *nested_struct_create(void)
udnp->dict1->string1 = strdup("test_string1");
udnp->dict1->dict2 = g_malloc0(sizeof(*udnp->dict1->dict2));
udnp->dict1->dict2->userdef = g_new0(UserDefOne, 1);
- udnp->dict1->dict2->userdef->base = g_new0(UserDefZero, 1);
- udnp->dict1->dict2->userdef->base->integer = 42;
+ udnp->dict1->dict2->userdef->integer = 42;
udnp->dict1->dict2->userdef->string = strdup("test_string");
udnp->dict1->dict2->string = strdup("test_string2");
udnp->dict1->dict3 = g_malloc0(sizeof(*udnp->dict1->dict3));
udnp->dict1->has_dict3 = true;
udnp->dict1->dict3->userdef = g_new0(UserDefOne, 1);
- udnp->dict1->dict3->userdef->base = g_new0(UserDefZero, 1);
- udnp->dict1->dict3->userdef->base->integer = 43;
+ udnp->dict1->dict3->userdef->integer = 43;
udnp->dict1->dict3->userdef->string = strdup("test_string");
udnp->dict1->dict3->string = strdup("test_string3");
return udnp;
@@ -278,15 +242,15 @@ static void nested_struct_compare(UserDefTwo *udnp1, UserDefTwo *udnp2)
g_assert(udnp2);
g_assert_cmpstr(udnp1->string0, ==, udnp2->string0);
g_assert_cmpstr(udnp1->dict1->string1, ==, udnp2->dict1->string1);
- g_assert_cmpint(udnp1->dict1->dict2->userdef->base->integer, ==,
- udnp2->dict1->dict2->userdef->base->integer);
+ g_assert_cmpint(udnp1->dict1->dict2->userdef->integer, ==,
+ udnp2->dict1->dict2->userdef->integer);
g_assert_cmpstr(udnp1->dict1->dict2->userdef->string, ==,
udnp2->dict1->dict2->userdef->string);
g_assert_cmpstr(udnp1->dict1->dict2->string, ==,
udnp2->dict1->dict2->string);
g_assert(udnp1->dict1->has_dict3 == udnp2->dict1->has_dict3);
- g_assert_cmpint(udnp1->dict1->dict3->userdef->base->integer, ==,
- udnp2->dict1->dict3->userdef->base->integer);
+ g_assert_cmpint(udnp1->dict1->dict3->userdef->integer, ==,
+ udnp2->dict1->dict3->userdef->integer);
g_assert_cmpstr(udnp1->dict1->dict3->userdef->string, ==,
udnp2->dict1->dict3->userdef->string);
g_assert_cmpstr(udnp1->dict1->dict3->string, ==,
@@ -338,14 +302,13 @@ static void test_primitives(gconstpointer opaque)
const SerializeOps *ops = args->ops;
PrimitiveType *pt = args->test_data;
PrimitiveType *pt_copy = g_malloc0(sizeof(*pt_copy));
- Error *err = NULL;
void *serialize_data;
pt_copy->type = pt->type;
- ops->serialize(pt, &serialize_data, visit_primitive_type, &err);
- ops->deserialize((void **)&pt_copy, serialize_data, visit_primitive_type, &err);
+ ops->serialize(pt, &serialize_data, visit_primitive_type, &error_abort);
+ ops->deserialize((void **)&pt_copy, serialize_data, visit_primitive_type,
+ &error_abort);
- g_assert(err == NULL);
g_assert(pt_copy != NULL);
if (pt->type == PTYPE_STRING) {
g_assert_cmpstr(pt->value.string, ==, pt_copy->value.string);
@@ -381,7 +344,6 @@ static void test_primitive_lists(gconstpointer opaque)
PrimitiveList pl = { .value = { NULL } };
PrimitiveList pl_copy = { .value = { NULL } };
PrimitiveList *pl_copy_ptr = &pl_copy;
- Error *err = NULL;
void *serialize_data;
void *cur_head = NULL;
int i;
@@ -528,10 +490,11 @@ static void test_primitive_lists(gconstpointer opaque)
}
}
- ops->serialize((void **)&pl, &serialize_data, visit_primitive_list, &err);
- ops->deserialize((void **)&pl_copy_ptr, serialize_data, visit_primitive_list, &err);
+ ops->serialize((void **)&pl, &serialize_data, visit_primitive_list,
+ &error_abort);
+ ops->deserialize((void **)&pl_copy_ptr, serialize_data,
+ visit_primitive_list, &error_abort);
- g_assert(err == NULL);
i = 0;
/* compare our deserialized list of primitives to the original */
@@ -688,10 +651,8 @@ static void test_primitive_lists(gconstpointer opaque)
g_assert_cmpint(i, ==, 33);
ops->cleanup(serialize_data);
- dealloc_helper(&pl, visit_primitive_list, &err);
- g_assert(!err);
- dealloc_helper(&pl_copy, visit_primitive_list, &err);
- g_assert(!err);
+ dealloc_helper(&pl, visit_primitive_list, &error_abort);
+ dealloc_helper(&pl_copy, visit_primitive_list, &error_abort);
g_free(args);
}
@@ -701,13 +662,12 @@ static void test_struct(gconstpointer opaque)
const SerializeOps *ops = args->ops;
TestStruct *ts = struct_create();
TestStruct *ts_copy = NULL;
- Error *err = NULL;
void *serialize_data;
- ops->serialize(ts, &serialize_data, visit_struct, &err);
- ops->deserialize((void **)&ts_copy, serialize_data, visit_struct, &err);
+ ops->serialize(ts, &serialize_data, visit_struct, &error_abort);
+ ops->deserialize((void **)&ts_copy, serialize_data, visit_struct,
+ &error_abort);
- g_assert(err == NULL);
struct_compare(ts, ts_copy);
struct_cleanup(ts);
@@ -723,14 +683,12 @@ static void test_nested_struct(gconstpointer opaque)
const SerializeOps *ops = args->ops;
UserDefTwo *udnp = nested_struct_create();
UserDefTwo *udnp_copy = NULL;
- Error *err = NULL;
void *serialize_data;
- ops->serialize(udnp, &serialize_data, visit_nested_struct, &err);
+ ops->serialize(udnp, &serialize_data, visit_nested_struct, &error_abort);
ops->deserialize((void **)&udnp_copy, serialize_data, visit_nested_struct,
- &err);
+ &error_abort);
- g_assert(err == NULL);
nested_struct_compare(udnp, udnp_copy);
nested_struct_cleanup(udnp);
@@ -745,7 +703,6 @@ static void test_nested_struct_list(gconstpointer opaque)
TestArgs *args = (TestArgs *) opaque;
const SerializeOps *ops = args->ops;
UserDefTwoList *listp = NULL, *tmp, *tmp_copy, *listp_copy = NULL;
- Error *err = NULL;
void *serialize_data;
int i = 0;
@@ -756,11 +713,10 @@ static void test_nested_struct_list(gconstpointer opaque)
listp = tmp;
}
- ops->serialize(listp, &serialize_data, visit_nested_struct_list, &err);
+ ops->serialize(listp, &serialize_data, visit_nested_struct_list,
+ &error_abort);
ops->deserialize((void **)&listp_copy, serialize_data,
- visit_nested_struct_list, &err);
-
- g_assert(err == NULL);
+ visit_nested_struct_list, &error_abort);
tmp = listp;
tmp_copy = listp_copy;
diff --git a/tests/test-vmstate.c b/tests/test-vmstate.c
index 1d620e04f..4d13bd09b 100644
--- a/tests/test-vmstate.c
+++ b/tests/test-vmstate.c
@@ -27,7 +27,7 @@
#include "qemu-common.h"
#include "migration/migration.h"
#include "migration/vmstate.h"
-#include "block/coroutine.h"
+#include "qemu/coroutine.h"
static char temp_file[] = "/tmp/vmst.test.XXXXXX";
static int temp_fd;
diff --git a/tests/test-xbzrle.c b/tests/test-xbzrle.c
index db93b0a3d..1cd8cb7d7 100644
--- a/tests/test-xbzrle.c
+++ b/tests/test-xbzrle.c
@@ -13,10 +13,8 @@
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
-#include <strings.h>
#include <string.h>
#include <sys/time.h>
-#include <assert.h>
#include "qemu-common.h"
#include "include/migration/migration.h"
diff --git a/tests/vhost-user-bridge.c b/tests/vhost-user-bridge.c
new file mode 100644
index 000000000..9fb09f1df
--- /dev/null
+++ b/tests/vhost-user-bridge.c
@@ -0,0 +1,1398 @@
+/*
+ * Vhost User Bridge
+ *
+ * Copyright (c) 2015 Red Hat, Inc.
+ *
+ * Authors:
+ * Victor Kaplansky <victork@redhat.com>
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or
+ * later. See the COPYING file in the top-level directory.
+ */
+
+/*
+ * TODO:
+ * - main should get parameters from the command line.
+ * - implement all request handlers. Still not implemented:
+ * vubr_get_queue_num_exec()
+ * vubr_send_rarp_exec()
+ * - test for broken requests and virtqueue.
+ * - implement features defined by Virtio 1.0 spec.
+ * - support mergeable buffers and indirect descriptors.
+ * - implement clean shutdown.
+ * - implement non-blocking writes to UDP backend.
+ * - implement polling strategy.
+ * - implement clean starting/stopping of vq processing
+ * - implement clean starting/stopping of used and buffers
+ * dirty page logging.
+ */
+
+#define _FILE_OFFSET_BITS 64
+
+#include <stddef.h>
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdint.h>
+#include <inttypes.h>
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <sys/unistd.h>
+#include <sys/mman.h>
+#include <sys/eventfd.h>
+#include <arpa/inet.h>
+#include <ctype.h>
+#include <netdb.h>
+
+#include <linux/vhost.h>
+
+#include "qemu/atomic.h"
+#include "standard-headers/linux/virtio_net.h"
+#include "standard-headers/linux/virtio_ring.h"
+
+#define VHOST_USER_BRIDGE_DEBUG 1
+
+#define DPRINT(...) \
+ do { \
+ if (VHOST_USER_BRIDGE_DEBUG) { \
+ printf(__VA_ARGS__); \
+ } \
+ } while (0)
+
+typedef void (*CallbackFunc)(int sock, void *ctx);
+
+typedef struct Event {
+ void *ctx;
+ CallbackFunc callback;
+} Event;
+
+typedef struct Dispatcher {
+ int max_sock;
+ fd_set fdset;
+ Event events[FD_SETSIZE];
+} Dispatcher;
+
+static void
+vubr_die(const char *s)
+{
+ perror(s);
+ exit(1);
+}
+
+static int
+dispatcher_init(Dispatcher *dispr)
+{
+ FD_ZERO(&dispr->fdset);
+ dispr->max_sock = -1;
+ return 0;
+}
+
+static int
+dispatcher_add(Dispatcher *dispr, int sock, void *ctx, CallbackFunc cb)
+{
+ if (sock >= FD_SETSIZE) {
+ fprintf(stderr,
+ "Error: Failed to add new event. sock %d should be less than %d\n",
+ sock, FD_SETSIZE);
+ return -1;
+ }
+
+ dispr->events[sock].ctx = ctx;
+ dispr->events[sock].callback = cb;
+
+ FD_SET(sock, &dispr->fdset);
+ if (sock > dispr->max_sock) {
+ dispr->max_sock = sock;
+ }
+ DPRINT("Added sock %d for watching. max_sock: %d\n",
+ sock, dispr->max_sock);
+ return 0;
+}
+
+/* dispatcher_remove() is not currently in use but may be useful
+ * in the future. */
+static int
+dispatcher_remove(Dispatcher *dispr, int sock)
+{
+ if (sock >= FD_SETSIZE) {
+ fprintf(stderr,
+ "Error: Failed to remove event. sock %d should be less than %d\n",
+ sock, FD_SETSIZE);
+ return -1;
+ }
+
+ FD_CLR(sock, &dispr->fdset);
+ DPRINT("Sock %d removed from dispatcher watch.\n", sock);
+ return 0;
+}
+
+/* timeout in us */
+static int
+dispatcher_wait(Dispatcher *dispr, uint32_t timeout)
+{
+ struct timeval tv;
+ tv.tv_sec = timeout / 1000000;
+ tv.tv_usec = timeout % 1000000;
+
+ fd_set fdset = dispr->fdset;
+
+ /* wait until some of sockets become readable. */
+ int rc = select(dispr->max_sock + 1, &fdset, 0, 0, &tv);
+
+ if (rc == -1) {
+ vubr_die("select");
+ }
+
+ /* Timeout */
+ if (rc == 0) {
+ return 0;
+ }
+
+ /* Now call callback for every ready socket. */
+
+ int sock;
+ for (sock = 0; sock < dispr->max_sock + 1; sock++) {
+ /* The callback on a socket can remove other sockets from the
+ * dispatcher, thus we have to check that the socket is
+ * still not removed from dispatcher's list
+ */
+ if (FD_ISSET(sock, &fdset) && FD_ISSET(sock, &dispr->fdset)) {
+ Event *e = &dispr->events[sock];
+ e->callback(sock, e->ctx);
+ }
+ }
+
+ return 0;
+}
+
+typedef struct VubrVirtq {
+ int call_fd;
+ int kick_fd;
+ uint32_t size;
+ uint16_t last_avail_index;
+ uint16_t last_used_index;
+ struct vring_desc *desc;
+ struct vring_avail *avail;
+ struct vring_used *used;
+ uint64_t log_guest_addr;
+ int enable;
+} VubrVirtq;
+
+/* Based on qemu/hw/virtio/vhost-user.c */
+
+#define VHOST_MEMORY_MAX_NREGIONS 8
+#define VHOST_USER_F_PROTOCOL_FEATURES 30
+
+#define VHOST_LOG_PAGE 4096
+
+enum VhostUserProtocolFeature {
+ VHOST_USER_PROTOCOL_F_MQ = 0,
+ VHOST_USER_PROTOCOL_F_LOG_SHMFD = 1,
+ VHOST_USER_PROTOCOL_F_RARP = 2,
+
+ VHOST_USER_PROTOCOL_F_MAX
+};
+
+#define VHOST_USER_PROTOCOL_FEATURE_MASK ((1 << VHOST_USER_PROTOCOL_F_MAX) - 1)
+
+typedef enum VhostUserRequest {
+ VHOST_USER_NONE = 0,
+ VHOST_USER_GET_FEATURES = 1,
+ VHOST_USER_SET_FEATURES = 2,
+ VHOST_USER_SET_OWNER = 3,
+ VHOST_USER_RESET_OWNER = 4,
+ VHOST_USER_SET_MEM_TABLE = 5,
+ VHOST_USER_SET_LOG_BASE = 6,
+ VHOST_USER_SET_LOG_FD = 7,
+ VHOST_USER_SET_VRING_NUM = 8,
+ VHOST_USER_SET_VRING_ADDR = 9,
+ VHOST_USER_SET_VRING_BASE = 10,
+ VHOST_USER_GET_VRING_BASE = 11,
+ VHOST_USER_SET_VRING_KICK = 12,
+ VHOST_USER_SET_VRING_CALL = 13,
+ VHOST_USER_SET_VRING_ERR = 14,
+ VHOST_USER_GET_PROTOCOL_FEATURES = 15,
+ VHOST_USER_SET_PROTOCOL_FEATURES = 16,
+ VHOST_USER_GET_QUEUE_NUM = 17,
+ VHOST_USER_SET_VRING_ENABLE = 18,
+ VHOST_USER_SEND_RARP = 19,
+ VHOST_USER_MAX
+} VhostUserRequest;
+
+typedef struct VhostUserMemoryRegion {
+ uint64_t guest_phys_addr;
+ uint64_t memory_size;
+ uint64_t userspace_addr;
+ uint64_t mmap_offset;
+} VhostUserMemoryRegion;
+
+typedef struct VhostUserMemory {
+ uint32_t nregions;
+ uint32_t padding;
+ VhostUserMemoryRegion regions[VHOST_MEMORY_MAX_NREGIONS];
+} VhostUserMemory;
+
+typedef struct VhostUserLog {
+ uint64_t mmap_size;
+ uint64_t mmap_offset;
+} VhostUserLog;
+
+typedef struct VhostUserMsg {
+ VhostUserRequest request;
+
+#define VHOST_USER_VERSION_MASK (0x3)
+#define VHOST_USER_REPLY_MASK (0x1<<2)
+ uint32_t flags;
+ uint32_t size; /* the following payload size */
+ union {
+#define VHOST_USER_VRING_IDX_MASK (0xff)
+#define VHOST_USER_VRING_NOFD_MASK (0x1<<8)
+ uint64_t u64;
+ struct vhost_vring_state state;
+ struct vhost_vring_addr addr;
+ VhostUserMemory memory;
+ VhostUserLog log;
+ } payload;
+ int fds[VHOST_MEMORY_MAX_NREGIONS];
+ int fd_num;
+} QEMU_PACKED VhostUserMsg;
+
+#define VHOST_USER_HDR_SIZE offsetof(VhostUserMsg, payload.u64)
+
+/* The version of the protocol we support */
+#define VHOST_USER_VERSION (0x1)
+
+#define MAX_NR_VIRTQUEUE (8)
+
+typedef struct VubrDevRegion {
+ /* Guest Physical address. */
+ uint64_t gpa;
+ /* Memory region size. */
+ uint64_t size;
+ /* QEMU virtual address (userspace). */
+ uint64_t qva;
+ /* Starting offset in our mmaped space. */
+ uint64_t mmap_offset;
+ /* Start address of mmaped space. */
+ uint64_t mmap_addr;
+} VubrDevRegion;
+
+typedef struct VubrDev {
+ int sock;
+ Dispatcher dispatcher;
+ uint32_t nregions;
+ VubrDevRegion regions[VHOST_MEMORY_MAX_NREGIONS];
+ VubrVirtq vq[MAX_NR_VIRTQUEUE];
+ int log_call_fd;
+ uint64_t log_size;
+ uint8_t *log_table;
+ int backend_udp_sock;
+ struct sockaddr_in backend_udp_dest;
+ int ready;
+ uint64_t features;
+} VubrDev;
+
+static const char *vubr_request_str[] = {
+ [VHOST_USER_NONE] = "VHOST_USER_NONE",
+ [VHOST_USER_GET_FEATURES] = "VHOST_USER_GET_FEATURES",
+ [VHOST_USER_SET_FEATURES] = "VHOST_USER_SET_FEATURES",
+ [VHOST_USER_SET_OWNER] = "VHOST_USER_SET_OWNER",
+ [VHOST_USER_RESET_OWNER] = "VHOST_USER_RESET_OWNER",
+ [VHOST_USER_SET_MEM_TABLE] = "VHOST_USER_SET_MEM_TABLE",
+ [VHOST_USER_SET_LOG_BASE] = "VHOST_USER_SET_LOG_BASE",
+ [VHOST_USER_SET_LOG_FD] = "VHOST_USER_SET_LOG_FD",
+ [VHOST_USER_SET_VRING_NUM] = "VHOST_USER_SET_VRING_NUM",
+ [VHOST_USER_SET_VRING_ADDR] = "VHOST_USER_SET_VRING_ADDR",
+ [VHOST_USER_SET_VRING_BASE] = "VHOST_USER_SET_VRING_BASE",
+ [VHOST_USER_GET_VRING_BASE] = "VHOST_USER_GET_VRING_BASE",
+ [VHOST_USER_SET_VRING_KICK] = "VHOST_USER_SET_VRING_KICK",
+ [VHOST_USER_SET_VRING_CALL] = "VHOST_USER_SET_VRING_CALL",
+ [VHOST_USER_SET_VRING_ERR] = "VHOST_USER_SET_VRING_ERR",
+ [VHOST_USER_GET_PROTOCOL_FEATURES] = "VHOST_USER_GET_PROTOCOL_FEATURES",
+ [VHOST_USER_SET_PROTOCOL_FEATURES] = "VHOST_USER_SET_PROTOCOL_FEATURES",
+ [VHOST_USER_GET_QUEUE_NUM] = "VHOST_USER_GET_QUEUE_NUM",
+ [VHOST_USER_SET_VRING_ENABLE] = "VHOST_USER_SET_VRING_ENABLE",
+ [VHOST_USER_SEND_RARP] = "VHOST_USER_SEND_RARP",
+ [VHOST_USER_MAX] = "VHOST_USER_MAX",
+};
+
+static void
+print_buffer(uint8_t *buf, size_t len)
+{
+ int i;
+ printf("Raw buffer:\n");
+ for (i = 0; i < len; i++) {
+ if (i % 16 == 0) {
+ printf("\n");
+ }
+ if (i % 4 == 0) {
+ printf(" ");
+ }
+ printf("%02x ", buf[i]);
+ }
+ printf("\n............................................................\n");
+}
+
+/* Translate guest physical address to our virtual address. */
+static uint64_t
+gpa_to_va(VubrDev *dev, uint64_t guest_addr)
+{
+ int i;
+
+ /* Find matching memory region. */
+ for (i = 0; i < dev->nregions; i++) {
+ VubrDevRegion *r = &dev->regions[i];
+
+ if ((guest_addr >= r->gpa) && (guest_addr < (r->gpa + r->size))) {
+ return guest_addr - r->gpa + r->mmap_addr + r->mmap_offset;
+ }
+ }
+
+ assert(!"address not found in regions");
+ return 0;
+}
+
+/* Translate qemu virtual address to our virtual address. */
+static uint64_t
+qva_to_va(VubrDev *dev, uint64_t qemu_addr)
+{
+ int i;
+
+ /* Find matching memory region. */
+ for (i = 0; i < dev->nregions; i++) {
+ VubrDevRegion *r = &dev->regions[i];
+
+ if ((qemu_addr >= r->qva) && (qemu_addr < (r->qva + r->size))) {
+ return qemu_addr - r->qva + r->mmap_addr + r->mmap_offset;
+ }
+ }
+
+ assert(!"address not found in regions");
+ return 0;
+}
+
+static void
+vubr_message_read(int conn_fd, VhostUserMsg *vmsg)
+{
+ char control[CMSG_SPACE(VHOST_MEMORY_MAX_NREGIONS * sizeof(int))] = { };
+ struct iovec iov = {
+ .iov_base = (char *)vmsg,
+ .iov_len = VHOST_USER_HDR_SIZE,
+ };
+ struct msghdr msg = {
+ .msg_iov = &iov,
+ .msg_iovlen = 1,
+ .msg_control = control,
+ .msg_controllen = sizeof(control),
+ };
+ size_t fd_size;
+ struct cmsghdr *cmsg;
+ int rc;
+
+ rc = recvmsg(conn_fd, &msg, 0);
+
+ if (rc == 0) {
+ vubr_die("recvmsg");
+ fprintf(stderr, "Peer disconnected.\n");
+ exit(1);
+ }
+ if (rc < 0) {
+ vubr_die("recvmsg");
+ }
+
+ vmsg->fd_num = 0;
+ for (cmsg = CMSG_FIRSTHDR(&msg);
+ cmsg != NULL;
+ cmsg = CMSG_NXTHDR(&msg, cmsg))
+ {
+ if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
+ fd_size = cmsg->cmsg_len - CMSG_LEN(0);
+ vmsg->fd_num = fd_size / sizeof(int);
+ memcpy(vmsg->fds, CMSG_DATA(cmsg), fd_size);
+ break;
+ }
+ }
+
+ if (vmsg->size > sizeof(vmsg->payload)) {
+ fprintf(stderr,
+ "Error: too big message request: %d, size: vmsg->size: %u, "
+ "while sizeof(vmsg->payload) = %lu\n",
+ vmsg->request, vmsg->size, sizeof(vmsg->payload));
+ exit(1);
+ }
+
+ if (vmsg->size) {
+ rc = read(conn_fd, &vmsg->payload, vmsg->size);
+ if (rc == 0) {
+ vubr_die("recvmsg");
+ fprintf(stderr, "Peer disconnected.\n");
+ exit(1);
+ }
+ if (rc < 0) {
+ vubr_die("recvmsg");
+ }
+
+ assert(rc == vmsg->size);
+ }
+}
+
+static void
+vubr_message_write(int conn_fd, VhostUserMsg *vmsg)
+{
+ int rc;
+
+ do {
+ rc = write(conn_fd, vmsg, VHOST_USER_HDR_SIZE + vmsg->size);
+ } while (rc < 0 && errno == EINTR);
+
+ if (rc < 0) {
+ vubr_die("write");
+ }
+}
+
+static void
+vubr_backend_udp_sendbuf(VubrDev *dev, uint8_t *buf, size_t len)
+{
+ int slen = sizeof(struct sockaddr_in);
+
+ if (sendto(dev->backend_udp_sock, buf, len, 0,
+ (struct sockaddr *) &dev->backend_udp_dest, slen) == -1) {
+ vubr_die("sendto()");
+ }
+}
+
+static int
+vubr_backend_udp_recvbuf(VubrDev *dev, uint8_t *buf, size_t buflen)
+{
+ int slen = sizeof(struct sockaddr_in);
+ int rc;
+
+ rc = recvfrom(dev->backend_udp_sock, buf, buflen, 0,
+ (struct sockaddr *) &dev->backend_udp_dest,
+ (socklen_t *)&slen);
+ if (rc == -1) {
+ vubr_die("recvfrom()");
+ }
+
+ return rc;
+}
+
+static void
+vubr_consume_raw_packet(VubrDev *dev, uint8_t *buf, uint32_t len)
+{
+ int hdrlen = sizeof(struct virtio_net_hdr_v1);
+
+ if (VHOST_USER_BRIDGE_DEBUG) {
+ print_buffer(buf, len);
+ }
+ vubr_backend_udp_sendbuf(dev, buf + hdrlen, len - hdrlen);
+}
+
+/* Kick the log_call_fd if required. */
+static void
+vubr_log_kick(VubrDev *dev)
+{
+ if (dev->log_call_fd != -1) {
+ DPRINT("Kicking the QEMU's log...\n");
+ eventfd_write(dev->log_call_fd, 1);
+ }
+}
+
+/* Kick the guest if necessary. */
+static void
+vubr_virtqueue_kick(VubrVirtq *vq)
+{
+ if (!(vq->avail->flags & VRING_AVAIL_F_NO_INTERRUPT)) {
+ DPRINT("Kicking the guest...\n");
+ eventfd_write(vq->call_fd, 1);
+ }
+}
+
+static void
+vubr_log_page(uint8_t *log_table, uint64_t page)
+{
+ DPRINT("Logged dirty guest page: %"PRId64"\n", page);
+ atomic_or(&log_table[page / 8], 1 << (page % 8));
+}
+
+static void
+vubr_log_write(VubrDev *dev, uint64_t address, uint64_t length)
+{
+ uint64_t page;
+
+ if (!(dev->features & (1ULL << VHOST_F_LOG_ALL)) ||
+ !dev->log_table || !length) {
+ return;
+ }
+
+ assert(dev->log_size > ((address + length - 1) / VHOST_LOG_PAGE / 8));
+
+ page = address / VHOST_LOG_PAGE;
+ while (page * VHOST_LOG_PAGE < address + length) {
+ vubr_log_page(dev->log_table, page);
+ page += VHOST_LOG_PAGE;
+ }
+ vubr_log_kick(dev);
+}
+
+static void
+vubr_post_buffer(VubrDev *dev, VubrVirtq *vq, uint8_t *buf, int32_t len)
+{
+ struct vring_desc *desc = vq->desc;
+ struct vring_avail *avail = vq->avail;
+ struct vring_used *used = vq->used;
+ uint64_t log_guest_addr = vq->log_guest_addr;
+
+ unsigned int size = vq->size;
+
+ uint16_t avail_index = atomic_mb_read(&avail->idx);
+
+ /* We check the available descriptors before posting the
+ * buffer, so here we assume that enough available
+ * descriptors. */
+ assert(vq->last_avail_index != avail_index);
+ uint16_t a_index = vq->last_avail_index % size;
+ uint16_t u_index = vq->last_used_index % size;
+ uint16_t d_index = avail->ring[a_index];
+
+ int i = d_index;
+
+ DPRINT("Post packet to guest on vq:\n");
+ DPRINT(" size = %d\n", vq->size);
+ DPRINT(" last_avail_index = %d\n", vq->last_avail_index);
+ DPRINT(" last_used_index = %d\n", vq->last_used_index);
+ DPRINT(" a_index = %d\n", a_index);
+ DPRINT(" u_index = %d\n", u_index);
+ DPRINT(" d_index = %d\n", d_index);
+ DPRINT(" desc[%d].addr = 0x%016"PRIx64"\n", i, desc[i].addr);
+ DPRINT(" desc[%d].len = %d\n", i, desc[i].len);
+ DPRINT(" desc[%d].flags = %d\n", i, desc[i].flags);
+ DPRINT(" avail->idx = %d\n", avail_index);
+ DPRINT(" used->idx = %d\n", used->idx);
+
+ if (!(desc[i].flags & VRING_DESC_F_WRITE)) {
+ /* FIXME: we should find writable descriptor. */
+ fprintf(stderr, "Error: descriptor is not writable. Exiting.\n");
+ exit(1);
+ }
+
+ void *chunk_start = (void *)gpa_to_va(dev, desc[i].addr);
+ uint32_t chunk_len = desc[i].len;
+
+ if (len <= chunk_len) {
+ memcpy(chunk_start, buf, len);
+ vubr_log_write(dev, desc[i].addr, len);
+ } else {
+ fprintf(stderr,
+ "Received too long packet from the backend. Dropping...\n");
+ return;
+ }
+
+ /* Add descriptor to the used ring. */
+ used->ring[u_index].id = d_index;
+ used->ring[u_index].len = len;
+ vubr_log_write(dev,
+ log_guest_addr + offsetof(struct vring_used, ring[u_index]),
+ sizeof(used->ring[u_index]));
+
+ vq->last_avail_index++;
+ vq->last_used_index++;
+
+ atomic_mb_set(&used->idx, vq->last_used_index);
+ vubr_log_write(dev,
+ log_guest_addr + offsetof(struct vring_used, idx),
+ sizeof(used->idx));
+
+ /* Kick the guest if necessary. */
+ vubr_virtqueue_kick(vq);
+}
+
+static int
+vubr_process_desc(VubrDev *dev, VubrVirtq *vq)
+{
+ struct vring_desc *desc = vq->desc;
+ struct vring_avail *avail = vq->avail;
+ struct vring_used *used = vq->used;
+ uint64_t log_guest_addr = vq->log_guest_addr;
+
+ unsigned int size = vq->size;
+
+ uint16_t a_index = vq->last_avail_index % size;
+ uint16_t u_index = vq->last_used_index % size;
+ uint16_t d_index = avail->ring[a_index];
+
+ uint32_t i, len = 0;
+ size_t buf_size = 4096;
+ uint8_t buf[4096];
+
+ DPRINT("Chunks: ");
+ i = d_index;
+ do {
+ void *chunk_start = (void *)gpa_to_va(dev, desc[i].addr);
+ uint32_t chunk_len = desc[i].len;
+
+ assert(!(desc[i].flags & VRING_DESC_F_WRITE));
+
+ if (len + chunk_len < buf_size) {
+ memcpy(buf + len, chunk_start, chunk_len);
+ DPRINT("%d ", chunk_len);
+ } else {
+ fprintf(stderr, "Error: too long packet. Dropping...\n");
+ break;
+ }
+
+ len += chunk_len;
+
+ if (!(desc[i].flags & VRING_DESC_F_NEXT)) {
+ break;
+ }
+
+ i = desc[i].next;
+ } while (1);
+ DPRINT("\n");
+
+ if (!len) {
+ return -1;
+ }
+
+ /* Add descriptor to the used ring. */
+ used->ring[u_index].id = d_index;
+ used->ring[u_index].len = len;
+ vubr_log_write(dev,
+ log_guest_addr + offsetof(struct vring_used, ring[u_index]),
+ sizeof(used->ring[u_index]));
+
+ vubr_consume_raw_packet(dev, buf, len);
+
+ return 0;
+}
+
+static void
+vubr_process_avail(VubrDev *dev, VubrVirtq *vq)
+{
+ struct vring_avail *avail = vq->avail;
+ struct vring_used *used = vq->used;
+ uint64_t log_guest_addr = vq->log_guest_addr;
+
+ while (vq->last_avail_index != atomic_mb_read(&avail->idx)) {
+ vubr_process_desc(dev, vq);
+ vq->last_avail_index++;
+ vq->last_used_index++;
+ }
+
+ atomic_mb_set(&used->idx, vq->last_used_index);
+ vubr_log_write(dev,
+ log_guest_addr + offsetof(struct vring_used, idx),
+ sizeof(used->idx));
+}
+
+static void
+vubr_backend_recv_cb(int sock, void *ctx)
+{
+ VubrDev *dev = (VubrDev *) ctx;
+ VubrVirtq *rx_vq = &dev->vq[0];
+ uint8_t buf[4096];
+ struct virtio_net_hdr_v1 *hdr = (struct virtio_net_hdr_v1 *)buf;
+ int hdrlen = sizeof(struct virtio_net_hdr_v1);
+ int buflen = sizeof(buf);
+ int len;
+
+ if (!dev->ready) {
+ return;
+ }
+
+ DPRINT("\n\n *** IN UDP RECEIVE CALLBACK ***\n\n");
+
+ uint16_t avail_index = atomic_mb_read(&rx_vq->avail->idx);
+
+ /* If there is no available descriptors, just do nothing.
+ * The buffer will be handled by next arrived UDP packet,
+ * or next kick on receive virtq. */
+ if (rx_vq->last_avail_index == avail_index) {
+ DPRINT("Got UDP packet, but no available descriptors on RX virtq.\n");
+ return;
+ }
+
+ len = vubr_backend_udp_recvbuf(dev, buf + hdrlen, buflen - hdrlen);
+
+ *hdr = (struct virtio_net_hdr_v1) { };
+ hdr->num_buffers = 1;
+ vubr_post_buffer(dev, rx_vq, buf, len + hdrlen);
+}
+
+static void
+vubr_kick_cb(int sock, void *ctx)
+{
+ VubrDev *dev = (VubrDev *) ctx;
+ eventfd_t kick_data;
+ ssize_t rc;
+
+ rc = eventfd_read(sock, &kick_data);
+ if (rc == -1) {
+ vubr_die("eventfd_read()");
+ } else {
+ DPRINT("Got kick_data: %016"PRIx64"\n", kick_data);
+ vubr_process_avail(dev, &dev->vq[1]);
+ }
+}
+
+static int
+vubr_none_exec(VubrDev *dev, VhostUserMsg *vmsg)
+{
+ DPRINT("Function %s() not implemented yet.\n", __func__);
+ return 0;
+}
+
+static int
+vubr_get_features_exec(VubrDev *dev, VhostUserMsg *vmsg)
+{
+ vmsg->payload.u64 =
+ ((1ULL << VIRTIO_NET_F_MRG_RXBUF) |
+ (1ULL << VHOST_F_LOG_ALL) |
+ (1ULL << VIRTIO_NET_F_GUEST_ANNOUNCE) |
+ (1ULL << VHOST_USER_F_PROTOCOL_FEATURES));
+
+ vmsg->size = sizeof(vmsg->payload.u64);
+
+ DPRINT("Sending back to guest u64: 0x%016"PRIx64"\n", vmsg->payload.u64);
+
+ /* Reply */
+ return 1;
+}
+
+static int
+vubr_set_features_exec(VubrDev *dev, VhostUserMsg *vmsg)
+{
+ DPRINT("u64: 0x%016"PRIx64"\n", vmsg->payload.u64);
+ dev->features = vmsg->payload.u64;
+ return 0;
+}
+
+static int
+vubr_set_owner_exec(VubrDev *dev, VhostUserMsg *vmsg)
+{
+ return 0;
+}
+
+static void
+vubr_close_log(VubrDev *dev)
+{
+ if (dev->log_table) {
+ if (munmap(dev->log_table, dev->log_size) != 0) {
+ vubr_die("munmap()");
+ }
+
+ dev->log_table = 0;
+ }
+ if (dev->log_call_fd != -1) {
+ close(dev->log_call_fd);
+ dev->log_call_fd = -1;
+ }
+}
+
+static int
+vubr_reset_device_exec(VubrDev *dev, VhostUserMsg *vmsg)
+{
+ vubr_close_log(dev);
+ dev->ready = 0;
+ dev->features = 0;
+ return 0;
+}
+
+static int
+vubr_set_mem_table_exec(VubrDev *dev, VhostUserMsg *vmsg)
+{
+ int i;
+ VhostUserMemory *memory = &vmsg->payload.memory;
+ dev->nregions = memory->nregions;
+
+ DPRINT("Nregions: %d\n", memory->nregions);
+ for (i = 0; i < dev->nregions; i++) {
+ void *mmap_addr;
+ VhostUserMemoryRegion *msg_region = &memory->regions[i];
+ VubrDevRegion *dev_region = &dev->regions[i];
+
+ DPRINT("Region %d\n", i);
+ DPRINT(" guest_phys_addr: 0x%016"PRIx64"\n",
+ msg_region->guest_phys_addr);
+ DPRINT(" memory_size: 0x%016"PRIx64"\n",
+ msg_region->memory_size);
+ DPRINT(" userspace_addr 0x%016"PRIx64"\n",
+ msg_region->userspace_addr);
+ DPRINT(" mmap_offset 0x%016"PRIx64"\n",
+ msg_region->mmap_offset);
+
+ dev_region->gpa = msg_region->guest_phys_addr;
+ dev_region->size = msg_region->memory_size;
+ dev_region->qva = msg_region->userspace_addr;
+ dev_region->mmap_offset = msg_region->mmap_offset;
+
+ /* We don't use offset argument of mmap() since the
+ * mapped address has to be page aligned, and we use huge
+ * pages. */
+ mmap_addr = mmap(0, dev_region->size + dev_region->mmap_offset,
+ PROT_READ | PROT_WRITE, MAP_SHARED,
+ vmsg->fds[i], 0);
+
+ if (mmap_addr == MAP_FAILED) {
+ vubr_die("mmap");
+ }
+ dev_region->mmap_addr = (uint64_t) mmap_addr;
+ DPRINT(" mmap_addr: 0x%016"PRIx64"\n", dev_region->mmap_addr);
+
+ close(vmsg->fds[i]);
+ }
+
+ return 0;
+}
+
+static int
+vubr_set_log_base_exec(VubrDev *dev, VhostUserMsg *vmsg)
+{
+ int fd;
+ uint64_t log_mmap_size, log_mmap_offset;
+ void *rc;
+
+ assert(vmsg->fd_num == 1);
+ fd = vmsg->fds[0];
+
+ assert(vmsg->size == sizeof(vmsg->payload.log));
+ log_mmap_offset = vmsg->payload.log.mmap_offset;
+ log_mmap_size = vmsg->payload.log.mmap_size;
+ DPRINT("Log mmap_offset: %"PRId64"\n", log_mmap_offset);
+ DPRINT("Log mmap_size: %"PRId64"\n", log_mmap_size);
+
+ rc = mmap(0, log_mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd,
+ log_mmap_offset);
+ if (rc == MAP_FAILED) {
+ vubr_die("mmap");
+ }
+ dev->log_table = rc;
+ dev->log_size = log_mmap_size;
+
+ vmsg->size = sizeof(vmsg->payload.u64);
+ /* Reply */
+ return 1;
+}
+
+static int
+vubr_set_log_fd_exec(VubrDev *dev, VhostUserMsg *vmsg)
+{
+ assert(vmsg->fd_num == 1);
+ dev->log_call_fd = vmsg->fds[0];
+ DPRINT("Got log_call_fd: %d\n", vmsg->fds[0]);
+ return 0;
+}
+
+static int
+vubr_set_vring_num_exec(VubrDev *dev, VhostUserMsg *vmsg)
+{
+ unsigned int index = vmsg->payload.state.index;
+ unsigned int num = vmsg->payload.state.num;
+
+ DPRINT("State.index: %d\n", index);
+ DPRINT("State.num: %d\n", num);
+ dev->vq[index].size = num;
+ return 0;
+}
+
+static int
+vubr_set_vring_addr_exec(VubrDev *dev, VhostUserMsg *vmsg)
+{
+ struct vhost_vring_addr *vra = &vmsg->payload.addr;
+ unsigned int index = vra->index;
+ VubrVirtq *vq = &dev->vq[index];
+
+ DPRINT("vhost_vring_addr:\n");
+ DPRINT(" index: %d\n", vra->index);
+ DPRINT(" flags: %d\n", vra->flags);
+ DPRINT(" desc_user_addr: 0x%016llx\n", vra->desc_user_addr);
+ DPRINT(" used_user_addr: 0x%016llx\n", vra->used_user_addr);
+ DPRINT(" avail_user_addr: 0x%016llx\n", vra->avail_user_addr);
+ DPRINT(" log_guest_addr: 0x%016llx\n", vra->log_guest_addr);
+
+ vq->desc = (struct vring_desc *)qva_to_va(dev, vra->desc_user_addr);
+ vq->used = (struct vring_used *)qva_to_va(dev, vra->used_user_addr);
+ vq->avail = (struct vring_avail *)qva_to_va(dev, vra->avail_user_addr);
+ vq->log_guest_addr = vra->log_guest_addr;
+
+ DPRINT("Setting virtq addresses:\n");
+ DPRINT(" vring_desc at %p\n", vq->desc);
+ DPRINT(" vring_used at %p\n", vq->used);
+ DPRINT(" vring_avail at %p\n", vq->avail);
+
+ vq->last_used_index = vq->used->idx;
+ return 0;
+}
+
+static int
+vubr_set_vring_base_exec(VubrDev *dev, VhostUserMsg *vmsg)
+{
+ unsigned int index = vmsg->payload.state.index;
+ unsigned int num = vmsg->payload.state.num;
+
+ DPRINT("State.index: %d\n", index);
+ DPRINT("State.num: %d\n", num);
+ dev->vq[index].last_avail_index = num;
+
+ return 0;
+}
+
+static int
+vubr_get_vring_base_exec(VubrDev *dev, VhostUserMsg *vmsg)
+{
+ unsigned int index = vmsg->payload.state.index;
+
+ DPRINT("State.index: %d\n", index);
+ vmsg->payload.state.num = dev->vq[index].last_avail_index;
+ vmsg->size = sizeof(vmsg->payload.state);
+ /* FIXME: this is a work-around for a bug in QEMU enabling
+ * too early vrings. When protocol features are enabled,
+ * we have to respect * VHOST_USER_SET_VRING_ENABLE request. */
+ dev->ready = 0;
+
+ if (dev->vq[index].call_fd != -1) {
+ close(dev->vq[index].call_fd);
+ dispatcher_remove(&dev->dispatcher, dev->vq[index].call_fd);
+ dev->vq[index].call_fd = -1;
+ }
+ if (dev->vq[index].kick_fd != -1) {
+ close(dev->vq[index].kick_fd);
+ dispatcher_remove(&dev->dispatcher, dev->vq[index].kick_fd);
+ dev->vq[index].kick_fd = -1;
+ }
+
+ /* Reply */
+ return 1;
+}
+
+static int
+vubr_set_vring_kick_exec(VubrDev *dev, VhostUserMsg *vmsg)
+{
+ uint64_t u64_arg = vmsg->payload.u64;
+ int index = u64_arg & VHOST_USER_VRING_IDX_MASK;
+
+ DPRINT("u64: 0x%016"PRIx64"\n", vmsg->payload.u64);
+
+ assert((u64_arg & VHOST_USER_VRING_NOFD_MASK) == 0);
+ assert(vmsg->fd_num == 1);
+
+ if (dev->vq[index].kick_fd != -1) {
+ close(dev->vq[index].kick_fd);
+ dispatcher_remove(&dev->dispatcher, dev->vq[index].kick_fd);
+ }
+ dev->vq[index].kick_fd = vmsg->fds[0];
+ DPRINT("Got kick_fd: %d for vq: %d\n", vmsg->fds[0], index);
+
+ if (index % 2 == 1) {
+ /* TX queue. */
+ dispatcher_add(&dev->dispatcher, dev->vq[index].kick_fd,
+ dev, vubr_kick_cb);
+
+ DPRINT("Waiting for kicks on fd: %d for vq: %d\n",
+ dev->vq[index].kick_fd, index);
+ }
+ /* We temporarily use this hack to determine that both TX and RX
+ * queues are set up and ready for processing.
+ * FIXME: we need to rely in VHOST_USER_SET_VRING_ENABLE and
+ * actual kicks. */
+ if (dev->vq[0].kick_fd != -1 &&
+ dev->vq[1].kick_fd != -1) {
+ dev->ready = 1;
+ DPRINT("vhost-user-bridge is ready for processing queues.\n");
+ }
+ return 0;
+
+}
+
+static int
+vubr_set_vring_call_exec(VubrDev *dev, VhostUserMsg *vmsg)
+{
+ uint64_t u64_arg = vmsg->payload.u64;
+ int index = u64_arg & VHOST_USER_VRING_IDX_MASK;
+
+ DPRINT("u64: 0x%016"PRIx64"\n", vmsg->payload.u64);
+ assert((u64_arg & VHOST_USER_VRING_NOFD_MASK) == 0);
+ assert(vmsg->fd_num == 1);
+
+ if (dev->vq[index].call_fd != -1) {
+ close(dev->vq[index].call_fd);
+ dispatcher_remove(&dev->dispatcher, dev->vq[index].call_fd);
+ }
+ dev->vq[index].call_fd = vmsg->fds[0];
+ DPRINT("Got call_fd: %d for vq: %d\n", vmsg->fds[0], index);
+
+ return 0;
+}
+
+static int
+vubr_set_vring_err_exec(VubrDev *dev, VhostUserMsg *vmsg)
+{
+ DPRINT("u64: 0x%016"PRIx64"\n", vmsg->payload.u64);
+ return 0;
+}
+
+static int
+vubr_get_protocol_features_exec(VubrDev *dev, VhostUserMsg *vmsg)
+{
+ vmsg->payload.u64 = 1ULL << VHOST_USER_PROTOCOL_F_LOG_SHMFD;
+ DPRINT("u64: 0x%016"PRIx64"\n", vmsg->payload.u64);
+ vmsg->size = sizeof(vmsg->payload.u64);
+
+ /* Reply */
+ return 1;
+}
+
+static int
+vubr_set_protocol_features_exec(VubrDev *dev, VhostUserMsg *vmsg)
+{
+ /* FIXME: unimplented */
+ DPRINT("u64: 0x%016"PRIx64"\n", vmsg->payload.u64);
+ return 0;
+}
+
+static int
+vubr_get_queue_num_exec(VubrDev *dev, VhostUserMsg *vmsg)
+{
+ DPRINT("Function %s() not implemented yet.\n", __func__);
+ return 0;
+}
+
+static int
+vubr_set_vring_enable_exec(VubrDev *dev, VhostUserMsg *vmsg)
+{
+ unsigned int index = vmsg->payload.state.index;
+ unsigned int enable = vmsg->payload.state.num;
+
+ DPRINT("State.index: %d\n", index);
+ DPRINT("State.enable: %d\n", enable);
+ dev->vq[index].enable = enable;
+ return 0;
+}
+
+static int
+vubr_send_rarp_exec(VubrDev *dev, VhostUserMsg *vmsg)
+{
+ DPRINT("Function %s() not implemented yet.\n", __func__);
+ return 0;
+}
+
+static int
+vubr_execute_request(VubrDev *dev, VhostUserMsg *vmsg)
+{
+ /* Print out generic part of the request. */
+ DPRINT(
+ "================== Vhost user message from QEMU ==================\n");
+ DPRINT("Request: %s (%d)\n", vubr_request_str[vmsg->request],
+ vmsg->request);
+ DPRINT("Flags: 0x%x\n", vmsg->flags);
+ DPRINT("Size: %d\n", vmsg->size);
+
+ if (vmsg->fd_num) {
+ int i;
+ DPRINT("Fds:");
+ for (i = 0; i < vmsg->fd_num; i++) {
+ DPRINT(" %d", vmsg->fds[i]);
+ }
+ DPRINT("\n");
+ }
+
+ switch (vmsg->request) {
+ case VHOST_USER_NONE:
+ return vubr_none_exec(dev, vmsg);
+ case VHOST_USER_GET_FEATURES:
+ return vubr_get_features_exec(dev, vmsg);
+ case VHOST_USER_SET_FEATURES:
+ return vubr_set_features_exec(dev, vmsg);
+ case VHOST_USER_SET_OWNER:
+ return vubr_set_owner_exec(dev, vmsg);
+ case VHOST_USER_RESET_OWNER:
+ return vubr_reset_device_exec(dev, vmsg);
+ case VHOST_USER_SET_MEM_TABLE:
+ return vubr_set_mem_table_exec(dev, vmsg);
+ case VHOST_USER_SET_LOG_BASE:
+ return vubr_set_log_base_exec(dev, vmsg);
+ case VHOST_USER_SET_LOG_FD:
+ return vubr_set_log_fd_exec(dev, vmsg);
+ case VHOST_USER_SET_VRING_NUM:
+ return vubr_set_vring_num_exec(dev, vmsg);
+ case VHOST_USER_SET_VRING_ADDR:
+ return vubr_set_vring_addr_exec(dev, vmsg);
+ case VHOST_USER_SET_VRING_BASE:
+ return vubr_set_vring_base_exec(dev, vmsg);
+ case VHOST_USER_GET_VRING_BASE:
+ return vubr_get_vring_base_exec(dev, vmsg);
+ case VHOST_USER_SET_VRING_KICK:
+ return vubr_set_vring_kick_exec(dev, vmsg);
+ case VHOST_USER_SET_VRING_CALL:
+ return vubr_set_vring_call_exec(dev, vmsg);
+ case VHOST_USER_SET_VRING_ERR:
+ return vubr_set_vring_err_exec(dev, vmsg);
+ case VHOST_USER_GET_PROTOCOL_FEATURES:
+ return vubr_get_protocol_features_exec(dev, vmsg);
+ case VHOST_USER_SET_PROTOCOL_FEATURES:
+ return vubr_set_protocol_features_exec(dev, vmsg);
+ case VHOST_USER_GET_QUEUE_NUM:
+ return vubr_get_queue_num_exec(dev, vmsg);
+ case VHOST_USER_SET_VRING_ENABLE:
+ return vubr_set_vring_enable_exec(dev, vmsg);
+ case VHOST_USER_SEND_RARP:
+ return vubr_send_rarp_exec(dev, vmsg);
+
+ case VHOST_USER_MAX:
+ assert(vmsg->request != VHOST_USER_MAX);
+ }
+ return 0;
+}
+
+static void
+vubr_receive_cb(int sock, void *ctx)
+{
+ VubrDev *dev = (VubrDev *) ctx;
+ VhostUserMsg vmsg;
+ int reply_requested;
+
+ vubr_message_read(sock, &vmsg);
+ reply_requested = vubr_execute_request(dev, &vmsg);
+ if (reply_requested) {
+ /* Set the version in the flags when sending the reply */
+ vmsg.flags &= ~VHOST_USER_VERSION_MASK;
+ vmsg.flags |= VHOST_USER_VERSION;
+ vmsg.flags |= VHOST_USER_REPLY_MASK;
+ vubr_message_write(sock, &vmsg);
+ }
+}
+
+static void
+vubr_accept_cb(int sock, void *ctx)
+{
+ VubrDev *dev = (VubrDev *)ctx;
+ int conn_fd;
+ struct sockaddr_un un;
+ socklen_t len = sizeof(un);
+
+ conn_fd = accept(sock, (struct sockaddr *) &un, &len);
+ if (conn_fd == -1) {
+ vubr_die("accept()");
+ }
+ DPRINT("Got connection from remote peer on sock %d\n", conn_fd);
+ dispatcher_add(&dev->dispatcher, conn_fd, ctx, vubr_receive_cb);
+}
+
+static VubrDev *
+vubr_new(const char *path)
+{
+ VubrDev *dev = (VubrDev *) calloc(1, sizeof(VubrDev));
+ dev->nregions = 0;
+ int i;
+ struct sockaddr_un un;
+ size_t len;
+
+ for (i = 0; i < MAX_NR_VIRTQUEUE; i++) {
+ dev->vq[i] = (VubrVirtq) {
+ .call_fd = -1, .kick_fd = -1,
+ .size = 0,
+ .last_avail_index = 0, .last_used_index = 0,
+ .desc = 0, .avail = 0, .used = 0,
+ .enable = 0,
+ };
+ }
+
+ /* Init log */
+ dev->log_call_fd = -1;
+ dev->log_size = 0;
+ dev->log_table = 0;
+ dev->ready = 0;
+ dev->features = 0;
+
+ /* Get a UNIX socket. */
+ dev->sock = socket(AF_UNIX, SOCK_STREAM, 0);
+ if (dev->sock == -1) {
+ vubr_die("socket");
+ }
+
+ un.sun_family = AF_UNIX;
+ strcpy(un.sun_path, path);
+ len = sizeof(un.sun_family) + strlen(path);
+ unlink(path);
+
+ if (bind(dev->sock, (struct sockaddr *) &un, len) == -1) {
+ vubr_die("bind");
+ }
+
+ if (listen(dev->sock, 1) == -1) {
+ vubr_die("listen");
+ }
+
+ dispatcher_init(&dev->dispatcher);
+ dispatcher_add(&dev->dispatcher, dev->sock, (void *)dev,
+ vubr_accept_cb);
+
+ DPRINT("Waiting for connections on UNIX socket %s ...\n", path);
+ return dev;
+}
+
+static void
+vubr_set_host(struct sockaddr_in *saddr, const char *host)
+{
+ if (isdigit(host[0])) {
+ if (!inet_aton(host, &saddr->sin_addr)) {
+ fprintf(stderr, "inet_aton() failed.\n");
+ exit(1);
+ }
+ } else {
+ struct hostent *he = gethostbyname(host);
+
+ if (!he) {
+ fprintf(stderr, "gethostbyname() failed.\n");
+ exit(1);
+ }
+ saddr->sin_addr = *(struct in_addr *)he->h_addr;
+ }
+}
+
+static void
+vubr_backend_udp_setup(VubrDev *dev,
+ const char *local_host,
+ const char *local_port,
+ const char *remote_host,
+ const char *remote_port)
+{
+ int sock;
+ const char *r;
+
+ int lport, rport;
+
+ lport = strtol(local_port, (char **)&r, 0);
+ if (r == local_port) {
+ fprintf(stderr, "lport parsing failed.\n");
+ exit(1);
+ }
+
+ rport = strtol(remote_port, (char **)&r, 0);
+ if (r == remote_port) {
+ fprintf(stderr, "rport parsing failed.\n");
+ exit(1);
+ }
+
+ struct sockaddr_in si_local = {
+ .sin_family = AF_INET,
+ .sin_port = htons(lport),
+ };
+
+ vubr_set_host(&si_local, local_host);
+
+ /* setup destination for sends */
+ dev->backend_udp_dest = (struct sockaddr_in) {
+ .sin_family = AF_INET,
+ .sin_port = htons(rport),
+ };
+ vubr_set_host(&dev->backend_udp_dest, remote_host);
+
+ sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
+ if (sock == -1) {
+ vubr_die("socket");
+ }
+
+ if (bind(sock, (struct sockaddr *)&si_local, sizeof(si_local)) == -1) {
+ vubr_die("bind");
+ }
+
+ dev->backend_udp_sock = sock;
+ dispatcher_add(&dev->dispatcher, sock, dev, vubr_backend_recv_cb);
+ DPRINT("Waiting for data from udp backend on %s:%d...\n",
+ local_host, lport);
+}
+
+static void
+vubr_run(VubrDev *dev)
+{
+ while (1) {
+ /* timeout 200ms */
+ dispatcher_wait(&dev->dispatcher, 200000);
+ /* Here one can try polling strategy. */
+ }
+}
+
+static int
+vubr_parse_host_port(const char **host, const char **port, const char *buf)
+{
+ char *p = strchr(buf, ':');
+
+ if (!p) {
+ return -1;
+ }
+ *p = '\0';
+ *host = strdup(buf);
+ *port = strdup(p + 1);
+ return 0;
+}
+
+#define DEFAULT_UD_SOCKET "/tmp/vubr.sock"
+#define DEFAULT_LHOST "127.0.0.1"
+#define DEFAULT_LPORT "4444"
+#define DEFAULT_RHOST "127.0.0.1"
+#define DEFAULT_RPORT "5555"
+
+static const char *ud_socket_path = DEFAULT_UD_SOCKET;
+static const char *lhost = DEFAULT_LHOST;
+static const char *lport = DEFAULT_LPORT;
+static const char *rhost = DEFAULT_RHOST;
+static const char *rport = DEFAULT_RPORT;
+
+int
+main(int argc, char *argv[])
+{
+ VubrDev *dev;
+ int opt;
+
+ while ((opt = getopt(argc, argv, "l:r:u:")) != -1) {
+
+ switch (opt) {
+ case 'l':
+ if (vubr_parse_host_port(&lhost, &lport, optarg) < 0) {
+ goto out;
+ }
+ break;
+ case 'r':
+ if (vubr_parse_host_port(&rhost, &rport, optarg) < 0) {
+ goto out;
+ }
+ break;
+ case 'u':
+ ud_socket_path = strdup(optarg);
+ break;
+ default:
+ goto out;
+ }
+ }
+
+ DPRINT("ud socket: %s\n", ud_socket_path);
+ DPRINT("local: %s:%s\n", lhost, lport);
+ DPRINT("remote: %s:%s\n", rhost, rport);
+
+ dev = vubr_new(ud_socket_path);
+ if (!dev) {
+ return 1;
+ }
+
+ vubr_backend_udp_setup(dev, lhost, lport, rhost, rport);
+ vubr_run(dev);
+ return 0;
+
+out:
+ fprintf(stderr, "Usage: %s ", argv[0]);
+ fprintf(stderr, "[-u ud_socket_path] [-l lhost:lport] [-r rhost:rport]\n");
+ fprintf(stderr, "\t-u path to unix doman socket. default: %s\n",
+ DEFAULT_UD_SOCKET);
+ fprintf(stderr, "\t-l local host and port. default: %s:%s\n",
+ DEFAULT_LHOST, DEFAULT_LPORT);
+ fprintf(stderr, "\t-r remote host and port. default: %s:%s\n",
+ DEFAULT_RHOST, DEFAULT_RPORT);
+
+ return 1;
+}
diff --git a/tests/vhost-user-test.c b/tests/vhost-user-test.c
index 75fedf097..991fd85c7 100644
--- a/tests/vhost-user-test.c
+++ b/tests/vhost-user-test.c
@@ -8,11 +8,11 @@
*
*/
-#define QEMU_GLIB_COMPAT_H
#include <glib.h>
#include "libqtest.h"
#include "qemu/option.h"
+#include "qemu/range.h"
#include "sysemu/char.h"
#include "sysemu/sysemu.h"
@@ -30,17 +30,11 @@
#define HAVE_MONOTONIC_TIME
#endif
-#if GLIB_CHECK_VERSION(2, 32, 0)
-#define HAVE_MUTEX_INIT
-#define HAVE_COND_INIT
-#define HAVE_THREAD_NEW
-#endif
-
#define QEMU_CMD_ACCEL " -machine accel=tcg"
-#define QEMU_CMD_MEM " -m 512 -object memory-backend-file,id=mem,size=512M,"\
+#define QEMU_CMD_MEM " -m %d -object memory-backend-file,id=mem,size=%dM,"\
"mem-path=%s,share=on -numa node,memdev=mem"
-#define QEMU_CMD_CHR " -chardev socket,id=chr0,path=%s"
-#define QEMU_CMD_NETDEV " -netdev vhost-user,id=net0,chardev=chr0,vhostforce"
+#define QEMU_CMD_CHR " -chardev socket,id=%s,path=%s"
+#define QEMU_CMD_NETDEV " -netdev vhost-user,id=net0,chardev=%s,vhostforce"
#define QEMU_CMD_NET " -device virtio-net-pci,netdev=net0 "
#define QEMU_CMD_ROM " -option-rom ../pc-bios/pxe-virtio.rom"
@@ -53,6 +47,11 @@
#define VHOST_MEMORY_MAX_NREGIONS 8
+#define VHOST_USER_F_PROTOCOL_FEATURES 30
+#define VHOST_USER_PROTOCOL_F_LOG_SHMFD 1
+
+#define VHOST_LOG_PAGE 0x1000
+
typedef enum VhostUserRequest {
VHOST_USER_NONE = 0,
VHOST_USER_GET_FEATURES = 1,
@@ -69,6 +68,9 @@ typedef enum VhostUserRequest {
VHOST_USER_SET_VRING_KICK = 12,
VHOST_USER_SET_VRING_CALL = 13,
VHOST_USER_SET_VRING_ERR = 14,
+ VHOST_USER_GET_PROTOCOL_FEATURES = 15,
+ VHOST_USER_SET_PROTOCOL_FEATURES = 16,
+ VHOST_USER_SET_VRING_ENABLE = 18,
VHOST_USER_MAX
} VhostUserRequest;
@@ -85,6 +87,11 @@ typedef struct VhostUserMemory {
VhostUserMemoryRegion regions[VHOST_MEMORY_MAX_NREGIONS];
} VhostUserMemory;
+typedef struct VhostUserLog {
+ uint64_t mmap_size;
+ uint64_t mmap_offset;
+} VhostUserLog;
+
typedef struct VhostUserMsg {
VhostUserRequest request;
@@ -93,11 +100,14 @@ typedef struct VhostUserMsg {
uint32_t flags;
uint32_t size; /* the following payload size */
union {
+#define VHOST_USER_VRING_IDX_MASK (0xff)
+#define VHOST_USER_VRING_NOFD_MASK (0x1<<8)
uint64_t u64;
struct vhost_vring_state state;
struct vhost_vring_addr addr;
VhostUserMemory memory;
- };
+ VhostUserLog log;
+ } payload;
} QEMU_PACKED VhostUserMsg;
static VhostUserMsg m __attribute__ ((unused));
@@ -111,154 +121,104 @@ static VhostUserMsg m __attribute__ ((unused));
#define VHOST_USER_VERSION (0x1)
/*****************************************************************************/
-int fds_num = 0, fds[VHOST_MEMORY_MAX_NREGIONS];
-static VhostUserMemory memory;
-static GMutex *data_mutex;
-static GCond *data_cond;
-
-static gint64 _get_time(void)
-{
-#ifdef HAVE_MONOTONIC_TIME
- return g_get_monotonic_time();
-#else
- GTimeVal time;
- g_get_current_time(&time);
-
- return time.tv_sec * G_TIME_SPAN_SECOND + time.tv_usec;
-#endif
-}
-
-static GMutex *_mutex_new(void)
-{
- GMutex *mutex;
-
-#ifdef HAVE_MUTEX_INIT
- mutex = g_new(GMutex, 1);
- g_mutex_init(mutex);
-#else
- mutex = g_mutex_new();
-#endif
-
- return mutex;
-}
-
-static void _mutex_free(GMutex *mutex)
-{
-#ifdef HAVE_MUTEX_INIT
- g_mutex_clear(mutex);
- g_free(mutex);
-#else
- g_mutex_free(mutex);
-#endif
-}
-
-static GCond *_cond_new(void)
-{
- GCond *cond;
-
-#ifdef HAVE_COND_INIT
- cond = g_new(GCond, 1);
- g_cond_init(cond);
-#else
- cond = g_cond_new();
-#endif
-
- return cond;
-}
-
-static gboolean _cond_wait_until(GCond *cond, GMutex *mutex, gint64 end_time)
+typedef struct TestServer {
+ gchar *socket_path;
+ gchar *mig_path;
+ gchar *chr_name;
+ CharDriverState *chr;
+ int fds_num;
+ int fds[VHOST_MEMORY_MAX_NREGIONS];
+ VhostUserMemory memory;
+ GMutex data_mutex;
+ GCond data_cond;
+ int log_fd;
+ uint64_t rings;
+} TestServer;
+
+#if !GLIB_CHECK_VERSION(2, 32, 0)
+static gboolean g_cond_wait_until(CompatGCond cond, CompatGMutex mutex,
+ gint64 end_time)
{
gboolean ret = FALSE;
-#ifdef HAVE_COND_INIT
- ret = g_cond_wait_until(cond, mutex, end_time);
-#else
+ end_time -= g_get_monotonic_time();
GTimeVal time = { end_time / G_TIME_SPAN_SECOND,
end_time % G_TIME_SPAN_SECOND };
ret = g_cond_timed_wait(cond, mutex, &time);
-#endif
return ret;
}
-
-static void _cond_free(GCond *cond)
-{
-#ifdef HAVE_COND_INIT
- g_cond_clear(cond);
- g_free(cond);
-#else
- g_cond_free(cond);
#endif
-}
-static GThread *_thread_new(const gchar *name, GThreadFunc func, gpointer data)
-{
- GThread *thread = NULL;
- GError *error = NULL;
-#ifdef HAVE_THREAD_NEW
- thread = g_thread_try_new(name, func, data, &error);
-#else
- thread = g_thread_create(func, data, TRUE, &error);
-#endif
- return thread;
-}
+static const char *tmpfs;
+static const char *root;
-static void read_guest_mem(void)
+static void wait_for_fds(TestServer *s)
{
- uint32_t *guest_mem;
gint64 end_time;
- int i, j;
- size_t size;
- g_mutex_lock(data_mutex);
+ g_mutex_lock(&s->data_mutex);
- end_time = _get_time() + 5 * G_TIME_SPAN_SECOND;
- while (!fds_num) {
- if (!_cond_wait_until(data_cond, data_mutex, end_time)) {
+ end_time = g_get_monotonic_time() + 5 * G_TIME_SPAN_SECOND;
+ while (!s->fds_num) {
+ if (!g_cond_wait_until(&s->data_cond, &s->data_mutex, end_time)) {
/* timeout has passed */
- g_assert(fds_num);
+ g_assert(s->fds_num);
break;
}
}
/* check for sanity */
- g_assert_cmpint(fds_num, >, 0);
- g_assert_cmpint(fds_num, ==, memory.nregions);
+ g_assert_cmpint(s->fds_num, >, 0);
+ g_assert_cmpint(s->fds_num, ==, s->memory.nregions);
+
+ g_mutex_unlock(&s->data_mutex);
+}
+
+static void read_guest_mem(const void *data)
+{
+ TestServer *s = (void *)data;
+ uint32_t *guest_mem;
+ int i, j;
+ size_t size;
+
+ wait_for_fds(s);
+
+ g_mutex_lock(&s->data_mutex);
/* iterate all regions */
- for (i = 0; i < fds_num; i++) {
+ for (i = 0; i < s->fds_num; i++) {
/* We'll check only the region statring at 0x0*/
- if (memory.regions[i].guest_phys_addr != 0x0) {
+ if (s->memory.regions[i].guest_phys_addr != 0x0) {
continue;
}
- g_assert_cmpint(memory.regions[i].memory_size, >, 1024);
+ g_assert_cmpint(s->memory.regions[i].memory_size, >, 1024);
- size = memory.regions[i].memory_size + memory.regions[i].mmap_offset;
+ size = s->memory.regions[i].memory_size +
+ s->memory.regions[i].mmap_offset;
guest_mem = mmap(0, size, PROT_READ | PROT_WRITE,
- MAP_SHARED, fds[i], 0);
+ MAP_SHARED, s->fds[i], 0);
g_assert(guest_mem != MAP_FAILED);
- guest_mem += (memory.regions[i].mmap_offset / sizeof(*guest_mem));
+ guest_mem += (s->memory.regions[i].mmap_offset / sizeof(*guest_mem));
for (j = 0; j < 256; j++) {
- uint32_t a = readl(memory.regions[i].guest_phys_addr + j*4);
+ uint32_t a = readl(s->memory.regions[i].guest_phys_addr + j*4);
uint32_t b = guest_mem[j];
g_assert_cmpint(a, ==, b);
}
- munmap(guest_mem, memory.regions[i].memory_size);
+ munmap(guest_mem, s->memory.regions[i].memory_size);
}
- g_assert_cmpint(1, ==, 1);
- g_mutex_unlock(data_mutex);
+ g_mutex_unlock(&s->data_mutex);
}
static void *thread_function(void *data)
{
- GMainLoop *loop;
- loop = g_main_loop_new(NULL, FALSE);
+ GMainLoop *loop = data;
g_main_loop_run(loop);
return NULL;
}
@@ -270,7 +230,8 @@ static int chr_can_read(void *opaque)
static void chr_read(void *opaque, const uint8_t *buf, int size)
{
- CharDriverState *chr = opaque;
+ TestServer *s = opaque;
+ CharDriverState *chr = s->chr;
VhostUserMsg msg;
uint8_t *p = (uint8_t *) &msg;
int fd;
@@ -280,20 +241,35 @@ static void chr_read(void *opaque, const uint8_t *buf, int size)
return;
}
- g_mutex_lock(data_mutex);
+ g_mutex_lock(&s->data_mutex);
memcpy(p, buf, VHOST_USER_HDR_SIZE);
if (msg.size) {
p += VHOST_USER_HDR_SIZE;
- qemu_chr_fe_read_all(chr, p, msg.size);
+ g_assert_cmpint(qemu_chr_fe_read_all(chr, p, msg.size), ==, msg.size);
}
switch (msg.request) {
case VHOST_USER_GET_FEATURES:
/* send back features to qemu */
msg.flags |= VHOST_USER_REPLY_MASK;
- msg.size = sizeof(m.u64);
- msg.u64 = 0;
+ msg.size = sizeof(m.payload.u64);
+ msg.payload.u64 = 0x1ULL << VHOST_F_LOG_ALL |
+ 0x1ULL << VHOST_USER_F_PROTOCOL_FEATURES;
+ p = (uint8_t *) &msg;
+ qemu_chr_fe_write_all(chr, p, VHOST_USER_HDR_SIZE + msg.size);
+ break;
+
+ case VHOST_USER_SET_FEATURES:
+ g_assert_cmpint(msg.payload.u64 & (0x1ULL << VHOST_USER_F_PROTOCOL_FEATURES),
+ !=, 0ULL);
+ break;
+
+ case VHOST_USER_GET_PROTOCOL_FEATURES:
+ /* send back features to qemu */
+ msg.flags |= VHOST_USER_REPLY_MASK;
+ msg.size = sizeof(m.payload.u64);
+ msg.payload.u64 = 1 << VHOST_USER_PROTOCOL_F_LOG_SHMFD;
p = (uint8_t *) &msg;
qemu_chr_fe_write_all(chr, p, VHOST_USER_HDR_SIZE + msg.size);
break;
@@ -301,19 +277,22 @@ static void chr_read(void *opaque, const uint8_t *buf, int size)
case VHOST_USER_GET_VRING_BASE:
/* send back vring base to qemu */
msg.flags |= VHOST_USER_REPLY_MASK;
- msg.size = sizeof(m.state);
- msg.state.num = 0;
+ msg.size = sizeof(m.payload.state);
+ msg.payload.state.num = 0;
p = (uint8_t *) &msg;
qemu_chr_fe_write_all(chr, p, VHOST_USER_HDR_SIZE + msg.size);
+
+ assert(msg.payload.state.index < 2);
+ s->rings &= ~(0x1ULL << msg.payload.state.index);
break;
case VHOST_USER_SET_MEM_TABLE:
/* received the mem table */
- memcpy(&memory, &msg.memory, sizeof(msg.memory));
- fds_num = qemu_chr_fe_get_msgfds(chr, fds, sizeof(fds) / sizeof(int));
+ memcpy(&s->memory, &msg.payload.memory, sizeof(msg.payload.memory));
+ s->fds_num = qemu_chr_fe_get_msgfds(chr, s->fds, G_N_ELEMENTS(s->fds));
/* signal the test that it can continue */
- g_cond_signal(data_cond);
+ g_cond_signal(&s->data_cond);
break;
case VHOST_USER_SET_VRING_KICK:
@@ -327,23 +306,38 @@ static void chr_read(void *opaque, const uint8_t *buf, int size)
*/
qemu_set_nonblock(fd);
break;
+
+ case VHOST_USER_SET_LOG_BASE:
+ if (s->log_fd != -1) {
+ close(s->log_fd);
+ s->log_fd = -1;
+ }
+ qemu_chr_fe_get_msgfds(chr, &s->log_fd, 1);
+ msg.flags |= VHOST_USER_REPLY_MASK;
+ msg.size = 0;
+ p = (uint8_t *) &msg;
+ qemu_chr_fe_write_all(chr, p, VHOST_USER_HDR_SIZE);
+
+ g_cond_signal(&s->data_cond);
+ break;
+
+ case VHOST_USER_SET_VRING_BASE:
+ assert(msg.payload.state.index < 2);
+ s->rings |= 0x1ULL << msg.payload.state.index;
+ break;
+
default:
break;
}
- g_mutex_unlock(data_mutex);
+
+ g_mutex_unlock(&s->data_mutex);
}
-static const char *init_hugepagefs(void)
+static const char *init_hugepagefs(const char *path)
{
- const char *path;
struct statfs fs;
int ret;
- path = getenv("QTEST_HUGETLBFS_PATH");
- if (!path) {
- path = "/hugetlbfs";
- }
-
if (access(path, R_OK | W_OK | X_OK)) {
g_test_message("access on path (%s): %s\n", path, strerror(errno));
return NULL;
@@ -366,44 +360,294 @@ static const char *init_hugepagefs(void)
return path;
}
+static TestServer *test_server_new(const gchar *name)
+{
+ TestServer *server = g_new0(TestServer, 1);
+ gchar *chr_path;
+
+ server->socket_path = g_strdup_printf("%s/%s.sock", tmpfs, name);
+ server->mig_path = g_strdup_printf("%s/%s.mig", tmpfs, name);
+
+ chr_path = g_strdup_printf("unix:%s,server,nowait", server->socket_path);
+ server->chr_name = g_strdup_printf("chr-%s", name);
+ server->chr = qemu_chr_new(server->chr_name, chr_path, NULL);
+ g_free(chr_path);
+
+ qemu_chr_add_handlers(server->chr, chr_can_read, chr_read, NULL, server);
+
+ g_mutex_init(&server->data_mutex);
+ g_cond_init(&server->data_cond);
+
+ server->log_fd = -1;
+
+ return server;
+}
+
+#define GET_QEMU_CMD(s) \
+ g_strdup_printf(QEMU_CMD, 512, 512, (root), (s)->chr_name, \
+ (s)->socket_path, (s)->chr_name)
+
+#define GET_QEMU_CMDE(s, mem, extra, ...) \
+ g_strdup_printf(QEMU_CMD extra, (mem), (mem), (root), (s)->chr_name, \
+ (s)->socket_path, (s)->chr_name, ##__VA_ARGS__)
+
+static gboolean _test_server_free(TestServer *server)
+{
+ int i;
+
+ qemu_chr_delete(server->chr);
+
+ for (i = 0; i < server->fds_num; i++) {
+ close(server->fds[i]);
+ }
+
+ if (server->log_fd != -1) {
+ close(server->log_fd);
+ }
+
+ unlink(server->socket_path);
+ g_free(server->socket_path);
+
+ unlink(server->mig_path);
+ g_free(server->mig_path);
+
+ g_free(server->chr_name);
+ g_free(server);
+
+ return FALSE;
+}
+
+static void test_server_free(TestServer *server)
+{
+ g_idle_add((GSourceFunc)_test_server_free, server);
+}
+
+static void wait_for_log_fd(TestServer *s)
+{
+ gint64 end_time;
+
+ g_mutex_lock(&s->data_mutex);
+ end_time = g_get_monotonic_time() + 5 * G_TIME_SPAN_SECOND;
+ while (s->log_fd == -1) {
+ if (!g_cond_wait_until(&s->data_cond, &s->data_mutex, end_time)) {
+ /* timeout has passed */
+ g_assert(s->log_fd != -1);
+ break;
+ }
+ }
+
+ g_mutex_unlock(&s->data_mutex);
+}
+
+static void write_guest_mem(TestServer *s, uint32 seed)
+{
+ uint32_t *guest_mem;
+ int i, j;
+ size_t size;
+
+ wait_for_fds(s);
+
+ /* iterate all regions */
+ for (i = 0; i < s->fds_num; i++) {
+
+ /* We'll write only the region statring at 0x0 */
+ if (s->memory.regions[i].guest_phys_addr != 0x0) {
+ continue;
+ }
+
+ g_assert_cmpint(s->memory.regions[i].memory_size, >, 1024);
+
+ size = s->memory.regions[i].memory_size +
+ s->memory.regions[i].mmap_offset;
+
+ guest_mem = mmap(0, size, PROT_READ | PROT_WRITE,
+ MAP_SHARED, s->fds[i], 0);
+
+ g_assert(guest_mem != MAP_FAILED);
+ guest_mem += (s->memory.regions[i].mmap_offset / sizeof(*guest_mem));
+
+ for (j = 0; j < 256; j++) {
+ guest_mem[j] = seed + j;
+ }
+
+ munmap(guest_mem, s->memory.regions[i].memory_size);
+ break;
+ }
+}
+
+static guint64 get_log_size(TestServer *s)
+{
+ guint64 log_size = 0;
+ int i;
+
+ for (i = 0; i < s->memory.nregions; ++i) {
+ VhostUserMemoryRegion *reg = &s->memory.regions[i];
+ guint64 last = range_get_last(reg->guest_phys_addr,
+ reg->memory_size);
+ log_size = MAX(log_size, last / (8 * VHOST_LOG_PAGE) + 1);
+ }
+
+ return log_size;
+}
+
+typedef struct TestMigrateSource {
+ GSource source;
+ TestServer *src;
+ TestServer *dest;
+} TestMigrateSource;
+
+static gboolean
+test_migrate_source_check(GSource *source)
+{
+ TestMigrateSource *t = (TestMigrateSource *)source;
+ gboolean overlap = t->src->rings && t->dest->rings;
+
+ g_assert(!overlap);
+
+ return FALSE;
+}
+
+#if !GLIB_CHECK_VERSION(2,36,0)
+/* this callback is unnecessary with glib >2.36, the default
+ * prepare for the source does the same */
+static gboolean
+test_migrate_source_prepare(GSource *source, gint *timeout)
+{
+ *timeout = -1;
+ return FALSE;
+}
+#endif
+
+GSourceFuncs test_migrate_source_funcs = {
+#if !GLIB_CHECK_VERSION(2,36,0)
+ .prepare = test_migrate_source_prepare,
+#endif
+ .check = test_migrate_source_check,
+};
+
+static void test_migrate(void)
+{
+ TestServer *s = test_server_new("src");
+ TestServer *dest = test_server_new("dest");
+ char *uri = g_strdup_printf("%s%s", "unix:", dest->mig_path);
+ QTestState *global = global_qtest, *from, *to;
+ GSource *source;
+ gchar *cmd;
+ QDict *rsp;
+ guint8 *log;
+ guint64 size;
+
+ cmd = GET_QEMU_CMDE(s, 2, "");
+ from = qtest_start(cmd);
+ g_free(cmd);
+
+ wait_for_fds(s);
+ size = get_log_size(s);
+ g_assert_cmpint(size, ==, (2 * 1024 * 1024) / (VHOST_LOG_PAGE * 8));
+
+ cmd = GET_QEMU_CMDE(dest, 2, " -incoming %s", uri);
+ to = qtest_init(cmd);
+ g_free(cmd);
+
+ source = g_source_new(&test_migrate_source_funcs,
+ sizeof(TestMigrateSource));
+ ((TestMigrateSource *)source)->src = s;
+ ((TestMigrateSource *)source)->dest = dest;
+ g_source_attach(source, NULL);
+
+ /* slow down migration to have time to fiddle with log */
+ /* TODO: qtest could learn to break on some places */
+ rsp = qmp("{ 'execute': 'migrate_set_speed',"
+ "'arguments': { 'value': 10 } }");
+ g_assert(qdict_haskey(rsp, "return"));
+ QDECREF(rsp);
+
+ cmd = g_strdup_printf("{ 'execute': 'migrate',"
+ "'arguments': { 'uri': '%s' } }",
+ uri);
+ rsp = qmp(cmd);
+ g_free(cmd);
+ g_assert(qdict_haskey(rsp, "return"));
+ QDECREF(rsp);
+
+ wait_for_log_fd(s);
+
+ log = mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, s->log_fd, 0);
+ g_assert(log != MAP_FAILED);
+
+ /* modify first page */
+ write_guest_mem(s, 0x42);
+ log[0] = 1;
+ munmap(log, size);
+
+ /* speed things up */
+ rsp = qmp("{ 'execute': 'migrate_set_speed',"
+ "'arguments': { 'value': 0 } }");
+ g_assert(qdict_haskey(rsp, "return"));
+ QDECREF(rsp);
+
+ qmp_eventwait("STOP");
+
+ global_qtest = to;
+ qmp_eventwait("RESUME");
+
+ read_guest_mem(dest);
+
+ g_source_destroy(source);
+ g_source_unref(source);
+
+ qtest_quit(to);
+ test_server_free(dest);
+ qtest_quit(from);
+ test_server_free(s);
+ g_free(uri);
+
+ global_qtest = global;
+}
+
int main(int argc, char **argv)
{
QTestState *s = NULL;
- CharDriverState *chr = NULL;
- const char *hugefs = 0;
- char *socket_path = 0;
- char *qemu_cmd = 0;
- char *chr_path = 0;
+ TestServer *server = NULL;
+ const char *hugefs;
+ char *qemu_cmd = NULL;
int ret;
+ char template[] = "/tmp/vhost-test-XXXXXX";
+ GMainLoop *loop;
+ GThread *thread;
g_test_init(&argc, &argv, NULL);
module_call_init(MODULE_INIT_QOM);
+ qemu_add_opts(&qemu_chardev_opts);
- hugefs = init_hugepagefs();
- if (!hugefs) {
- return 0;
+ tmpfs = mkdtemp(template);
+ if (!tmpfs) {
+ g_test_message("mkdtemp on path (%s): %s\n", template, strerror(errno));
+ }
+ g_assert(tmpfs);
+
+ hugefs = getenv("QTEST_HUGETLBFS_PATH");
+ if (hugefs) {
+ root = init_hugepagefs(hugefs);
+ g_assert(root);
+ } else {
+ root = tmpfs;
}
- socket_path = g_strdup_printf("/tmp/vhost-%d.sock", getpid());
-
- /* create char dev and add read handlers */
- qemu_add_opts(&qemu_chardev_opts);
- chr_path = g_strdup_printf("unix:%s,server,nowait", socket_path);
- chr = qemu_chr_new("chr0", chr_path, NULL);
- g_free(chr_path);
- qemu_chr_add_handlers(chr, chr_can_read, chr_read, NULL, chr);
+ server = test_server_new("test");
+ loop = g_main_loop_new(NULL, FALSE);
/* run the main loop thread so the chardev may operate */
- data_mutex = _mutex_new();
- data_cond = _cond_new();
- _thread_new(NULL, thread_function, NULL);
+ thread = g_thread_new(NULL, thread_function, loop);
+
+ qemu_cmd = GET_QEMU_CMD(server);
- qemu_cmd = g_strdup_printf(QEMU_CMD, hugefs, socket_path);
s = qtest_start(qemu_cmd);
g_free(qemu_cmd);
- qtest_add_func("/vhost-user/read-guest-mem", read_guest_mem);
+ qtest_add_data_func("/vhost-user/read-guest-mem", server, read_guest_mem);
+ qtest_add_func("/vhost-user/migrate", test_migrate);
ret = g_test_run();
@@ -412,10 +656,22 @@ int main(int argc, char **argv)
}
/* cleanup */
- unlink(socket_path);
- g_free(socket_path);
- _cond_free(data_cond);
- _mutex_free(data_mutex);
+ test_server_free(server);
+
+ /* finish the helper thread and dispatch pending sources */
+ g_main_loop_quit(loop);
+ g_thread_join(thread);
+ while (g_main_context_pending(NULL)) {
+ g_main_context_iteration (NULL, TRUE);
+ }
+ g_main_loop_unref(loop);
+
+ ret = rmdir(tmpfs);
+ if (ret != 0) {
+ g_test_message("unable to rmdir: path (%s): %s\n",
+ tmpfs, strerror(errno));
+ }
+ g_assert_cmpint(ret, ==, 0);
return ret;
}
diff --git a/tests/virtio-net-test.c b/tests/virtio-net-test.c
index ea7478c27..982d77a14 100644
--- a/tests/virtio-net-test.c
+++ b/tests/virtio-net-test.c
@@ -10,20 +10,242 @@
#include <glib.h>
#include <string.h>
#include "libqtest.h"
+#include "qemu-common.h"
+#include "qemu/sockets.h"
#include "qemu/osdep.h"
-#include "libqos/pci.h"
+#include "qemu/iov.h"
+#include "libqos/pci-pc.h"
+#include "libqos/virtio.h"
+#include "libqos/virtio-pci.h"
+#include "libqos/malloc.h"
+#include "libqos/malloc-pc.h"
+#include "libqos/malloc-generic.h"
+#include "qemu/bswap.h"
+#include "hw/virtio/virtio-net.h"
#define PCI_SLOT_HP 0x06
+#define PCI_SLOT 0x04
+#define PCI_FN 0x00
-/* Tests only initialization so far. TODO: Replace with functional tests */
-static void pci_nop(void)
+#define QVIRTIO_NET_TIMEOUT_US (30 * 1000 * 1000)
+#define VNET_HDR_SIZE sizeof(struct virtio_net_hdr_mrg_rxbuf)
+
+static void test_end(void)
+{
+ qtest_end();
+}
+
+#ifndef _WIN32
+
+static QVirtioPCIDevice *virtio_net_pci_init(QPCIBus *bus, int slot)
+{
+ QVirtioPCIDevice *dev;
+
+ dev = qvirtio_pci_device_find(bus, QVIRTIO_NET_DEVICE_ID);
+ g_assert(dev != NULL);
+ g_assert_cmphex(dev->vdev.device_type, ==, QVIRTIO_NET_DEVICE_ID);
+
+ qvirtio_pci_device_enable(dev);
+ qvirtio_reset(&qvirtio_pci, &dev->vdev);
+ qvirtio_set_acknowledge(&qvirtio_pci, &dev->vdev);
+ qvirtio_set_driver(&qvirtio_pci, &dev->vdev);
+
+ return dev;
+}
+
+static QPCIBus *pci_test_start(int socket)
+{
+ char *cmdline;
+
+ cmdline = g_strdup_printf("-netdev socket,fd=%d,id=hs0 -device "
+ "virtio-net-pci,netdev=hs0", socket);
+ qtest_start(cmdline);
+ g_free(cmdline);
+
+ return qpci_init_pc();
+}
+
+static void driver_init(const QVirtioBus *bus, QVirtioDevice *dev)
+{
+ uint32_t features;
+
+ features = qvirtio_get_features(bus, dev);
+ features = features & ~(QVIRTIO_F_BAD_FEATURE |
+ QVIRTIO_F_RING_INDIRECT_DESC |
+ QVIRTIO_F_RING_EVENT_IDX);
+ qvirtio_set_features(bus, dev, features);
+
+ qvirtio_set_driver_ok(bus, dev);
+}
+
+static void rx_test(const QVirtioBus *bus, QVirtioDevice *dev,
+ QGuestAllocator *alloc, QVirtQueue *vq,
+ int socket)
+{
+ uint64_t req_addr;
+ uint32_t free_head;
+ char test[] = "TEST";
+ char buffer[64];
+ int len = htonl(sizeof(test));
+ struct iovec iov[] = {
+ {
+ .iov_base = &len,
+ .iov_len = sizeof(len),
+ }, {
+ .iov_base = test,
+ .iov_len = sizeof(test),
+ },
+ };
+ int ret;
+
+ req_addr = guest_alloc(alloc, 64);
+
+ free_head = qvirtqueue_add(vq, req_addr, 64, true, false);
+ qvirtqueue_kick(bus, dev, vq, free_head);
+
+ ret = iov_send(socket, iov, 2, 0, sizeof(len) + sizeof(test));
+ g_assert_cmpint(ret, ==, sizeof(test) + sizeof(len));
+
+ qvirtio_wait_queue_isr(bus, dev, vq, QVIRTIO_NET_TIMEOUT_US);
+ memread(req_addr + VNET_HDR_SIZE, buffer, sizeof(test));
+ g_assert_cmpstr(buffer, ==, "TEST");
+
+ guest_free(alloc, req_addr);
+}
+
+static void tx_test(const QVirtioBus *bus, QVirtioDevice *dev,
+ QGuestAllocator *alloc, QVirtQueue *vq,
+ int socket)
+{
+ uint64_t req_addr;
+ uint32_t free_head;
+ uint32_t len;
+ char buffer[64];
+ int ret;
+
+ req_addr = guest_alloc(alloc, 64);
+ memwrite(req_addr + VNET_HDR_SIZE, "TEST", 4);
+
+ free_head = qvirtqueue_add(vq, req_addr, 64, false, false);
+ qvirtqueue_kick(bus, dev, vq, free_head);
+
+ qvirtio_wait_queue_isr(bus, dev, vq, QVIRTIO_NET_TIMEOUT_US);
+ guest_free(alloc, req_addr);
+
+ ret = qemu_recv(socket, &len, sizeof(len), 0);
+ g_assert_cmpint(ret, ==, sizeof(len));
+ len = ntohl(len);
+
+ ret = qemu_recv(socket, buffer, len, 0);
+ g_assert_cmpstr(buffer, ==, "TEST");
+}
+
+static void rx_stop_cont_test(const QVirtioBus *bus, QVirtioDevice *dev,
+ QGuestAllocator *alloc, QVirtQueue *vq,
+ int socket)
+{
+ uint64_t req_addr;
+ uint32_t free_head;
+ char test[] = "TEST";
+ char buffer[64];
+ int len = htonl(sizeof(test));
+ struct iovec iov[] = {
+ {
+ .iov_base = &len,
+ .iov_len = sizeof(len),
+ }, {
+ .iov_base = test,
+ .iov_len = sizeof(test),
+ },
+ };
+ int ret;
+
+ req_addr = guest_alloc(alloc, 64);
+
+ free_head = qvirtqueue_add(vq, req_addr, 64, true, false);
+ qvirtqueue_kick(bus, dev, vq, free_head);
+
+ qmp("{ 'execute' : 'stop'}");
+
+ ret = iov_send(socket, iov, 2, 0, sizeof(len) + sizeof(test));
+ g_assert_cmpint(ret, ==, sizeof(test) + sizeof(len));
+
+ /* We could check the status, but this command is more importantly to
+ * ensure the packet data gets queued in QEMU, before we do 'cont'.
+ */
+ qmp("{ 'execute' : 'query-status'}");
+ qmp("{ 'execute' : 'cont'}");
+
+ qvirtio_wait_queue_isr(bus, dev, vq, QVIRTIO_NET_TIMEOUT_US);
+ memread(req_addr + VNET_HDR_SIZE, buffer, sizeof(test));
+ g_assert_cmpstr(buffer, ==, "TEST");
+
+ guest_free(alloc, req_addr);
+}
+
+static void send_recv_test(const QVirtioBus *bus, QVirtioDevice *dev,
+ QGuestAllocator *alloc, QVirtQueue *rvq,
+ QVirtQueue *tvq, int socket)
{
+ rx_test(bus, dev, alloc, rvq, socket);
+ tx_test(bus, dev, alloc, tvq, socket);
}
+static void stop_cont_test(const QVirtioBus *bus, QVirtioDevice *dev,
+ QGuestAllocator *alloc, QVirtQueue *rvq,
+ QVirtQueue *tvq, int socket)
+{
+ rx_stop_cont_test(bus, dev, alloc, rvq, socket);
+}
+
+static void pci_basic(gconstpointer data)
+{
+ QVirtioPCIDevice *dev;
+ QPCIBus *bus;
+ QVirtQueuePCI *tx, *rx;
+ QGuestAllocator *alloc;
+ void (*func) (const QVirtioBus *bus,
+ QVirtioDevice *dev,
+ QGuestAllocator *alloc,
+ QVirtQueue *rvq,
+ QVirtQueue *tvq,
+ int socket) = data;
+ int sv[2], ret;
+
+ ret = socketpair(PF_UNIX, SOCK_STREAM, 0, sv);
+ g_assert_cmpint(ret, !=, -1);
+
+ bus = pci_test_start(sv[1]);
+ dev = virtio_net_pci_init(bus, PCI_SLOT);
+
+ alloc = pc_alloc_init();
+ rx = (QVirtQueuePCI *)qvirtqueue_setup(&qvirtio_pci, &dev->vdev,
+ alloc, 0);
+ tx = (QVirtQueuePCI *)qvirtqueue_setup(&qvirtio_pci, &dev->vdev,
+ alloc, 1);
+
+ driver_init(&qvirtio_pci, &dev->vdev);
+ func(&qvirtio_pci, &dev->vdev, alloc, &rx->vq, &tx->vq, sv[0]);
+
+ /* End test */
+ close(sv[0]);
+ guest_free(alloc, tx->vq.desc);
+ pc_alloc_uninit(alloc);
+ qvirtio_pci_device_disable(dev);
+ g_free(dev);
+ qpci_free_pc(bus);
+ test_end();
+}
+#endif
+
static void hotplug(void)
{
+ qtest_start("-device virtio-net-pci");
+
qpci_plug_device_test("virtio-net-pci", "net1", PCI_SLOT_HP, NULL);
qpci_unplug_acpi_device_test("net1", PCI_SLOT_HP);
+
+ test_end();
}
int main(int argc, char **argv)
@@ -31,13 +253,14 @@ int main(int argc, char **argv)
int ret;
g_test_init(&argc, &argv, NULL);
- qtest_add_func("/virtio/net/pci/nop", pci_nop);
+#ifndef _WIN32
+ qtest_add_data_func("/virtio/net/pci/basic", send_recv_test, pci_basic);
+ qtest_add_data_func("/virtio/net/pci/rx_stop_cont",
+ stop_cont_test, pci_basic);
+#endif
qtest_add_func("/virtio/net/pci/hotplug", hotplug);
- qtest_start("-device virtio-net-pci");
ret = g_test_run();
- qtest_end();
-
return ret;
}
diff --git a/tests/virtio-scsi-test.c b/tests/virtio-scsi-test.c
index 11ccdd632..66d8491e9 100644
--- a/tests/virtio-scsi-test.c
+++ b/tests/virtio-scsi-test.c
@@ -13,6 +13,7 @@
#include "libqtest.h"
#include "qemu/osdep.h"
#include <stdio.h>
+#include "block/scsi.h"
#include "libqos/virtio.h"
#include "libqos/virtio-pci.h"
#include "libqos/pci-pc.h"
@@ -71,40 +72,6 @@ static void qvirtio_scsi_stop(void)
qtest_end();
}
-static QVirtIOSCSI *qvirtio_scsi_pci_init(int slot)
-{
- QVirtIOSCSI *vs;
- QVirtioPCIDevice *dev;
- void *addr;
- int i;
-
- vs = g_new0(QVirtIOSCSI, 1);
- vs->alloc = pc_alloc_init();
- vs->bus = qpci_init_pc();
-
- dev = qvirtio_pci_device_find(vs->bus, QVIRTIO_SCSI_DEVICE_ID);
- vs->dev = (QVirtioDevice *)dev;
- g_assert(dev != NULL);
- g_assert_cmphex(vs->dev->device_type, ==, QVIRTIO_SCSI_DEVICE_ID);
-
- qvirtio_pci_device_enable(dev);
- qvirtio_reset(&qvirtio_pci, vs->dev);
- qvirtio_set_acknowledge(&qvirtio_pci, vs->dev);
- qvirtio_set_driver(&qvirtio_pci, vs->dev);
-
- addr = dev->addr + QVIRTIO_PCI_DEVICE_SPECIFIC_NO_MSIX;
- vs->num_queues = qvirtio_config_readl(&qvirtio_pci, vs->dev,
- (uint64_t)(uintptr_t)addr);
-
- g_assert_cmpint(vs->num_queues, <, MAX_NUM_QUEUES);
-
- for (i = 0; i < vs->num_queues + 2; i++) {
- vs->vq[i] = qvirtqueue_setup(&qvirtio_pci, vs->dev, vs->alloc, i);
- }
-
- return vs;
-}
-
static void qvirtio_scsi_pci_free(QVirtIOSCSI *vs)
{
int i;
@@ -134,7 +101,8 @@ static uint64_t qvirtio_scsi_alloc(QVirtIOSCSI *vs, size_t alloc_size,
static uint8_t virtio_scsi_do_command(QVirtIOSCSI *vs, const uint8_t *cdb,
const uint8_t *data_in,
size_t data_in_len,
- uint8_t *data_out, size_t data_out_len)
+ uint8_t *data_out, size_t data_out_len,
+ QVirtIOSCSICmdResp *resp_out)
{
QVirtQueue *vq;
QVirtIOSCSICmdReq req = { { 0 } };
@@ -174,6 +142,10 @@ static uint8_t virtio_scsi_do_command(QVirtIOSCSI *vs, const uint8_t *cdb,
response = readb(resp_addr + offsetof(QVirtIOSCSICmdResp, response));
+ if (resp_out) {
+ memread(resp_addr, resp_out, sizeof(*resp_out));
+ }
+
guest_free(vs->alloc, req_addr);
guest_free(vs->alloc, resp_addr);
guest_free(vs->alloc, data_in_addr);
@@ -181,6 +153,52 @@ static uint8_t virtio_scsi_do_command(QVirtIOSCSI *vs, const uint8_t *cdb,
return response;
}
+static QVirtIOSCSI *qvirtio_scsi_pci_init(int slot)
+{
+ const uint8_t test_unit_ready_cdb[CDB_SIZE] = {};
+ QVirtIOSCSI *vs;
+ QVirtioPCIDevice *dev;
+ QVirtIOSCSICmdResp resp;
+ void *addr;
+ int i;
+
+ vs = g_new0(QVirtIOSCSI, 1);
+ vs->alloc = pc_alloc_init();
+ vs->bus = qpci_init_pc();
+
+ dev = qvirtio_pci_device_find(vs->bus, QVIRTIO_SCSI_DEVICE_ID);
+ vs->dev = (QVirtioDevice *)dev;
+ g_assert(dev != NULL);
+ g_assert_cmphex(vs->dev->device_type, ==, QVIRTIO_SCSI_DEVICE_ID);
+
+ qvirtio_pci_device_enable(dev);
+ qvirtio_reset(&qvirtio_pci, vs->dev);
+ qvirtio_set_acknowledge(&qvirtio_pci, vs->dev);
+ qvirtio_set_driver(&qvirtio_pci, vs->dev);
+
+ addr = dev->addr + QVIRTIO_PCI_DEVICE_SPECIFIC_NO_MSIX;
+ vs->num_queues = qvirtio_config_readl(&qvirtio_pci, vs->dev,
+ (uint64_t)(uintptr_t)addr);
+
+ g_assert_cmpint(vs->num_queues, <, MAX_NUM_QUEUES);
+
+ for (i = 0; i < vs->num_queues + 2; i++) {
+ vs->vq[i] = qvirtqueue_setup(&qvirtio_pci, vs->dev, vs->alloc, i);
+ }
+
+ /* Clear the POWER ON OCCURRED unit attention */
+ g_assert_cmpint(virtio_scsi_do_command(vs, test_unit_ready_cdb,
+ NULL, 0, NULL, 0, &resp),
+ ==, 0);
+ g_assert_cmpint(resp.status, ==, CHECK_CONDITION);
+ g_assert_cmpint(resp.sense[0], ==, 0x70); /* Fixed format sense buffer */
+ g_assert_cmpint(resp.sense[2], ==, UNIT_ATTENTION);
+ g_assert_cmpint(resp.sense[12], ==, 0x29); /* POWER ON */
+ g_assert_cmpint(resp.sense[13], ==, 0x00);
+
+ return vs;
+}
+
/* Tests only initialization so far. TODO: Replace with functional tests */
static void pci_nop(void)
{
@@ -221,9 +239,12 @@ static void hotplug(void)
static void test_unaligned_write_same(void)
{
QVirtIOSCSI *vs;
- uint8_t buf[512] = { 0 };
- const uint8_t write_same_cdb[CDB_SIZE] = { 0x41, 0x00, 0x00, 0x00, 0x00,
+ uint8_t buf1[512] = { 0 };
+ uint8_t buf2[512] = { 1 };
+ const uint8_t write_same_cdb_1[CDB_SIZE] = { 0x41, 0x00, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x02, 0x00 };
+ const uint8_t write_same_cdb_2[CDB_SIZE] = { 0x41, 0x00, 0x00, 0x00, 0x00,
+ 0x01, 0x00, 0x33, 0x00, 0x00 };
qvirtio_scsi_start("-drive file=blkdebug::null-co://,if=none,id=dr1"
",format=raw,file.align=4k "
@@ -231,7 +252,10 @@ static void test_unaligned_write_same(void)
vs = qvirtio_scsi_pci_init(PCI_SLOT);
g_assert_cmphex(0, ==,
- virtio_scsi_do_command(vs, write_same_cdb, NULL, 0, buf, 512));
+ virtio_scsi_do_command(vs, write_same_cdb_1, NULL, 0, buf1, 512, NULL));
+
+ g_assert_cmphex(0, ==,
+ virtio_scsi_do_command(vs, write_same_cdb_2, NULL, 0, buf2, 512, NULL));
qvirtio_scsi_pci_free(vs);
qvirtio_scsi_stop();